@lunora/codegen 1.0.0-alpha.294 → 1.0.0-alpha.296

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 CHANGED
@@ -3105,12 +3105,12 @@ declare const platformMatrixIds: () => ReadonlyArray<string>;
3105
3105
  interface PlatformDiagnostic {
3106
3106
  /** The codegen capability this concerns, when it is feature-specific. */
3107
3107
  feature?: CapabilityKey;
3108
- /** Severity. All three names are errors — each drops or misdirects an emitted surface. */
3108
+ /** Severity. Error when the emitted surface would be wrong; warn when codegen fell back to a default or can only suspect a deploy failure. */
3109
3109
  level: "error" | "warn";
3110
3110
  /** Human-readable explanation of the gap. */
3111
3111
  message: string;
3112
- /** The lint id: `platform_unsupported_feature`, `platform_undeclared_feature`, or `platform_unknown_target`. */
3113
- name: "platform_undeclared_feature" | "platform_unknown_target" | "platform_unreadable_target" | "platform_unsupported_feature";
3112
+ /** The lint id: `platform_unsupported_feature`, `platform_undeclared_feature`, `platform_unknown_target`, `platform_unreadable_target` or `platform_vector_dimensions_out_of_range`. */
3113
+ name: "platform_undeclared_feature" | "platform_unknown_target" | "platform_unreadable_target" | "platform_unsupported_feature" | "platform_vector_dimensions_out_of_range";
3114
3114
  /** How to resolve it. */
3115
3115
  remediation: string;
3116
3116
  /** The requested deploy target. */
package/dist/index.d.ts CHANGED
@@ -3105,12 +3105,12 @@ declare const platformMatrixIds: () => ReadonlyArray<string>;
3105
3105
  interface PlatformDiagnostic {
3106
3106
  /** The codegen capability this concerns, when it is feature-specific. */
3107
3107
  feature?: CapabilityKey;
3108
- /** Severity. All three names are errors — each drops or misdirects an emitted surface. */
3108
+ /** Severity. Error when the emitted surface would be wrong; warn when codegen fell back to a default or can only suspect a deploy failure. */
3109
3109
  level: "error" | "warn";
3110
3110
  /** Human-readable explanation of the gap. */
3111
3111
  message: string;
3112
- /** The lint id: `platform_unsupported_feature`, `platform_undeclared_feature`, or `platform_unknown_target`. */
3113
- name: "platform_undeclared_feature" | "platform_unknown_target" | "platform_unreadable_target" | "platform_unsupported_feature";
3112
+ /** The lint id: `platform_unsupported_feature`, `platform_undeclared_feature`, `platform_unknown_target`, `platform_unreadable_target` or `platform_vector_dimensions_out_of_range`. */
3113
+ name: "platform_undeclared_feature" | "platform_unknown_target" | "platform_unreadable_target" | "platform_unsupported_feature" | "platform_vector_dimensions_out_of_range";
3114
3114
  /** How to resolve it. */
3115
3115
  remediation: string;
3116
3116
  /** The requested deploy target. */
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 f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,errorPlatformDiagnosticNames as c,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bk0u9QUu.mjs";import{default as P}from"./packem_shared/discoverCrons-DF7dOP9x.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs";import{default as W}from"./packem_shared/discoverFunctions-DaEZl3uE.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-C_u9YiFb.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-BUrA_96X.mjs";import{default as w}from"./packem_shared/discoverInserts-OT_fiEGq.mjs";import{d as Y}from"./packem_shared/index-BW4hJ4Wm.mjs";import{default as Z}from"./packem_shared/discoverMigrations-C9mLIhGZ.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-Bw0YtaO8.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-9ZDpRptb.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyChannels as me,discoverNotifyConfig as fe}from"./packem_shared/NOTIFY_FILENAME-CPjbiHQl.mjs";import{default as pe}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-C8V4cMIP.mjs";import{QUEUES_FILENAME as xe,discoverQueues as Se}from"./packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs";import{default as ue}from"./packem_shared/discoverR2sqlCalls-COKmDnih.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-CuRLSnf9.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Cb8JR1b4.mjs";import{discoverSandboxUsage as Oe}from"./packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs";import{default as Te}from"./packem_shared/discoverSchema-Btu1KpBX.mjs";import{readServiceBindings as Ie,resolveServiceBindings as _e}from"./packem_shared/readServiceBindings-DvqIThzd.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Fe}from"./packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs";import{default as De}from"./packem_shared/discoverStorageRulesMetadata-BPJplDfz.mjs";import{WORKFLOWS_FILENAME as ye,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-CQR8fE9B.mjs";import{emitApp as He}from"./packem_shared/emitApp-DAZCUDbr.mjs";import{isD1GlobalTable as Be,isHyperdriveGlobalTable as ke}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DFv-RYZU.mjs";import{OPENRPC_VERSION as qe,buildOpenRpcDocument as we,emitOpenRpc as Je,emitOpenRpcModule as Ye}from"./packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs";import{DEFAULT_TARGET as Ze,platformMatrixIds as $e,readProjectTarget as er,resolveCodegenTarget as rr}from"./packem_shared/DEFAULT_TARGET-3U7x981M.mjs";import{l as tr,r as sr}from"./packem_shared/project-config-file-BV7RR-l6.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ir,runCodegen as mr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BN_EhAiC.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as pr,evaluateSchemaDrift as nr,parseSchemaSnapshot as lr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as xr}from"./packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Ar,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Nr,SDK_TARGETS as gr,generateSdk as Or}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as Tr,secretKindOf as hr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-CpOGYfyl.mjs";import{default as Mr}from"./packem_shared/emitFunctions-BeKgL3dl.mjs";import{e as Pr}from"./packem_shared/server-DAvi_bv_.mjs";import{e as br}from"./packem_shared/shard-Ct-49zW9.mjs";import{G as Ur}from"./packem_shared/shared-DnCokNcE.mjs";import{MESSAGE_SOLUTIONS as Hr,findSolutionByMessage as jr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as kr,findProjectConfigFile as Wr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{createCodegenProject as Vr,findTsconfig as zr,refreshCodegenProject as Qr}from"./packem_shared/createCodegenProject-V51_yBw3.mjs";import{s as wr,t as Jr,u as Yr}from"./packem_shared/shard-runtime-BX0xmo0P.mjs";import{emitApi as Zr,emitCollections as $r,emitInternalApi as eo}from"./packem_shared/emitApi-Zx6VPN-7.mjs";import{emitCrons as oo,emitScheduler as to,emitVectors as so,emitWranglerCronTriggers as ao}from"./packem_shared/emitCrons-BQW2lviZ.mjs";import{emitDataModel as mo}from"./packem_shared/emitDataModel-DdtjdNg3.mjs";import{isTypedSchema as po}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{N as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Ze as DEFAULT_TARGET,j as FLAGS_FILENAME,Ur as GENERATED_HEADER,Ar as LUNORA_ERROR_CODES,Hr as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,qe as OPENRPC_VERSION,kr as PROJECT_CONFIG_FILENAMES,xe as QUEUES_FILENAME,ir as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Nr as SDK_LANGUAGES,gr as SDK_TARGETS,Me as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,ye as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,we as buildOpenRpcDocument,pr as buildSchemaSnapshot,b as capabilitiesUsedBy,Vr as createCodegenProject,n as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,g as discoverAgents,I as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyChannels,fe as discoverNotifyConfig,le as discoverQueries,Se as discoverQueues,ue as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Oe as discoverSandboxUsage,Te as discoverSchema,Fe as discoverShapes,De as discoverStorageRulesMetadata,Ue as discoverWorkflows,wr as emitAgents,Zr as emitApi,He as emitApp,$r as emitCollections,Jr as emitContainers,oo as emitCrons,mo as emitDataModel,_r as emitDrizzleSchema,Mr as emitFunctions,eo as emitInternalApi,Ve as emitOpenApi,ze as emitOpenApiModule,Je as emitOpenRpc,Ye as emitOpenRpcModule,to as emitScheduler,Pr as emitServer,br as emitShard,so as emitVectors,Yr as emitWorkflows,ao as emitWranglerCronTriggers,l as errorAdvisoryNames,c as errorPlatformDiagnosticNames,nr as evaluateSchemaDrift,jr as findLunoraSolution,Wr as findProjectConfigFile,zr as findTsconfig,xr as fingerprintSchemaSources,y as foldCapabilitySignals,m as formatAdvisories,Or as generateSdk,Be as isD1GlobalTable,ke as isHyperdriveGlobalTable,R as isTestPath,po as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,tr as loadProjectConfig,U as mayReadCapabilityContext,lr as parseSchemaSnapshot,$e as platformMatrixIds,pe as readPackageDependencies,sr as readProjectConfigLiterals,er as readProjectTarget,Ie as readServiceBindings,Tr as redact,Qr as refreshCodegenProject,rr as resolveCodegenTarget,_e as resolveServiceBindings,mr as runCodegen,Er as schemaFromIr,hr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,d as toAdvisorContext,vr as validatorIrToJsonSchema};
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 f,toAdvisorContext as d}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as n,errorAdvisoryNames as l,errorPlatformDiagnosticNames as c,sortedUniqueNames as x}from"./packem_shared/describeErrorLevelFindings-vzaGS9KL.mjs";import{CAPABILITY_PROBES as E}from"./packem_shared/CAPABILITY_PROBES-brcmKenl.mjs";import{CodegenDiagnosticError as A,diagnosticAt as v}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as N,discoverAgents as g}from"./packem_shared/AGENTS_FILENAME-B6-kjzM3.mjs";import{isTestPath as R,listLunoraSourceFiles as T}from"./packem_shared/isTestPath-B81lOULB.mjs";import{default as I}from"./packem_shared/discoverAuthApiCalls-xs0ONfI-.mjs";import{CONTAINERS_FILENAME as L,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-Bk0u9QUu.mjs";import{default as P}from"./packem_shared/discoverCrons-DF7dOP9x.mjs";import{capabilitiesUsedBy as b,foldCapabilitySignals as y,mayReadCapabilityContext as U,sourceCapabilitySignals as G}from"./packem_shared/capabilitiesUsedBy-QgSZyE0T.mjs";import{FLAGS_FILENAME as j,discoverFlags as B}from"./packem_shared/FLAGS_FILENAME-Bf0MSlHH.mjs";import{default as W}from"./packem_shared/discoverFunctions-DaEZl3uE.mjs";import{default as V}from"./packem_shared/discoverHttpRoutes-C_u9YiFb.mjs";import{default as Q}from"./packem_shared/discoverHyperdriveCalls-BUrA_96X.mjs";import{default as w}from"./packem_shared/discoverInserts-OT_fiEGq.mjs";import{d as Y}from"./packem_shared/index-DZZpHXMv.mjs";import{default as Z}from"./packem_shared/discoverMigrations-C9mLIhGZ.mjs";import{MUTATORS_FILENAME as ee,discoverMutators as re}from"./packem_shared/MUTATORS_FILENAME-Bw0YtaO8.mjs";import{default as te}from"./packem_shared/discoverNondeterministicCalls-9ZDpRptb.mjs";import{NOTIFY_FILENAME as ae,discoverNotifyCalls as ie,discoverNotifyChannels as me,discoverNotifyConfig as fe}from"./packem_shared/NOTIFY_FILENAME-CPjbiHQl.mjs";import{default as pe}from"./packem_shared/readPackageDependencies-RHhGiz0k.mjs";import{default as le}from"./packem_shared/discoverQueries-C8V4cMIP.mjs";import{QUEUES_FILENAME as xe,discoverQueues as Se}from"./packem_shared/QUEUES_FILENAME-CsRy4VTF.mjs";import{default as ue}from"./packem_shared/discoverR2sqlCalls-COKmDnih.mjs";import{default as ve}from"./packem_shared/discoverRlsProcedures-BlUd32bU.mjs";import{default as Ne}from"./packem_shared/discoverRlsMetadata-Cb8JR1b4.mjs";import{discoverSandboxUsage as Oe}from"./packem_shared/discoverSandboxUsage-w6Q3RvxZ.mjs";import{default as Te}from"./packem_shared/discoverSchema-rxbrQztG.mjs";import{readServiceBindings as Ie,resolveServiceBindings as _e}from"./packem_shared/readServiceBindings-DvqIThzd.mjs";import{SHAPES_FILENAME as Me,discoverShapes as Fe}from"./packem_shared/SHAPES_FILENAME-DkBUN9dK.mjs";import{default as De}from"./packem_shared/discoverStorageRulesMetadata-BPJplDfz.mjs";import{WORKFLOWS_FILENAME as ye,discoverWorkflows as Ue}from"./packem_shared/WORKFLOWS_FILENAME-CQR8fE9B.mjs";import{emitApp as He}from"./packem_shared/emitApp-DAZCUDbr.mjs";import{isD1GlobalTable as Be,isHyperdriveGlobalTable as ke}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DFv-RYZU.mjs";import{OPENRPC_VERSION as qe,buildOpenRpcDocument as we,emitOpenRpc as Je,emitOpenRpcModule as Ye}from"./packem_shared/OPENRPC_VERSION-CCY7xqSL.mjs";import{DEFAULT_TARGET as Ze,platformMatrixIds as $e,readProjectTarget as er,resolveCodegenTarget as rr}from"./packem_shared/DEFAULT_TARGET-BnQiNNKu.mjs";import{l as tr,r as sr}from"./packem_shared/project-config-file-BV7RR-l6.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ir,runCodegen as mr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-D9fd22gh.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as pr,evaluateSchemaDrift as nr,parseSchemaSnapshot as lr}from"./packem_shared/SchemaSnapshotParseError-CPOXlFhI.mjs";import{default as xr}from"./packem_shared/fingerprintSchemaSources-eVG9aVt0.mjs";import{schemaFromIr as Er}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Ar,validatorIrToJsonSchema as vr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as Nr,SDK_TARGETS as gr,generateSdk as Or}from"./packem_shared/SDK_LANGUAGES-Df_CnJx5.mjs";import{redact as Tr,secretKindOf as hr}from"./packem_shared/redact-Cy14LEnc.mjs";import{default as _r}from"./packem_shared/emitDrizzleSchema-DitcRZ1a.mjs";import{default as Mr}from"./packem_shared/emitFunctions-BeKgL3dl.mjs";import{e as Pr}from"./packem_shared/server-DAvi_bv_.mjs";import{e as br}from"./packem_shared/shard-BWVyL-4A.mjs";import{G as Ur}from"./packem_shared/shared-DnCokNcE.mjs";import{MESSAGE_SOLUTIONS as Hr,findSolutionByMessage as jr}from"@lunora/errors";import{PROJECT_CONFIG_FILENAMES as kr,findProjectConfigFile as Wr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-DzOu-lSc.mjs";import{createCodegenProject as Vr,findTsconfig as zr,refreshCodegenProject as Qr}from"./packem_shared/createCodegenProject-V51_yBw3.mjs";import{s as wr,t as Jr,u as Yr}from"./packem_shared/shard-runtime-BX0xmo0P.mjs";import{emitApi as Zr,emitCollections as $r,emitInternalApi as eo}from"./packem_shared/emitApi-Zx6VPN-7.mjs";import{emitCrons as oo,emitScheduler as to,emitVectors as so,emitWranglerCronTriggers as ao}from"./packem_shared/emitCrons-BQW2lviZ.mjs";import{emitDataModel as mo}from"./packem_shared/emitDataModel-BskFt9Wv.mjs";import{isTypedSchema as po}from"./packem_shared/isTypedSchema-CKzc3ioR.mjs";const e="0.0.0";export{N as AGENTS_FILENAME,E as CAPABILITY_PROBES,L as CONTAINERS_FILENAME,A as CodegenDiagnosticError,Ze as DEFAULT_TARGET,j as FLAGS_FILENAME,Ur as GENERATED_HEADER,Ar as LUNORA_ERROR_CODES,Hr as LUNORA_SOLUTION_RULES,ee as MUTATORS_FILENAME,ae as NOTIFY_FILENAME,qe as OPENRPC_VERSION,kr as PROJECT_CONFIG_FILENAMES,xe as QUEUES_FILENAME,ir as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Nr as SDK_LANGUAGES,gr as SDK_TARGETS,Me as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,ye as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,we as buildOpenRpcDocument,pr as buildSchemaSnapshot,b as capabilitiesUsedBy,Vr as createCodegenProject,n as describeErrorLevelFindings,v as diagnosticAt,s as diffSchemaSnapshots,g as discoverAgents,I as discoverAuthApiCalls,M as discoverContainers,P as discoverCrons,B as discoverFlags,W as discoverFunctions,V as discoverHttpRoutes,Q as discoverHyperdriveCalls,w as discoverInserts,Y as discoverMaskProcedures,Z as discoverMigrations,re as discoverMutators,te as discoverNondeterministicCalls,ie as discoverNotifyCalls,me as discoverNotifyChannels,fe as discoverNotifyConfig,le as discoverQueries,Se as discoverQueues,ue as discoverR2sqlCalls,Ne as discoverRlsMetadata,ve as discoverRlsProcedures,Oe as discoverSandboxUsage,Te as discoverSchema,Fe as discoverShapes,De as discoverStorageRulesMetadata,Ue as discoverWorkflows,wr as emitAgents,Zr as emitApi,He as emitApp,$r as emitCollections,Jr as emitContainers,oo as emitCrons,mo as emitDataModel,_r as emitDrizzleSchema,Mr as emitFunctions,eo as emitInternalApi,Ve as emitOpenApi,ze as emitOpenApiModule,Je as emitOpenRpc,Ye as emitOpenRpcModule,to as emitScheduler,Pr as emitServer,br as emitShard,so as emitVectors,Yr as emitWorkflows,ao as emitWranglerCronTriggers,l as errorAdvisoryNames,c as errorPlatformDiagnosticNames,nr as evaluateSchemaDrift,jr as findLunoraSolution,Wr as findProjectConfigFile,zr as findTsconfig,xr as fingerprintSchemaSources,y as foldCapabilitySignals,m as formatAdvisories,Or as generateSdk,Be as isD1GlobalTable,ke as isHyperdriveGlobalTable,R as isTestPath,po as isTypedSchema,f as lintSchema,T as listLunoraSourceFiles,tr as loadProjectConfig,U as mayReadCapabilityContext,lr as parseSchemaSnapshot,$e as platformMatrixIds,pe as readPackageDependencies,sr as readProjectConfigLiterals,er as readProjectTarget,Ie as readServiceBindings,Tr as redact,Qr as refreshCodegenProject,rr as resolveCodegenTarget,_e as resolveServiceBindings,mr as runCodegen,Er as schemaFromIr,hr as secretKindOf,a as serializeSchemaSnapshot,x as sortedUniqueNames,G as sourceCapabilitySignals,d as toAdvisorContext,vr as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h,CELLD_CAPABILITIES as b}from"@lunora/platform";import{r as m}from"./project-config-file-BV7RR-l6.mjs";const d="cloudflare",v=t=>{const{target:e}=m(t);return e!==void 0&&e.length>0?e:void 0},I=(t,e)=>e??v(t)??d,C=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=m(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${d}" 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: "${d}" }\`), or pass \`--target\`.`,target:d}]},S={max:1536,min:32},L=(t,e)=>{if(t!=="cloudflare")return[];const{max:a,min:r}=S,n=`${String(r)}-${String(a)}`;return e.filter(({dimensions:s})=>s!==void 0&&(!Number.isInteger(s)||s<r||s>a)).map(({dimensions:s,name:i})=>({level:"warn",message:`Vector index "${i}" declares ${String(s)} dimensions; Cloudflare Vectorize accepts ${n}, so creating a Vectorize index for it fails at deploy.`,name:"platform_vector_dimensions_out_of_range",remediation:`If a Vectorize index backs "${i}", use ${n} dimensions (many embedding models can truncate output to fit). Ignore this if another store, such as pgvector, backs it.`,target:t}))},u={celld:b,cloudflare:h,node:f},E=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),y={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},w=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","services","topics","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],g={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",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`)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},_=(t,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}),k=(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=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:s,target:i}=t;for(const l of w){if(s[l]!==!0)continue;const o=r.features[l]?.level;o!=="unsupported"&&o!==void 0||(a[l]=!1,!n.has(l)&&e.push(o==="unsupported"?_(l,r,i):k(l,r,i)))}},$=(t,e,a,r={})=>{const n={...t},s={...r},i=[],l=new Set;for(const[o,c]of Object.entries(y)){if(c===null||!t[o])continue;const p=e.features[c]?.level;p==="unsupported"?(n[o]=!1,l.add(c),i.push({feature:o,level:"error",message:`${e.name} does not support "${o}" (ctx.${o}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${o} usage, or deploy to a target whose capability matrix marks "${c}" as native or emulated.`,target:a})):p===void 0&&(n[o]=!1,l.add(c),i.push({feature:o,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${o}" (ctx.${o}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${c}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return T({diagnostics:i,gatedSignals:s,matrix:e,reported:l,signals:r,target:a}),{diagnostics:i,signals:s,usage:n}},R=(t,e,a={})=>{const r=u[e];return r===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,r,e,a)},O=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{y as CAPABILITY_TO_FEATURE,d as DEFAULT_TARGET,$ as gateAgainstMatrix,R as gatePlatformFeatures,E as platformMatrixIds,v as readProjectTarget,C as readTargetDiagnostics,I as resolveCodegenTarget,O as studioPlatformFor,L as vectorizeDimensionDiagnostics};
@@ -0,0 +1,11 @@
1
+ import{existsSync as F,mkdirSync as nn,readFileSync as ki,writeFileSync as Ri,rmSync as ht,readdirSync as Fi}from"node:fs";import{dirname as rn,join as v,relative as Li}from"node:path";import{performance as rt}from"node:perf_hooks";import{runAdvisor as Di}from"@lunora/advisor";import{LunoraError as U}from"@lunora/errors";import{serializeSchemaSnapshot as Mi}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as _i}from"./formatAdvisories-DwmUKYuc.mjs";import{Node as r,SyntaxKind as d,ts as Ki,VariableDeclarationKind as Bi}from"ts-morph";import{listLunoraSourceFiles as S,lunoraRelativePath as I,bindingKeyName as te,collectCallRows as T,findObjectProperty as D,collectSecurityCallRows as zi,propertyInitializer as C,listSecurityScanFiles as ze,objectLiteralFromCallbackBody as on,limitNameOf as an,optionsObjectLiteral as cn,handlerOf as $i,collectNodeRows as J,chainRootOf as Ot,outermostValueWrapper as P,isWriteTarget as $e,isSameNode as y,unwrapExpression as h,isConstDeclaration as Z,memberAccessOf as ln,returningFunctionOf as vt,walkChain as Vi,RUN_METHODS as dn,functionReferenceSegments as Ui,isTestPath as qi,isFunctionLike as ee,functionKeyOf as un}from"./isTestPath-B81lOULB.mjs";import{b as j,d as $,f as O,g as kt,c as E,a as fn,w as Rt,k as Wi,l as Hi,h as ji,m as Gi,j as Et,i as Yi}from"./attribution-hVBriwzy.mjs";import{a as gs,r as ot,i as q,b as Qi,m as gn,c as Ve,e as Ft,E as pn,C as mn,d as Xi,f as Ji,g as Zi}from"./context-root-wBahDTzk.mjs";import{a as b,i as er,c as Q,d as hn,e as tr,f as sr}from"./classify-procedure-call-BAj0D1u2.mjs";import{a as A,r as vn,s as nr,b as ir}from"./project-config-file-BV7RR-l6.mjs";import{a as rr,b as Ue}from"./module-specifiers-WF8iAydP.mjs";import{r as qe,s as or}from"./parse-validator-IDBKIT7M.mjs";import ar from"./discoverAuthApiCalls-xs0ONfI-.mjs";import cr from"./discoverHyperdriveCalls-BUrA_96X.mjs";import{diagnosticAt as Se}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Lt,a as Le,s as En,d as lr}from"./index-DZZpHXMv.mjs";import{i as z,r as xn}from"./database-calls-CHZbBUCZ.mjs";import{MUTATORS_FILENAME as dr,isDefineMutatorCallee as ur,mutatorServerImplOf as fr,discoverMutators as gr}from"./MUTATORS_FILENAME-Bw0YtaO8.mjs";import pr from"./discoverNondeterministicCalls-9ZDpRptb.mjs";import{discoverNotifyConfig as mr,discoverNotifyCalls as hr}from"./NOTIFY_FILENAME-CPjbiHQl.mjs";import vr from"./discoverR2sqlCalls-COKmDnih.mjs";import Er from"./discoverRlsProcedures-BlUd32bU.mjs";import{s as Dt,n as xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Sr,redact as Ar,isHeuristicSecretKind as yr,isSecretishName as br}from"./redact-Cy14LEnc.mjs";import{a as Ce,d as Nr,r as wr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as Pr,discoverWorkflows as Ir}from"./WORKFLOWS_FILENAME-CQR8fE9B.mjs";import{r as Cr}from"./json-data-Chfs2Cz5.mjs";import{G as Tr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Or}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as tv,refreshCodegenProject as sv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as kr,usedCapabilities as Rr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as Sn,isHyperdriveGlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Fr}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as Lr}from"./CONTAINERS_FILENAME-Bk0u9QUu.mjs";import Dr from"./discoverCrons-DF7dOP9x.mjs";import{contextPropertiesRead as Mr,discoverFeatureUsage as _r}from"./capabilitiesUsedBy-QgSZyE0T.mjs";import yn from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Kr}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as Br}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as zr}from"./readServiceBindings-DvqIThzd.mjs";import $r from"./discoverStorageRulesMetadata-BPJplDfz.mjs";import{resolveCodegenTarget as bn,gatePlatformFeatures as Vr,readTargetDiagnostics as Ur,vectorizeDimensionDiagnostics as qr,studioPlatformFor as Wr}from"./DEFAULT_TARGET-BnQiNNKu.mjs";import{i as Hr}from"./schema-BgM8A3XV.mjs";import{b as Nn,e as jr}from"./shard-BWVyL-4A.mjs";import{e as Gr,a as Yr}from"./server-DAvi_bv_.mjs";import{emitDataModel as Qr}from"./emitDataModel-BskFt9Wv.mjs";import{i as Xr,a as Jr,e as Zr,b as eo,d as to,c as so}from"./unwrap-handler-return-B-jQde6M.mjs";import no from"./discoverFunctions-DaEZl3uE.mjs";import io from"./discoverHttpRoutes-C_u9YiFb.mjs";import ro from"./discoverInserts-OT_fiEGq.mjs";import{e as wn}from"./exported-procedure-chains-DKK5HoK3.mjs";import oo from"./discoverMigrations-C9mLIhGZ.mjs";import ao from"./discoverQueries-C8V4cMIP.mjs";import co from"./discoverRlsMetadata-Cb8JR1b4.mjs";import lo from"./discoverSchema-rxbrQztG.mjs";import{discoverShapes as uo}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as fo}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as go}from"./emitApp-DAZCUDbr.mjs";import{readJsonSync as po}from"@visulima/fs";import{buildSchemaSnapshot as mo}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{buildOpenApiDocument as ho,emitOpenApiModule as vo}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as Eo,emitOpenRpcModule as xo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as So,t as Ao,u as yo,s as bo,w as No}from"./shard-runtime-BX0xmo0P.mjs";import{emitCollections as wo,emitSeed as Po,emitApi as Io,emitInternalApi as Co}from"./emitApi-Zx6VPN-7.mjs";import{emitCrons as To,emitScheduler as Oo,emitShardRegistry as ko,emitDurableObjects as Ro,emitVectors as Fo,emitWranglerCronTriggers as Lo}from"./emitCrons-BQW2lviZ.mjs";import Do from"./emitDrizzleSchema-DitcRZ1a.mjs";import Mo from"./emitFunctions-BeKgL3dl.mjs";const Pn=new Set(["delete","get","head","options","patch","post","put"]),_o=new Set(["handler","stream"]),Ko=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ps=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Bo=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Pn.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},zo=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||Pn.has(n.getName()))break;s=n.getExpression()}return Bo(s)},$o=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(ps.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&ps.has(s.getText()))return!0}return!1},Vo=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!_o.has(n.getName()))return;const i=zo(s);if(!i||!Ko.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&$o(o);return{exportName:$(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Uo=(e,t)=>{const s=[];for(const n of j(e)){const i=Vo(n,t);i&&s.push(i)}return s},qo=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Uo(i,I(t,n)))}return s},Wo=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Ho=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?te(t):void 0}},jo=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&gs(a)}))return!1;const n=O(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&gs(i)},ms=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=Wo(e);return n!==void 0&&Ho(n)===t?!0:t==="args"&&jo(e)},In=(e,t)=>r.isIdentifier(e)?ms(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>ms(s,t)),Go=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},hs=e=>{const t=r.isIdentifier(e)?O(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!kt(t)?t.getInitializer():void 0},xt=e=>In(e,"args"),W=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},H=e=>{if(xt(e))return!0;const t=W(e);return t!==void 0&&xt(t)},Yo=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=W(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},se=e=>{if(ot(e))return!0;const t=hs(e);if(t!==void 0&&ot(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=hs(i);return o!==void 0&&ot(o)})},Te=(e,t)=>In(e,t),Qo=(e,t)=>{if(Te(e,t))return!0;const s=W(e);if(s!==void 0&&Te(s,t))return!0;const n=Go(e);if(n!==void 0){const i=W(n);return i!==void 0&&Te(i,t)}return!1},Xo=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:q(e.getExpression(),["ai"]),Jo=(e,t)=>{if(!Xo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)||se(s)))return{scope:E(e),file:t,line:e.getStartLineNumber()}},Zo=(e,t)=>T(e,t,Jo),ea=new Set(["generateText","streamText"]),ta=new Set(["messages","prompt","system"]),sa=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],na=(e,t)=>sa.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),ia=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Qi(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&na(i,s));return n===void 0?void 0:`${n}.${s}`},ra=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=ia(t);if(s!==void 0)return s}},oa=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=te(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},aa=e=>{if(xt(e))return!0;const t=oa(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},ca=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!ta.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&aa(s))return!0}return!1},la=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());if(i===void 0||!ea.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(b(c.getExpression())==="tool"&&(a=ra(c),a!==void 0))break;a!==void 0&&s.push({scope:E(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:ca(o)})}return s},da=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...la(i,I(t,n)))}return s},ua=e=>q(e,["fetch"]),fa=(e,t)=>{if(!ua(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!H(s)))return{scope:E(e),file:t,line:e.getStartLineNumber()}},ga=(e,t)=>T(e,t,fa),Mt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=qe(s.getExpression());return n===void 0||Mt(n,t)})}finally{t.delete(e)}},pa=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=D(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:qe(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Mt(i)}},ma=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?qe(o):void 0;a===void 0?s=!0:(t.push(a),s||=Mt(a))}n=i.getExpression()}return{objects:t,opaque:s}},_t=(e,t)=>t?ma(t):pa(e),Cn=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=qe(s.getExpression());return n===void 0?[]:Cn(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},ha=e=>e.flatMap(t=>Cn(t,new Set)),va=new Set(["check","length","max"]),St=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(va.has(s.getName()))return!0;t=n}},At=e=>rr(e)||e==="@lunora/values",Ea=e=>{const t=new Set(["v"]);for(const s of er(e,"v",At))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&At(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},xa=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},Sa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Aa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&At(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),Kt=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return Sa(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Aa(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},ya=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},ba=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},Na=e=>r.isReturnStatement(e)?e.getExpression():void 0,wa=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ba(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=Na(t);return s?[s]:[]}),Tn=(e,t)=>{if(Kt(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Tn(e.getExpression(),t)},Pa=(e,t)=>{const s=ya(e.getExpression(),e.getSourceFile());if(!s)return[];const n=St(e),i=new Set(wa(s).map(o=>Tn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=Kt(o,t);return a===void 0?[]:[{bounded:St(o)||n&&i.has(o),factory:a}]})},Ia=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=Kt(s,t),i=n===void 0?[]:[{bounded:St(s),factory:n}];return r.isCallExpression(s)?[...i,...Pa(s,t)]:i}),Ca=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Ia(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Ta=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=Q(n);if(i?.visibility!=="public")return;const{objects:o}=_t(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Ca(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:$(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Oa=(e,t)=>{const s=[],n=Ea(e),i={destructured:xa(e,n),namespaces:n};for(const o of j(e)){const a=Ta(o,t,i);a&&s.push(a)}return s},ka=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Oa(i,I(t,n)))}return s},at=e=>e?.getKind()===d.TrueKeyword,Ra=e=>e?.getKind()===d.FalseKeyword,Fa=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,La=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Da=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&b(t.getExpression())==="scim"),Ma=e=>e!==void 0&&r.isCallExpression(e)&&La.has(b(e.getExpression())??""),_a=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),Ka=e=>{const t=C(e,"advanced"),s=C(e,"emailAndPassword"),n=C(e,"session");return{analyzable:!0,disableCsrfCheck:at(C(t,"disableCSRFCheck")),emailPasswordEnabled:at(C(s,"enabled")),requireEmailVerification:at(C(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Da(C(e,"plugins"))&&Ma(C(e,"database")),secureCookiesDisabled:Ra(C(t,"useSecureCookies")),sessionFreshAgeZero:Fa(C(n,"freshAge")),trustedOriginsWildcard:_a(C(e,"trustedOrigins"))}},Ba=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),za=(e,t)=>{if(b(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?Ka(s):Ba();return{scope:E(e),file:t,line:e.getStartLineNumber(),...i}},$a=(e,t)=>zi(e,t,za),Va=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return gn(e.getExpression(),t.matchReceiver)?s:void 0},Ua=(e,t,s)=>{const n=Va(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!H(i)||se(i))&&!(s.requireUnmodifiedReach===!0&&!Yo(i)))return{scope:E(e),file:t,line:e.getStartLineNumber(),method:n}},We=(e,t,s)=>T(e,t,(n,i)=>Ua(n,i,s)),qa=new Set(["content","pdf","scrape","screenshot"]),Wa=(e,t)=>We(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:qa}),Ha=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),ja=new Set(["RateLimiter"]),Ga=new Set(["extend"]),vs="lunora",Ya=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],On=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},yt=e=>e&&r.isObjectLiteralExpression(e)?On(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Qa=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&on(t.getBody());return s?On(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Xa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());i!==void 0&&(Ha.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...yt(n.getArguments()[0])}):Ga.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Qa(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=b(n.getExpression());i===void 0||!ja.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...yt(n.getArguments()[0])})}return s},Ja=(e,t)=>{for(const s of Ya){const n=v(t,s);if(!F(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))b(a.getExpression())===vs&&o.push({callee:vs,file:s,line:a.getStartLineNumber(),...yt(a.getArguments()[0])});return o}return[]},Za=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Xa(o,n))}return s.push(...Ja(e,rn(t))),s},Es="ctx.containers.",ec=e=>{if(!e.startsWith(Es))return!1;const t=e.slice(Es.length);return t.length>0&&!t.includes(".")},tc=(e,t)=>We(e,t,{argIndex:0,matchReceiver:ec,methods:new Set(["get"])}),sc=new Set(["allow","deny","setAllowed"]),nc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=D(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},ic=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!nc(e)))return{detail:"enableInternet: true",scope:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},rc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!sc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},oc=(e,t)=>ic(e,t)??rc(e,t),ac=(e,t)=>T(e,t,oc),cc=new Set(["defineExportSink","r2Sink","webhookExportSink"]),lc=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return cc.has(s)?s:void 0},dc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},uc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of ze(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=lc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?dc(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},fc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),gc=new Set(["dbRateLimit","rateLimit"]),pc=e=>{const t=cn(e);if(!t)return!1;const s=D(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},mc=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=fc.get(s);if(n!==void 0)return{callee:s,scope:E(e),failOpen:pc(e.getArguments()[n]),file:t,limitName:gc.has(s)?an(e):"",line:e.getStartLineNumber()}},hc=(e,t)=>T(e,t,mc),vc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=Q(t);if(s?.kind!=="query")return;const n=$i(t,s.receiver);return n?{exportName:$(e)??e.getName(),handler:n}:void 0},xs=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Ec=e=>{const t=xs(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=xs(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},xc=(e,t)=>{const s=[];for(const n of Ve(e.handler,"flags"))s.push({callee:Ec(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},Sc=(e,t)=>{const s=[];for(const n of j(e)){const i=vc(n);i&&s.push(...xc(i,t))}return s},Ac=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Sc(i,I(t,n)))}return s},yc=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:q(e.getExpression(),["flags"]),bc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},Nc=(e,t)=>{if(!yc(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=bc(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:E(e),file:t,key:i,line:e.getStartLineNumber()}},wc=(e,t)=>T(e,t,Nc),Pc=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Ic=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Cc=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))Pc(a)&&s.push({file:o,indexName:Ic(a),line:a.getStartLineNumber()})}return s},ve=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,kn=e=>{const t=e.getArguments()[0],s=ve(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=D(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?ve(n.getInitializer()):void 0},Tc=new Set(["delete","get","head","options","patch","post","put"]),Oc=new Set(["handler","stream"]),kc=new Set(["runAction","runMutation"]),Rc=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),Ee=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,Rn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(te(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},Ss=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:Rn(s,"ctx")},As=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:Rn(s,"request")},ys=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(kc.has(a)&&Ee(c,t))return a;if(Rc.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&Ee(c.getExpression(),t))return`db.${a}`}},bs=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&Ee(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!Ee(n.getInitializer(),t))){for(const o of i.getElements())if(te(o)==="auth")return!0}}return!1},Fc=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Lc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Ee(n.getExpression(),t)},Dc=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Fn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Dc(s)},Mc=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?Fn(t,a.getText()):[]}return[]},_c=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=Fn(s,t.getText());return n.length>0?n:Mc(t,s)},Ns=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>Lc(i,t)&&_c(i).some(o=>Fc.test(o)))},Kc=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Oc.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Tc.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Bc=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=ve(e.getArguments()[0]),l=c&&Ss(c,!0);if(!c||l===void 0||Ns(c,As(c,!0)))return;const u=ys(c,l);return u===void 0?void 0:{scope:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:bs(c,l),sideEffect:u}}const n=Kc(e);if(n===void 0)return;const i=ve(e.getArguments()[0]),o=i&&Ss(i,!1);if(!i||o===void 0||Ns(i,As(i,!1)))return;const a=ys(i,o);return a===void 0?void 0:{scope:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:bs(i,o),sideEffect:a}},zc=(e,t)=>T(e,t,Bc),$c=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Vc=new Set(["append","set"]),Ln=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ws=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>$c.has(b(n.getExpression())??"")&&Te(n,t)),Uc=(e,t)=>{if(ws(e,t))return!0;const s=W(e);return s!==void 0&&ws(s,t)},bt=(e,t)=>Qo(e,t)&&!Uc(e,t),qc=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=W(e);return t!==void 0&&r.isNewExpression(t)&&b(t.getExpression())==="Headers"},De=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=W(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Bt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&bt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Ln(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();bt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=De(n.getExpression());i!==void 0&&Bt(i,t,s)}},Dn=(e,t)=>{const s=De(e);if(s===void 0)return;const n=D(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=De(n.getInitializer());i!==void 0&&Bt(i,"response-init",t)},Wc=(e,t)=>{const s=b(e.getExpression());if(s==="Response")Dn(e.getArguments()[1],t);else if(s==="Headers"){const n=De(e.getArguments()[0]);n!==void 0&&Bt(n,"headers-ctor",t)}},Hc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){Dn(e.getArguments()[1],t);return}if(Vc.has(n)&&qc(i)){const o=e.getArguments()[1];o!==void 0&&bt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Ln(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},jc=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))Wc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Hc(s,t)},Gc=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=ve(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return jc(n,{scope:E(e),relativePath:t,requestName:o.getText(),rows:a}),a},Yc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...Gc(n,t));return s},Qc=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Yc(i,I(t,n)))}return s},Mn="identity.ts",Xc=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Jc=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ue(n.getModuleSpecifierValue())}return!1},Zc=e=>{if(r.isIdentifier(e))return Xc(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Jc(t)}return!1},el=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Zc(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Se(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=fn(s,"member");a!==void 0&&t.push({exportName:a})}return t},tl=(e,t)=>{const s=v(t,Mn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=el(n);if(i.length!==0){if(i.length>1)throw Se(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},sl=new Set(["auth","context.auth"]),nl="userId",il=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},rl=(e,t)=>{const s=v(t,Mn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(b(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?il(o):void 0}},Ps=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return sl.has(t.getText())||q(t,["auth"])?e:void 0},ol=e=>{if(r.isPropertyAccessExpression(e)&&Ps(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&Ps(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Is=(e,t,s)=>{const n=ol(e);return n===void 0?void 0:{declared:n===nl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:E(e)}},al=(e,t)=>{const s=rl(e,t);return s===void 0?[]:[...J(e,t,d.PropertyAccessExpression,(n,i)=>Is(n,i,s)),...J(e,t,d.ElementAccessExpression,(n,i)=>Is(n,i,s))]},cl=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=C(s,"key");if(!(!n||!H(n)||se(n)))return{scope:E(e),file:t,line:e.getStartLineNumber()}},ll=(e,t)=>T(e,t,cl),dl=new Set(["delete","get","getRaw","getWithMetadata","put"]),ul=(e,t,s=[])=>{const n=We(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:dl});return Rt(n,s)},fl=new Set(["queue","send"]),Cs=new Set(["bcc","cc","to"]),gl=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!fl.has(t))return;const s=e.getExpression();return q(s,["mail"])||q(s,["email"])?t:void 0},pl=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Cs.has(A(t))&&H(n)&&!se(n)}if(!r.isPropertyAssignment(t)||!Cs.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&H(s)&&!se(s)}):!1,ml=(e,t)=>{const s=gl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!pl(n)))return{scope:E(e),file:t,line:e.getStartLineNumber(),method:s}},hl=(e,t)=>T(e,t,ml),vl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Le(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Le(l);if(u===void 0)continue;const f=En(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},El=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Q(s):void 0;return n?.receiver?Lt(n.receiver).flatMap(i=>vl(i,$(e)??e.getName(),t)):[]},xl=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...El(a,o))}return s},Sl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return z(s)},Al=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=D(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},yl=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ur(s.getExpression())?s:void 0},bl=e=>{const t=yl(e),s=t===void 0?void 0:Al(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?$(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>Sl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Nl=e=>e.getVariableDeclarations().flatMap(t=>bl(t)),wl=(e,t)=>{const s=v(t,dr);if(!F(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Nl(n)},Pl=new Set(["delete","get","patch"]),Il=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Cl=new Set(["auth","identity","session","user"]),Tl=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Ol=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!z(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},kl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},Rl=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Fl=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Ll=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>Rl(s.getExpression(),t)&&Fl(s.getThenStatement())),Dl=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Pl.has(i))continue;const o=n.getExpression();if(!(z(o)||r.isPropertyAccessExpression(o)&&z(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},Ml=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Ft(Ot(s))!==void 0)),_l=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Tl.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),Kl=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Il.has(t.getText()))return!0;return[...Cl].some(t=>Ve(e,t).length>0)?!0:Ml(e)||_l(e)},Bl=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Q(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=kn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&hn(n.receiver,"use","rls"),a=Kl(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=Ol(u);if(f===void 0)continue;const g=kl(u);if(g===void 0||c.has(g)||!Ll(i,g))continue;const p=Dl(i,g);p!==void 0&&(c.add(g),l.push({exportName:$(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:f,usesRls:o,visibility:n.visibility}))}return l},zl=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...Bl(a,o))}return s},_n=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?O(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},$l=e=>{const t=P(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!$e(s)},Vl=e=>{const t=P(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Ul=e=>{const s=P(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!$e(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},Me=e=>{const t=O(e);return t===void 0||Hi(t.getSourceFile())},Nt=(e,t)=>{const s=P(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&Me(o);if(_n(Ot(o),t))return!(r.isPropertyAccessExpression(o)&&pn.has(o.getName()))||r.isExpressionStatement(P(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!Me(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},Oe={kind:"opaque"},ql={kind:"unreached"},Wl=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},wt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?O(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=Wl(s);return i===void 0||kt(i)?void 0:i}const n=Z(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},Kn=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?Oe:c===void 0?a.some(l=>l.isRestParameter())?Oe:ql:c.isRestParameter()?Oe:{kind:"parameter",parameter:c}},Hl=e=>{const t=P(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=wt(s.getExpression());return n===void 0?Oe:Kn(n,s,t)},jl=new Set(["__defineGetter__","__defineSetter__","__proto__"]),Gl=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Bn=e=>{const t=P(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=Gl(s);if(n!==void 0)return y(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},Yl=4,zn=(e,t,s=0)=>{if(Wi(e))return!0;if($l(e)){const i=P(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!jl.has(c)}if(Vl(e)||Ul(e)||Bn(e)||Nt(e,t))return!0;const n=Hl(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Ql(n.parameter,s+1)},Ts=new WeakMap,Ql=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Ts.get(e.compilerNode);if(n!==void 0)return n;if(t>Yl)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||O(a)?.compilerNode!==e.compilerNode||zn(a,void 0,t));return(o||t===0)&&Ts.set(e.compilerNode,o),o},Os=new WeakMap,Xl=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=O(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Jl=(e,t,s)=>{const{context:n,impl:i}=e,o=Os.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const p=g.getNameNode();return r.isIdentifier(p)?[p]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?zn(g,n):!$e(g),f=!Xl(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const p=g.getText();if(p==="arguments")return!1;const x=l.get(p);return x===void 0||c.includes(g)||O(g)?.compilerNode!==x?!0:u(g)});return Os.set(i.compilerNode,f),f},ks=new WeakMap,Zl=e=>{let t=ks.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=fr(s);return n===void 0?[]:[[n.compilerNode,s]]})),ks.set(e.compilerNode,t)),t},ed=e=>{const t=Zl(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:$(n)??n.getName()};return a!==void 0&&Jl(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},ct="args",pe=e=>{const t=ln(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===ct?t.member:void 0}if(!r.isIdentifier(e))return;const s=O(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=Z(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&te(i)===ct||r.isIdentifier(o)&&o.getText()===ct?te(s):void 0},td=new Set(["auth","identity","user"]),Pt=e=>{const t=i=>{const o=Ft(i);return o!==void 0&&o.length>0&&td.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=W(s);return n!==void 0&&t(n)},$n=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=pe(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?W(n):void 0;if(o!==void 0)for(const a of $n(o,t-1))s.add(a)}return s},ke=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...ke(n),...ke(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=pe(h(u)??u);return g===void 0?[]:ke(f).filter(p=>p===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=pe(h(n)??n),c=pe(h(i)??i);return a!==void 0&&Pt(i)&&o.push(a),c!==void 0&&Pt(n)&&o.push(c),o},sd=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&tr(i.getExpression(),"defineIdentityGuard")},nd=e=>{if(!sd(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=pe(h(s)??s),o=t.some((a,c)=>c!==n&&Pt(a));return i!==void 0&&o?[i]:[]})},id=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},rd=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),Rs=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},od=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),ad=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&Rs(n,e)&&id(n.getThenStatement()))for(const i of ke(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&od(n)&&Rs(n,e))for(const i of nd(n))s.add(i);return s},cd=(e,t)=>{const s=$n(t);if(s.size===0)return!1;const n=e.getFirstAncestor(rd);if(n===void 0)return!1;const i=ad(n,e.getStart());return[...s].every(o=>i.has(o))},ld=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),dd=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),It=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),Vn=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),ud=e=>{const t=P(e),s=t.getParent();if(r.isVariableDeclaration(s))return y(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},fd=e=>{const t=ud(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||Z(t)?[t]:void 0:Vn(t)},me=e=>e.isUnion()?e.getUnionTypes().every(t=>me(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>me(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),_e=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},Re=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},gd=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&dd.get(s.getText())?.has(t.getName())===!0&&Me(s)},pd=e=>{const t=vt(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=P(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&_e(n,mn)?n:void 0},md=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=P(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:_e(n,ld,t)?n:void 0},hd=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},vd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&y(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Fs=e=>{const t=P(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&gd(s);return md(s,t)??hd(s,t)??vd(s,t)??(n?s:pd(t))},Ed=5e4,Un=()=>({inProgress:new Set,verdicts:new Map});class xd{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>Ed&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const Sd=8,Ad=8;class yd{budget;scope;taint;verdicts=Un();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!me(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?Vn(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=Sd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(P(l),!0,a,0))&&(t===n||!me(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let p=Fs(o);p!==void 0;p=Fs(o)){if(r.isCallExpression(p)&&this.callbackCompromises(p,n))return!0;o=P(p)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&me(o.getType());if($e(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=fd(o);if(u!==void 0)return u.some(p=>n(p,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=P(t).getParent();if(n>=Ad)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===P(t)?this.valueCompromises(i,!1,s,n+1):!_e(i,It);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||Z(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=P(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>Re(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=_e(t,It)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=wt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!Nt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(Nt(s,this.scope.context))return!1;const i=wt(t.getExpression()),o=i===void 0?void 0:Kn(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Bn(t)||y(vt(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=vt(t);return y(s,this.scope.impl)?void 0:s}}const bd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),Nd=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=O(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},wd=new Set(["all","allSettled","any","race"]),Ls=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,lt=8;class Pd{budget=new xd;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Un();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new yd(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,lt)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>ji(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=O(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=P(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!It.has(g.getName()))return!0;const p=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(g.getExpression(),!0)||p.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&Z(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const p=P(g),x=p.getParent();return!r.isCallExpression(x)||x.getExpression()!==p||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&Me(i)&&wd.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:Re(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=O(t),i=Ls(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&pn.has(i)?!1:i!==void 0&&mn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>Re(a)!==void 0)&&(i===void 0||!bd.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Ot(i),c=r.isIdentifier(a)?Ls(O(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=Re(i);if(o===void 0)return!Nd(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Vi(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(_n(i,this.scope.context))return!0;const o=r.isIdentifier(i)?O(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=Z(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=kt(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,lt))return!1;if(this.variableDepth>=lt)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Ds=new WeakMap,Id=e=>{const t=Ds.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new Pd(e);return Ds.set(e.impl.compilerNode,s),s},Cd=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Td=new Set(["insert","insertManyUnsafe","patch","replace"]),Od=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Td.has(t)&&Xi(e.getExpression())?t:void 0},kd=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},Rd=(e,t)=>{const s=ln(e);return s?.member===t?h(s.object):void 0},Ms=(e,t)=>r.isIdentifier(e)&&O(e)?.compilerNode===t.compilerNode,qn=(e,t,s,n=1)=>{const i=Rd(e,s);if(i!==void 0)return Ms(i,t);const o=r.isIdentifier(e)?O(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&te(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||Z(l)&&Ms(h(l.getInitializer()),t))}const a=Z(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&qn(a,t,s,n-1)},Ct=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...Ct(t.getWhenTrue()),...Ct(t.getWhenFalse())]:[t]},Fd=(e,t,s)=>{const n=[],i=s===void 0?void 0:Id(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!Cd.has(a))continue;const l=Ct(c).filter(f=>i===void 0?H(f)&&!Ji(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&qn(c,s.parameter,a),g=l.every(p=>cd(t.call,p));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Ld=(e,t,s)=>{const n=Od(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=kd(i,n);if(o.length===0)return[];const a=E(e),c=ed(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Fd(u,l,c))},Dd=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=T(e,t,(c,l)=>Ld(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return Rt(o,s).map(c=>Gi(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Md=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),_d=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Kd=e=>{const t=D(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?_d(t.getInitializer()):void 0},Bd=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Md.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?Kd(n):void 0;return{callee:s,scope:E(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},zd=(e,t)=>T(e,t,Bd),$d=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),Vd=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Ud=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=D(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},Wn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Hn=(e,t)=>e===t||e.startsWith(`${t}.`),jn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},_s=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},Gn=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>_s(s));return r.isIdentifier(e)&&_s(e)&&t.push(e),t},qd=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},Wd=e=>{const t=Wn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Hd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Wd(e),i=new Set,o=a=>jn(a).some(c=>n.some(l=>Hn(c.getText(),l)))?!0:Gn(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of qd(a))i.add(l)}return{names:i,prefixes:n}},jd=(e,t)=>jn(e).some(s=>t.prefixes.some(n=>Hn(s.getText(),n)))?!0:Gn(e).some(s=>t.names.has(s.getText())),Gd=e=>{const t=Ui(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Yd=(e,t,s)=>{const n=Wn(e,0);if(n===void 0)return[];const i=Hd(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!dn.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!jd(u,i))continue;const f=Gd(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:E(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Qd=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=Vd(n),o=i===void 0?void 0:$d.get(i);if(o===void 0)continue;const a=Ud(n,o);a!==void 0&&s.push(...Yd(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Xd=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qd(i,I(t,n)))}return s},Ks={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Bs=new Set(["account","credential","member","passkey","session","user"]),Jd=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Zd=e=>{const s=Jd(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Bs.has(s)||Bs.has(n)},eu=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},tu=(e,t)=>{const{objects:s,opaque:n}=_t(e,t);return ha(s).some(i=>eu(i))?!0:n?void 0:!1},su=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!D(t,"captcha"),usesRateLimit:!!D(t,"rateLimit")}},nu=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Fe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},iu=e=>{const t=nu(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=su(t);return{...Fe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ks?{...Fe,[Ks[s]]:!0}:Fe},ru=e=>{const t={...Fe};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=iu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},ou=new Set(["insert","insertMany","insertManyUnsafe","replace"]),au=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ou.has(t.getName()))return!1;const s=t.getExpression();if(!z(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:Zd(i.getLiteralText())},cu=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),zs=new Set(["queues","scheduler","topics","workflows"]),lu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!cu.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&zs.has(s.getName())&&Zi(s.getExpression()))return!0;s=s.getExpression()}const n=Ft(s);return n?.length===1&&zs.has(n[0]??"")},du=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return z(s)},Yn=new Set(["generateObject","generateText","streamObject","streamText"]),uu=e=>{const t=b(e.getExpression());return t!==void 0&&Yn.has(t)},fu=e=>{const t=b(e.getExpression());if(t===void 0||!Yn.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!D(s,"maxOutputTokens")},gu=new Set(["log","span","trace"]),pu=new Set(["ai"]),mu=new Set(["email","mail"]),hu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),dt=(e,t)=>[...t].some(s=>Ve(e,s).length>0),Qn=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),vu=new Set(["every","filter","flatMap","forEach","map","some"]),Eu=new Set(["all","allSettled","race"]),Xn=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(vu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&Eu.has(n))return t},xu=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Qn.has(t.getKind())){const s=Xn(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Su=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Qn.has(t.getKind())){if(t=Xn(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Au=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(p=>{const x=p.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(p.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},yu=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},bu=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Nu=e=>{let t=!1,s=!0;for(const n of[...hu].flatMap(i=>Ve(e,i))){const i=bu(n);i&&(t=!0,!xu(i)&&!yu(i)&&!Au(i)&&!Su(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},wu=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),$s="lunora-advisor-exempt",Pu=/^[\s*/]+/u,Iu=/[\w-]/u,Cu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
2
+ `);for(const n of s.split(`
3
+ `)){const i=n.replace(Pu,"");if(!i.startsWith($s))continue;const o=i.slice($s.length);if(Iu.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Tu=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=D(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Ou=(e,t)=>{const s=Tu(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},ku=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(au(l)&&(o=!0),lu(l)&&(t=!0),du(l)&&(i=!0),uu(l)&&(s=!0),fu(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Nu(e);return{callsMail:dt(e,mu),emitsEvent:dt(e,gu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||dt(e,pu),throwsBareError:wu(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},Ru=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=Q(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?ru(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Ou(e,s);return{...o?ku(o):{},...Cu(e),...i,analyzableBody:o!==void 0,exportName:$(e)??e.getName(),file:t,hasEmailArg:tu(s,n.receiver),kind:n.kind,visibility:n.visibility}},Fu=(e,t)=>{const s=[];for(const n of j(e)){const i=Ru(n,t);i&&s.push(i)}return s},Lu=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Fu(i,I(t,n)))}return s},Du=new Set(["dbRateLimit","rateLimit"]),Mu=e=>r.isArrowFunction(e)?e.getBody():e,_u=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Jn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Zn=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},Ku=(e,t)=>H(e)||t!==void 0&&Zn(e,t).some(s=>Jn(s)),Bu=(e,t)=>t===void 0?se(e):Zn(e,t).some(s=>!Jn(s)),zu=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Du.has(s))return;const n=C(cn(e.getArguments()[2]),"key");if(!n)return;const i=Mu(n),o=_u(n);if(!(!Ku(i,o)||Bu(i,o)))return{callee:s,scope:E(e),file:t,limitName:an(e),line:e.getStartLineNumber()}},$u=(e,t)=>T(e,t,zu),Vu=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Uu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Vu.has(t.getName()))return;const s=t.getExpression();if(z(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&z(s.getExpression()))return s.getName()},qu=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&z(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Wu=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},ei=(e,t=!1)=>{const s=Wu(e);if(r.isIdentifier(s)){if(t)return;const n=W(s);return n===void 0?void 0:ei(n,!0)}if(r.isCallExpression(s))return Uu(s)??qu(s)},Hu=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},ju=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Q(s);if(n?.kind!=="query")return[];const i=kn(s);if(i===void 0)return[];const o=n.receiver!==void 0&&sr(n.receiver,"output"),a=n.receiver!==void 0&&hn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Hu(i)){const f=ei(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:$(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},Gu=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...ju(a,o))}return s},Yu=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},Qu=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Q(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=xn(o);if(a===void 0)continue;const c=Yu(C(a.options,"with"));c.length!==0&&i.push({exportName:$(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Xu=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...Qu(a,o))}return s},B=(e,t)=>`${e}:${t}`,Vs=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Ju=(e,t)=>[...J(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?Vs(s,n,s.getName(),s.isExported()):void 0),...J(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?Vs(i,n,s.getName(),i.isExported()):void 0})],Zu=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(B(c,a))},ef=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,tf=(e,t)=>{const s=new Map(e.map(n=>[B(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(B(i.file,i.name))?.set(ef(n),{fields:n.fields,method:n.method,table:n.table})}return s},sf=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>Zu(n,t,s)).filter(n=>n!==void 0),nf=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(B(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(B(o.file,o.name))?.push(a)}},rf=(e,t,s)=>{const n=new Map(e.map(a=>[B(a.file,a.name),a])),i=new Map(e.map(a=>[`${Dt(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[B(a.file,a.name),sf(a,n,t)]));return nf(s,n,i,o),o},of=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},af=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(B(i.file,i.name))??[])of(t.get(B(i.file,i.name)),t.get(B(o.file,o.name)))&&(n=!0)}},cf=(e,t,s,n)=>{const i=Ju(e,t),o=tf(i,s);return af(i,o,rf(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(B(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},Ke=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=Ke(e.getLeft()),s=Ke(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},lf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&Ke(t)!==void 0},df=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},uf=(e,t,s)=>yr(e)?!qi(s)&&br(df(t)):!0,ff=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(lf(o))continue;const a=Ke(o);if(a===void 0)continue;const c=Sr(a);if(c===void 0||!uf(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:Ar(a)}))}return s},gf=(e,t)=>{const s=[];for(const n of S(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ff(i,I(t,n)))}return s},pf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Q(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=xn(o);if(a===void 0)continue;const c=C(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&H(c);!l&&!u||i.push({exportName:$(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},mf=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of j(i))s.push(...pf(a,o))}return s},hf=new Set(["query","unsafe"]),vf=e=>!r.isPropertyAccessExpression(e)||!hf.has(e.getName())?!1:q(e.getExpression(),["sql"]),Ef=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),xf=(e,t)=>{if(!vf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ef(s)))return{file:t,line:s.getStartLineNumber(),scope:E(e)}},Sf=(e,t)=>T(e,t,xf),Af=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],yf=e=>{for(const[t,s]of Af)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},bf=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=yf(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Nf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),wf=(e,t,s=[])=>{const n=We(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Nf,requireUnmodifiedReach:!0});return Rt(n,s)},Pf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),If=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,Cf=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=If(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Tf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=Pf.get(t);return s===void 0?void 0:gn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Of=(e,t)=>{const s=Tf(e.getExpression());if(s!==void 0)return{scope:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...Cf(e.getArguments()[s.optionsIndex])}},kf=(e,t)=>T(e,t,Of),Rf=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),ti=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:Rf(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>ee(i)||s(i));if(!(n===void 0||ee(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},zt=(e,t)=>y(e.getFirstAncestor(s=>y(s,t)||ee(s)),t),Ff=(e,t)=>y(e,t)||e.getFirstAncestor(s=>y(s,t))!==void 0,si=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return y(e,t)||zt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=ti(e);return s!==void 0&&!Ff(s,t)}return!1},ni=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],Lf=e=>ni(e).some(t=>si(t,e)),Df=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Mf=e=>ni(e).some(t=>si(t,e)||r.isBreakStatement(t)&&y(ti(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Df(t)&&zt(t,e)),_f=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>zt(t,e)),Kf=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),Bf=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",ut=(e,t)=>{const s=Kf(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||Mf(e)||_f(e))return;const i=E(e);if(!(i.kind==="module"&&e.getFirstAncestor(ee)!==void 0))return{file:t,kind:Bf(e),line:e.getStartLineNumber(),scope:i}},zf=(e,t)=>[...J(e,t,d.WhileStatement,ut),...J(e,t,d.ForStatement,ut),...J(e,t,d.DoStatement,ut)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),$f=new Set(["when","where"]),ft=new Set(["definePolicy","defineShape"]),Vf=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return ft.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return ft.has(i)?i:void 0}const s=t.getText();return ft.has(s)?s:void 0},Uf=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,ii=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Uf(e))return"empty-object";if(r.isParenthesizedExpression(e))return ii(e.getExpression())}},$t=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),qf=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>$t(t)===e),ri=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>$t(t)===e),Wf=e=>{const t=qf(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||ri(e).length>0},Hf=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>$t(t)===e),Tt=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",jf=(e,t)=>Tt(e)||Tt(t),Gf=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Us=e=>!Tt(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Yf=(e,t,s)=>{const n=Gf.get(e);if(n!==void 0)return jf(t,s)?n==="positive"?"negative":"positive":Us(t)||Us(s)?void 0:n},he=e=>{if(r.isParenthesizedExpression(e))return he(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Yf(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=he(e.getLeft()),i=he(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},qs=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},Qf=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Xf=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Jf=e=>{const t=[];for(const s of ri(e)){const n=he(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Hf(e)){const n=he(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?qs(s.getThenStatement()):qs(s.getElseStatement())??Qf(s);i!==void 0&&t.push(Xf(i))}return t},Zf=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},eg=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!$f.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&Wf(a))for(const c of Jf(a)){const l=ii(c);l!==void 0&&i.push({exportName:Zf(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},tg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=Vf(n);i!==void 0&&s.push(...eg(n,i,t))}return s},sg=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...tg(i,I(t,n)))}return s},ng=new Set(["query","upsert","upsertNow"]),ig=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(ng.has(t))return q(e.getExpression(),["vectors"])?t:void 0},rg=(e,t)=>{const s=ig(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=C(n,"namespace");if(!(!i||!H(i)||se(i)))return{scope:E(e),file:t,line:e.getStartLineNumber(),method:s}},og=(e,t)=>T(e,t,rg),ag=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:p,workflows:x}=s;return _i({adminRoutes:qo(e,t),aiRawRuns:Zo(e,t),aiToolSideEffects:da(e,t),argumentDerivedFetches:ga(e,t),argumentValidators:ka(e,t),authApiCalls:ar(e,t),authConfigs:$a(e,t),browserUrlAccesses:Wa(e,t),callEdges:n.callEdges,configCalls:Za(e,t),containerKeyAccesses:tc(e,t),containerOverrides:ac(e,t),containers:i,cronTargets:o.flatMap(k=>k.functionPath===void 0?[]:[k.functionPath]),exportSinks:uc(e,t),staleMigrationImports:bf(e,t),failOpenGuards:hc(e,t),flagReads:Ac(e,t),flagSecurityDefaults:wc(e,t),geoIndexUsages:Cc(e,t),httpActionGuards:zc(e,t),httpHeaderWrites:Qc(e,t),hyperdriveCalls:cr(e,t),identityClaimReads:al(e,t),imageDeliveryUrlAccesses:ll(e,t),inserts:n.inserts,kvKeyAccesses:ul(e,t,a),mailRecipientAccesses:hl(e,t),maskProcedures:lr(e,t),maskStrategies:xl(e,t),mutatorWrites:wl(e,t),nondeterministicCalls:pr(e,t),normalizeIdAuthorizations:zl(e,t),notifyCalls:hr(e,t),notifyConfig:mr(e,t),mutators:l,ownerFieldWrites:Dd(e,t,a,l),unrestrictedWhereBranches:sg(e,t),paymentWebhooks:zd(e,t),privilegedDispatches:Xd(e,t),procedureProtections:Lu(e,t),queries:n.queries,queues:u,r2sqlCalls:vr(e,t),ratelimitKeySelectors:$u(e,t),rawRowReturns:Gu(e,t),relationLoads:Xu(e,t),rlsProcedures:Er(e,t),schema:f,secretLiterals:gf(e,t),modules:c,shapes:g,softDeleteReads:mf(e,t),sqlInterpolations:Sf(e,t),storageKeyAccesses:wf(e,t,a),storageUploads:kf(e,t),tableWrites:n.tableWrites,rowEffects:cf(e,t,n.tableWrites,n.callEdges),unboundedLoops:zf(e,t),vectorNamespaceAccesses:og(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:p})},cg=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),lg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>cg(i))]},dg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),ug=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",Ws={error:"ERROR",info:"INFO",warn:"WARN"},Hs={ERROR:2,INFO:0,WARN:1},fg=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"}),gg=(e,t)=>{const{advisor:s}=vn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(Ws,n)?Ws[n]:void 0;return i===void 0?[...t,fg(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>ug(o)||Hs[o.level]>=Hs[i])},pg=(e,t)=>{const{advisor:s}=vn(e),n=lg(t,s?.accept??[]);return gg(e,s?.acceptUnreadable===!0?[...n,dg()]:n)},mg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},hg="crons",vg=Pr.replace(/\.ts$/u,""),oe=(e,t)=>`${Dt(e)}:${t}`,gt=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},Eg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${mg[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...gt("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...gt("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...gt("workflow",t.workflow,"workflow name")}))],xg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",Sg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:xg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Ag=e=>Eg(e).flatMap(t=>Sg(t)),yg=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:hg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],bg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),ge=(e,t)=>t===void 0?e:{...e,module:t},Ng=e=>{const t=new Map,s=new Map,n=bg(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(oe(c.file,c.exportName),l)};for(const c of e.functions){const l=oe(c.filePath,c.exportName),u=[...xr(c.filePath),c.exportName].join(".");o(ge({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Ce(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=oe(c.filePath,c.exportName);o(ge({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Ce(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(ge({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(ge({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Ce(e.modules,c.filePath)),oe(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(ge({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Ce(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},oe(vg,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},wg=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,Pg=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(oe(e.file,e.exportName))??{reason:wg(e.exportName)},Ig=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=Pg(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},pt=e=>`${e.from}|${e.kind}|${e.to}`,Cg=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Tg=e=>{const{nodes:t,sites:s}=Ng(e),n=new Map,i=new Map;for(const o of[...yg(e),...Ag(e)]){const a=Ig(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(pt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Cg(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>pt(o).localeCompare(pt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},Og=e=>`${Tr}export const architecture = ${Cr(e,"Record<string, unknown>")};
4
+ `,js=(e,t="api")=>{const s=new Map;for(const n of e){const i=Dt(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new U("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},kg=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>Sn(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=>An(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:kr)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},Rg=(e,t,s={})=>{if(t===void 0)return;const n=kg(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
5
+ `);throw new U("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
6
+ ${i}
7
+
8
+ Install them with your package manager, then re-run codegen.`)},Fg="env.ts",Lg=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Dg=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ue(n.getModuleSpecifierValue())}return!1},Mg=e=>{if(r.isIdentifier(e))return Lg(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Dg(t)}return!1},_g=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Mg(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw Se(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=fn(s,"member");a!==void 0&&t.push({exportName:a})}return t},Kg=(e,t)=>{const s=v(t,Fg);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=_g(n);if(i.length!==0){if(i.length>1)throw Se(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Bg=new Set(["allowedHosts","deniedHosts","interceptHttps"]),zg=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},$g=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Vg=new Set(["durable"]),Ug=new Set(["rollback"]),qg=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},Wg=new Map([["defineContainer",{keys:Bg,signal:"containerEgressPolicy"}],["defineStep",{keys:Ug,signal:"workflowRollback"}],["stream",{keys:Vg,signal:"durableStreams"}]]),Hg=(e,t)=>{const s=Wg.get(qg(t));if(s!==void 0)return t.getArguments().some(n=>$g(zg(e,n),s.keys))?s.signal:void 0},jg=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Mr(i).has("secrets"));for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=Hg(i,o);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},Gg="createWorker",Yg="extend",Gs=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Ys=e=>{const t=[],s=Gs(C(e,"backupCron"));s!==void 0&&t.push(s);const n=C(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=Gs(i.getNameNode());o!==void 0&&t.push(o)}return t},Qg=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Gg)return r.isObjectLiteralExpression(s)?Ys(s):[];if(t!==Yg||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=on(s.getBody());return n===void 0?[]:Ys(n)},Xg=(e,t)=>{const s=[];for(const{filePath:n}of ze(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression))s.push(...Qg(o))}return[...new Set(s)]},oi=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:oi(e.inner)},Jg=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=oi(n);return i!==void 0&&t.has(i)}))},Zg=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new U("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new U("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},ep=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=tl(s,t),a=Kg(s,t),c=Ir(s,t),{queues:l,topics:u}=Kr(s,t),f=zr(n),g=Fr(s,t);Zg(c,g);const p=Lr(s,t),x=$r(s,t),k=Dr(s,t,c,g),X=Xg(s,t),L=jg(s,t),N=Br(s,t),K=_r(s,t);K.browser=K.browser||N.usesSandboxBrowser;const G=bn(n,e.target),w=Vr(K,G,{agents:g.length>0,commitOrderedTables:i.tables.some(R=>R.commitOrdered===!0),cronTriggers:k.length>0,crossShardFanout:i.tables.some(R=>Hr(R)),containerEgressPolicy:L.containerEgressPolicy,containerRuntimeScheduling:p.some(R=>R.schedulingPolicy==="durable_object"),containerSandboxTools:p.some(R=>R.sandbox===!0),durableStreams:L.durableStreams,globalTables:i.tables.some(R=>R.shardMode==="global"),queues:l.length>0,relationGraph:Jg(i),secrets:L.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:L.workflowRollback,workflowSchedules:c.some(R=>R.schedules!==void 0)}),Y=w.usage,ne=Rr(Y),ce=w.signals.vectorStore!==!1,le=w.signals.services===!1?[]:f,de=yn(n),V=de??new Set,M=V.has("lunorash");Rg(i,de,{hasVectors:ce,scheduler:Y.scheduler||k.length>0,storage:Y.storage||x.rules.length>0||Object.keys(Nn(i)).length>0,usage:Y});const _=F(v(t,"flags.ts")),Ae=F(v(t,"notify.ts"));return{agents:g,capabilities:ne,containers:p,crons:k,dataModelContent:Qr(i),declaredDependencies:de,dependencies:V,entryCronTriggers:X,env:a,featureUsage:Y,hasFlags:_,hasNotify:Ae,identity:o,platformGate:{...w,diagnostics:[...Ur(n,e.target),...w.diagnostics,...qr(G,i.vectorIndexes)]},queues:l,serverContent:Gr({agents:g,capabilities:ne,containers:p,env:a,hasVectors:ce,hasFlags:_,hasNotify:Ae,identity:o,queues:l,schema:i,services:le,storageRuleBuckets:x.rules.map(R=>R.bucket),topics:u,useUmbrella:M,workflows:c}),services:le,storageRulesMetadata:x,topics:u,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:M,workflows:c}},ai=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},tp=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},sp=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),np=/^[\w$]+:[\w$]+$/u,ip=(e,t)=>{const s=un(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Qs=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},rp=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Qs(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Bi.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Qs(s):void 0}}},op=(e,t,s)=>({schedule:{argKeys:rp(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),ap=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(dn.has(s))return ip(s,n);if((s==="runAfter"||s==="runAt")&&tp(t)){const l=un(i)??(r.isStringLiteral(i)&&np.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...op(s,n,o)}}const a=sp.get(s),c=a===void 0?void 0:ai(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},cp=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),ci=e=>Ki.isOptionalChain(e.compilerNode),lp=(e,t)=>r.isIfStatement(t)?!y(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?y(e,t.getStatement()):r.isForStatement(t)?y(e,t.getStatement())||y(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:ee(t)?t.getFirstAncestor(ee)!==void 0:r.isConditionalExpression(t)?!y(e,t.getCondition()):r.isBinaryExpression(t)?!y(e,t.getLeft())&&cp.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&ci(t)?!y(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Lf(s)),dp=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&y(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(ee);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&y(o.getFirstAncestor(ee),i))===!0},up=(e,t)=>{if(ci(e)||t==="schedule"&&dp(e))return!0;let s=e;for(let n=s.getParent();n!==void 0&&!r.isSourceFile(n);n=n.getParent()){if(lp(s,n))return!0;s=n}return!1},Xs=(e,t,s)=>s===void 0?void 0:{...s,...up(e,s.kind)?{conditional:!0}:{},file:t,line:e.getStartLineNumber(),scope:E(e)},fp=(e,t)=>[...T(e,t,(s,n)=>Xs(s,n,ap(s))),...J(e,t,d.PropertyAccessExpression,(s,n)=>{const i=ai(s,"services");return Xs(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],gp=new Set(["boolean","number","object","string"]),pp=e=>{const t=e.getName();if(!gp.has(t))return;const s=e.getExpression();return q(s,["flags"])||q(s,["flags","details"])?t:void 0},mp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=pp(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},hp=(e,t)=>{const s=new Map;for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=mp(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},vp=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||Xr(o))return;const a=e.getSourceFile().getFilePath();if(Jr(i,e,a)){const c=Zr(i,e,a,0,new Set);return c===void 0&&eo(o),c}return o},Ep=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=nr(t.getNameNode());return s===void 0||s==="namespace"}),xp=(e,t)=>{for(const{filePath:s}of ze(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||Ep(a)))return i}}},Sp="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Ap=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw Se(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${Sp}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},yp=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,bp=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?yp(e):!0,li=(e,t=!1)=>{for(const s of e.getProperties()){if(bp(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||li(n,!0))return!0}return!1},Np=(e,t)=>{for(const s of S(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of wn(n))for(const o of Lt(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||li(a)))return!0}}return!1},wp=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Le(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Le(a);c!==void 0&&s.push({column:c,strategy:En(a),table:i})}}return s},Pp=(e,t)=>{const s=new Map;for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of wn(i))for(const a of Lt(o))for(const c of wp(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Ip=["providerSubscriptionId","state"],Cp=["providerEventId","processedAt"],Js=(e,t)=>t.every(s=>s in e.shape),Tp=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Js(t,Ip)&&Js(s,Cp)},Op=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],kp=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},Rp=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},Fp="@lunora/privacy",di="userId",Lp=e=>e.replaceAll("\\","/"),Dp="privacy",Mp=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),He=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,je=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",Vt=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),_p=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},Ge=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Kp=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=_p(s,"tables"),i=He(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:Vt(n).map(a=>je(a)))t.datasets.set(o,i)},Bp=(e,t)=>{const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)?Vt(s):[],i=new Set(n.map(o=>je(o)));for(const o of Op)i.has(o)||t.datasets.set(o,"authDataset");for(const o of n){const a=r.isPropertyAssignment(o)?He(o.getInitializer()):void 0;a!==void 0&&t.datasets.set(a,"authDataset")}},Zs=(e,t,s)=>{t.datasets.set(He(e.getArguments()[0])??s,s)},Ut=8,xe=(e,t=0)=>{if(t>Ut)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return xe(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:xe(i,t+1)},zp=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[je(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},ui=(e,t=0)=>{const s=xe(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Ut)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?ui(i.getExpression(),t+1):[zp(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},$p=e=>{const t=e.getArguments()[0];return t===void 0?void 0:ui(t)},Vp=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:xe(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?Vt(n):[])t.excluded.set(je(i),r.isPropertyAssignment(i)?He(i.getInitializer())??"":"")},Up=(e,t)=>{switch(Ge(e)){case"actionCacheDataset":{Zs(e,t,"actionCache");break}case"authDataset":{Bp(e,t);break}case"defineDataset":{Kp(e,t);break}case"documentHistoryDataset":{Zs(e,t,"documentHistory");break}}},qt=e=>e!==void 0&&r.isCallExpression(e)&&Ge(e)==="defineDataset",fi=e=>e!==void 0&&r.isCallExpression(e)&&Mp.has(Ge(e)??""),qp=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(qt(i)||fi(i))?n:void 0},gi=(e,t,s=0)=>{const n=xe(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Ut)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!gi(i.getExpression(),t,s+1))return!1}else if(!qt(i)&&!fi(i)){const o=r.isIdentifier(i)?qp(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},Wp=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||gi(t,s)?s:void 0},Hp=(e,t)=>{const s=[];for(const i of e.getDescendantsOfKind(d.CallExpression))if(Up(i,t),Ge(i)==="definePrivacy"){const o=$p(i);Vp(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:Wp(o)})}return{declared:e.getDescendantsOfKind(d.VariableDeclaration).filter(i=>qt(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},jp=(e,t)=>{const s=v(t,"schema.ts"),n=[...S(t),...F(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Lp(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},Gp=(e,t,s)=>{if(s?.has(Fp)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[]};const n={datasets:new Map,excluded:new Map},i=[],o=[];for(const f of jp(e,t)){const g=Hp(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:kp(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l}},Yp=e=>e.extensionKey!==Dp&&di in e.shape,Qp=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (it has a "${di}" column) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Xp=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Yp(o)).map(o=>o.name),[n]=Rp(s,t.classifications);if(n!==void 0)throw new U("PRIVACY_COVERAGE",Qp(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new U("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Jp=(e,t)=>{const s=Wr(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Zp=new Set(["delete","hardDelete","patch","replace","restore"]),em=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),tm=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),en=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},sm=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:en(i,e)}return en(s,e)},tn="",nm=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},im=(e,t)=>{if(em.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():tn]};if(Zp.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:sm(t,e);return{method:e,tables:s.length===0?[tn]:s}}},sn=(e,t)=>e===void 0?void 0:{...e,fields:nm(t,e.method)},rm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if(z(n))return sn(im(s,e.getArguments()[0]),e);if(tm.has(s)&&r.isPropertyAccessExpression(n)&&z(n.getExpression()))return sn({method:s,tables:[n.getName()]},e)},om=(e,t)=>T(e,t,(s,n)=>{const i=rm(s);if(i===void 0)return;const o=E(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),am=(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"}),cm=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||D(s,"args")===void 0)return!1}return _t(e,t).opaque},lm=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=Q(a);c!==void 0&&cm(a,c.receiver)&&s.push(am(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},dm=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...lm(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},um=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Be=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),pi=e=>!e.isAny(),mi=e=>{const t=e.getType();if(!pi(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:um.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},fm=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},hi={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."},gm=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.`}),pm={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},mm=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),hm={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},vm=(e,t,s)=>{if(!t.some(i=>Yi(i)))return pm;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return mm.has(s.typeName)&&!n&&!t.some(i=>fo(i))?hm:hi},vi=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:gm(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},Em=(e,t,s)=>{const n=[];for(const i of j(e)){const o=r.isIdentifier(i.getNameNode())?Et(i):[i.getName()],c=o.some(u=>Be(s,t,u))||!fm(i)?void 0:mi(i),[l=i.getName()]=o;c!==void 0&&n.push(vi(t,l,c,i.getStartLineNumber(),vm(i,o,c)))}return n},xm=(e,t,s)=>{if(Be(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=mi(i.getExpression());o!==void 0&&n.push(vi(t,"default",o,i.getStartLineNumber(),hi))}return n},Sm=(e,t,s)=>[...Em(e,t,s),...xm(e,t,s)],Am=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>Et(n).some(i=>Be(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=Et(n).find(o=>Be(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),ym=({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"}),bm=(e,t,s)=>{const n=[],i=[];for(const a of S(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...Sm(c,l,s)),i.push(...Am(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!pi(a.getType()))&&n.push(ym(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Nm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},wm=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Pm=(e,t)=>T(e,t,(s,n)=>Nm(s)?{file:n,line:s.getStartLineNumber(),scope:E(s),workflow:wm(s)}:void 0),Ye=(e,t)=>{F(e)&&ki(e,"utf8")===t||Ri(e,t,"utf8")},Im=(e,t)=>{if(t===""){ht(e,{force:!0});return}Ye(e,t)},Cm=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){ht(s,{force:!0,recursive:!0});return}if(F(s))for(const n of Fi(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Li(e,i)]===void 0&&ht(i)}for(const[n,i]of Object.entries(t))nn(rn(v(e,n)),{recursive:!0}),Ye(v(e,n),i)},Tm=e=>{try{const t=po(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},ae=(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,Om=(e,t)=>{F(e)||nn(e,{recursive:!0});const s=[];for(const n of t)n.kind==="services"?(Cm(e,n.files),s.push(...Object.keys(n.files))):n.kind==="always"?(Ye(v(e,n.name),n.content),s.push(n.name)):(Im(v(e,n.name),n.content),n.content!==""&&s.push(n.name));return s},km=e=>{const t=Tm(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=ho({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=Eo({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
9
+ `,openApiModuleContent:vo(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
10
+ `,openRpcModuleContent:xo(i)}},Rm=".lunora-schema.json",Fm=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Lm=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new U("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new U("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new U("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},Dm=8,Mm=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lunoraDirectory:o,migrations:a,project:c,shapes:l,usesSandbox:u,useUmbrella:f,workflows:g}=e,p=()=>so(()=>{const N=no(c,o),K=gr(c,o);return{functions:N,httpRoutes:io(c,o),mutators:K}});let{erased:x,value:{functions:k,httpRoutes:X,mutators:L}}=p();js([...k,...L].map(N=>N.filePath)),js(X.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const K=Io({agents:t,functions:k,httpRoutes:X,mutators:L,useUmbrella:f,workflows:g}),G=Mo({agents:t,functions:k,migrations:a,mutators:L,shapes:l,useUmbrella:f,usesSandbox:u}),w=Co({functions:k,useUmbrella:f});if(N>=Dm||mt(c,s,K)&&mt(c,i,w)&&mt(c,n,G))return{apiContent:K,erased:x,functions:k,functionsContent:G,httpRoutes:X,internalContent:w,mutators:L};ae(c,s,K),ae(c,i,w),ae(c,n,G),{erased:x,value:{functions:k,httpRoutes:X,mutators:L}}=p()}},Jh=e=>{const t=Fm(),s=t?rt.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=v(n,"schema.ts");if(!F(i))throw new U("INTERNAL",`schema.ts not found at ${i}`);const o=e.project??Or(n);or(vp);const a=lo(o,i,e.projectRoot);Xp(a.tables,Gp(o,n,yn(e.projectRoot)));const{agents:c,capabilities:l,containers:u,crons:f,dataModelContent:g,dependencies:p,entryCronTriggers:x,env:k,featureUsage:X,hasFlags:L,hasNotify:N,identity:K,platformGate:G,queues:w,serverContent:Y,services:ne,storageRulesMetadata:ce,topics:le,usesSandbox:de,useUmbrella:V,workflows:M}=ep({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});Ap(a,a.jurisdiction===void 0?void 0:xp(o,n));const _=v(n,"_generated"),Ae=v(_,"dataModel.ts"),R=v(_,"server.ts"),Ei=v(_,"api.ts"),xi=v(_,"internal.ts"),Si=v(_,"functions.ts");ae(o,Ae,g),ae(o,R,Y);const Wt=Object.fromEntries(ne.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(Yr(m,_))));for(const[m,it]of Object.entries(Wt))ae(o,v(_,m),it);const ye=oo(o,n),ie=uo(o,n),{apiContent:Ht,erased:Ai,functions:re,functionsContent:jt,httpRoutes:Qe,internalContent:Gt,mutators:Xe}=Mm({agents:c,apiPath:Ei,generatedFunctionsPath:Si,internalPath:xi,lunoraDirectory:n,migrations:ye,project:o,shapes:ie,useUmbrella:V,usesSandbox:de,workflows:M}),Yt=Nr(o,n),Je=wr(Yt,a,[...re,...Qe].map(m=>m.filePath)),be=Yt.length>0,Ne=e.lint===!1&&!be?void 0:{callEdges:fp(o,n),inserts:ro(o,n),queries:ao(o,n,re),tableWrites:om(o,n),workflowCalls:Pm(o,n)},we=e.lint===!1||Ne===void 0?void 0:ag(o,n,{callSites:Ne,containers:u,crons:f,functions:re,modules:Je,mutators:Xe,queues:w,schema:a,shapes:ie,workflows:M,wranglerVariables:e.wranglerVariables}),Qt=we===void 0?[]:pg(e.projectRoot,[...Di(we,{source:"static"}),...bm(o,n,{byName:new Set([...M,...w,...c,...u].map(m=>m.exportName)),byPath:new Set([...re,...Xe,...ie,...ye].map(m=>`${m.filePath}:${m.exportName}`))}),...dm(o,n),...to(Ai,n),...So(w,e.wranglerQueueProducers)]),yi=co(o,n),Xt=Pp(o,n);Lm(ie,Xt,Np(o,n));const bi=L?hp(o,n):[],Ze=G.signals.vectorStore!==!1,ue=Jp(X,{containerCount:u.length,cronCount:f.length,dependencies:p,hasPaymentTables:Tp(a.tables),queueCount:w.length,storageColumnCount:Object.keys(Nn(a)).length,storageRuleCount:ce.rules.length,vectorIndexCount:a.vectorIndexes.length,target:bn(e.projectRoot,e.target),vectorStoreSupported:Ze,workflowCount:M.length}),Jt=t?rt.now():0,et=mo(a,ye.map(m=>m.id)),Zt=jr({advisories:Qt.filter(m=>m.name!=="procedure_type_check_unavailable"),advisorProcedures:we?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:k,flagKeys:bi,hasFlags:L,hasNotify:N,hasVectors:Ze,maskMetadata:Xt,mutators:Xe,queues:w,rlsMetadata:yi,schema:a,schemaSnapshot:et,shapes:ie,services:ne,storageRules:ce,studioFeatures:ue,topics:le,useUmbrella:V,workflows:M}),es=wo(ie,p.has("@lunora/db"),V),ts=Ao(u,a.jurisdiction),ss=yo(M),ns=bo(c),is=No(w,e.wranglerQueueProducers),rs=To(f),Ni=Oo(ue.scheduler),wi=ko(a.tables,V),Pi=ir(e.projectRoot)?Ro(V):"",os=Fo(a.vectorIndexes),Pe=Do(a,V),as=Po(p.has("@lunora/seed")),Ie=e.apiSpec??"openapi",tt=Ie==="openapi"||Ie==="both",st=Ie==="openrpc"||Ie==="both",cs=go({capabilities:l,emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:p.has("@lunora/cloudflare-access"),hasAuth:p.has("@lunora/auth"),hasFramework:p.has("@lunora/astro")||p.has("@lunora/svelte")||p.has("@lunora/vue")||F(v(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(m=>Sn(m)),hasHyperdriveGlobal:a.tables.some(m=>An(m)),hasKvIntrospector:ue.kv,hasNotify:N,hasQueue:w.some(m=>m.mode==="push"),hasScheduler:ue.scheduler,hasSourcedTables:a.tables.some(m=>m.externalSource!==void 0),hasStorage:ue.storage,hasVectors:Ze,hasWorkflow:M.length>0,identity:K,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(m=>({name:m.name,shardMode:m.shardMode})),useUmbrella:V,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:be,wantsOpenApi:tt,wantsOpenRpc:st}),{openApiContent:ls,openApiModuleContent:ds,openRpcContent:us,openRpcModuleContent:fs}=km({functions:re,httpRoutes:Qe,modules:Je,projectRoot:e.projectRoot,wantsArchitecture:be}),fe=be&&Ne!==void 0?Tg({...Ne,crons:f,functions:re,httpRoutes:Qe,modules:Je,queues:w,schema:a,services:ne,topics:le,workflows:M}):void 0,nt=v(n,Rm),Ii=F(nt),Ci=e.dryRun?[]:Om(_,[{content:cs,kind:"always",name:"app.ts"},{content:g,kind:"always",name:"dataModel.ts"},{content:Ht,kind:"always",name:"api.ts"},{content:Gt,kind:"always",name:"internal.ts"},{content:Y,kind:"always",name:"server.ts"},{content:jt,kind:"always",name:"functions.ts"},{content:Zt,kind:"always",name:"shard.ts"},{content:rs,kind:"always",name:"crons.ts"},{content:os,kind:"always",name:"vectors.ts"},{content:Pe.global,kind:"always",name:"drizzle.global.ts"},{content:Pe.shard,kind:"always",name:"drizzle.shard.ts"},{content:ts,kind:"optional",name:"containers.ts"},{content:ss,kind:"optional",name:"workflows.ts"},{content:ns,kind:"optional",name:"agents.ts"},{content:is,kind:"optional",name:"queues.ts"},{content:Ni,kind:"optional",name:"scheduler.ts"},{content:wi,kind:"optional",name:"shardRegistry.ts"},{content:Pi,kind:"optional",name:"durableObjects.ts"},{content:as,kind:"optional",name:"seed.ts"},{content:es,kind:"optional",name:"collections.ts"},{files:Wt,kind:"services"},{content:tt?ls:"",kind:"optional",name:"openapi.json"},{content:tt?ds:"",kind:"optional",name:"openapi.ts"},{content:st?us:"",kind:"optional",name:"openrpc.json"},{content:st?fs:"",kind:"optional",name:"openrpc.ts"},{content:fe===void 0?"":`${JSON.stringify(fe,void 0,2)}
11
+ `,kind:"optional",name:"architecture.json"},{content:fe===void 0?"":Og(fe),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!Ii||e.updateSchemaBaseline===!0)&&Ye(nt,Mi(et)),t){const m=rt.now(),it=Math.round(m-s),Ti=Math.round(Jt-s),Oi=Math.round(m-Jt);console.error(`@lunora/codegen: codegen took ${it.toString()}ms (discovery ${Ti.toString()}ms, emit ${Oi.toString()}ms)`)}return{advisories:Qt,advisorContext:we,agents:c,architecture:fe,containers:u,cronTriggers:[...new Set([...Lo(f),...x])],generated:{agents:ns,api:Ht,app:cs,collections:es,containers:ts,crons:rs,dataModel:g,drizzleGlobal:Pe.global,drizzleShard:Pe.shard,functions:jt,internal:Gt,openApi:ls,openApiModule:ds,openRpc:us,openRpcModule:fs,queues:is,seed:as,server:Y,shard:Zt,vectors:os,workflows:ss},migrations:ye,outputDirectory:_,platformDiagnostics:G.diagnostics,queues:w,schemaSnapshot:et,schemaSnapshotPath:nt,workflows:M,writtenFiles:Ci}};export{Rm as SCHEMA_SNAPSHOT_FILENAME,Or as createCodegenProject,tv as findTsconfig,sv as refreshCodegenProject,Jh as runCodegen};
@@ -1 +1 @@
1
- import"./isTestPath-B81lOULB.mjs";import"./attribution-hVBriwzy.mjs";import"./database-calls-CHZbBUCZ.mjs";import"./classify-procedure-call-BAj0D1u2.mjs";import{d as a}from"./index-BW4hJ4Wm.mjs";export{a as default};
1
+ import"./isTestPath-B81lOULB.mjs";import"./attribution-hVBriwzy.mjs";import"./database-calls-CHZbBUCZ.mjs";import"./classify-procedure-call-BAj0D1u2.mjs";import{d as a}from"./index-DZZpHXMv.mjs";export{a as default};
@@ -0,0 +1 @@
1
+ import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-B81lOULB.mjs";import{b as p,d}from"./attribution-hVBriwzy.mjs";import{t as m}from"./database-calls-CHZbBUCZ.mjs";import{c as b}from"./classify-procedure-call-BAj0D1u2.mjs";import{r as h}from"./chain-CRDaTj2c.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=h(e);return{rlsTables:t.flatMap(r=>g(r)),usesRls:t.length>0}},v=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=m(e,v,x);return{exportName:d(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},M=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=P(a,n);l&&r.push(l)}}return r};export{M as default};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{Node as i,SyntaxKind as C}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as B}from"node:module";import{join as _}from"node:path";import{fileURLToPath as V}from"node:url";import{createJiti as q}from"jiti";import{findObjectProperty as u}from"./isTestPath-B81lOULB.mjs";import{r as J,p as U}from"./parse-validator-IDBKIT7M.mjs";import{R as K}from"./reserved-words-CW1QFbTd.mjs";import{a as I}from"./project-config-file-BV7RR-l6.mjs";const W=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,Z=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},G=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:G(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=Z(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},X=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",H=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},Q=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return H(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:X(e.shardMode),vectorIndexes:[]}},Y=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>Q(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},ee=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},te=e=>{const t=ee(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},ne=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},re=(e,t)=>{const n=te(e);if(n)try{const s=q(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=B(_(t,"noop.cjs"))(s.startsWith("file:")?V(s):s),o=ne(r,n);return typeof o!="object"||o===null?void 0:Y(o)}catch{return}},se=new Set(["cosine","dot-product","euclidean"]),h=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=h(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},b=(e,t)=>{const n=h(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},A=(e,t)=>{const n=h(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},x=(e,t)=>{const n=h(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},N=e=>e&&se.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ie=(e,t)=>{const n=x(e,t);return n!==void 0&&n.length>0?n:void 0},P=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=c.getLiteralText();if(!s.has(m))throw d(c,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},oe=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ae=/^(?:sqlite_|_cf_|__)/u,le=/__(?:agg|rank|geo|fts)_/u,ce=e=>ae.test(e)||le.test(e),de=new Set(["cascade","restrict","set null"]),fe=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,w=(e,t)=>{if(fe.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(K.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(ce(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ue=e=>e&&de.has(e)?e:void 0,pe=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},me=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",m;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,m=s==="one"?ue(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:m,references:c,table:a}},ge=e=>{const t=pe(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=me(s);r&&n.push(r)}return n},he=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},be=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},xe=e=>{const[t,n,s]=e,r=be(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)he(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},ye=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"filterFields"),o=f(n,"language"),a=A(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},ve=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=b(n,"precision")),{field:s,name:y(t),precision:r}},Ee=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=b(n,"after")),{after:r,field:s}},Ie=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},we=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Ie(l)).filter(l=>l!==void 0))}r=x(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},ke=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:b(s,"dimensions"),field:r,metadata:x(s,"metadata"),metric:N(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Se=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},O=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw d(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw d(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Te=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ie(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},_e=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ve(n));break}case"global":{e.shardMode="global",e.globalBackend=Se(n);break}case"index":{e.indexes.push(xe(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(we(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ge(r));break}case"searchIndex":{e.searchIndexes.push(ye(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:O(n[0],"deletedAt")};break}case"source":{e.externalSource=Te(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(O(n[0],"updatedAt"));break}case"ttl":{e.ttl=Ee(n);break}case"vectorize":{const r=ke(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Oe=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Le=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,oe(t))},Ae=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw d(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw d(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw d(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},j=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))_e(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=U(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=Ae(e,s,n),Oe(e,t,n.searchIndexes),Le(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},D=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=J(r.getExpression());a!==void 0&&!s.has(a)&&D(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(w(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(j(o,a))}}return t},Ne=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Pe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:b(s,"dimensions"),metric:N(f(s,"metric")),name:o,table:Ne(s)}},z=e=>{const t=[];for(const n of e.getProperties()){const s=Pe(n);s&&t.push(s)}return t},k=(e,t)=>`${e}_${t}`,$e=(e,t)=>{if(!$.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?k(t,e):e,je=(e,t,n,s)=>{const r=k(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},De=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},ze=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Me=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Fe=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Re=(e,t)=>{const n=De(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Fe(n);return s?h(s,t.getName()):void 0}return n}},Ce=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,ze(t))return t;const s=Me(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Re(a,t)}},Be=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ve=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);w(a,r.getNameNode()),s.push(j(o,a))}return s},qe=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:z(n)},M=(e,t,n,s,r)=>{$e(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>je(c,e,o,r)),l=n.map(c=>({...c,name:k(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},Je=(e,t,n)=>M(e,Ve(n),qe(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ue=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Ce(n);if(!s){if(t!==void 0){const o=re(n,t);if(o){for(const a of o.bareTables)w(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Be(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Je(r.key,r.keyNode,r.options)},Ke=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},We=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ke(e)){const a=Ue(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Ze=new Set(["eu","fedramp","us"]),Ge=e=>P(e,"jurisdiction","jurisdiction",Ze,'"eu", "us", or "fedramp"'),Xe=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&A(r,"pinAuth")===!0}t=s}},He=new Set(["required"]),Qe=e=>P(e,"rls","rls mode",He,'"required"'),dt=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(C.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new R("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=D(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?z(l):[],m=We(r,a,n),S=[...a.flatMap(p=>p.vectorIndexes),...c,...m],F=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=S.find(p=>F.has(p.table));if(v)throw d(r,W(v.table,v.name));return{jurisdiction:Ge(r),...Xe(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:Qe(r),tables:a,vectorIndexes:S}};export{dt as default};
@@ -1,4 +1,4 @@
1
- import{r as k}from"./qualifiers-DEdXn5wP.mjs";import{a as s,e as i,v as d,f as v,G as M}from"./shared-DnCokNcE.mjs";const D="schema",w=a=>{for(const e of a.tables)s(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([h,r])=>{const o=i(h);if(r.kind==="optional"){const g=r.inner?d(r.inner):"unknown";return` ${o}?: ${g};`}return` ${o}: ${d(r)};`}).join(`
1
+ import{r as k}from"./qualifiers-DEdXn5wP.mjs";import{a as i,e as o,v as d,f as v,G as M}from"./shared-DnCokNcE.mjs";const _="schema",w=a=>{for(const e of a.tables)i(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([g,r])=>{const s=o(g);if(r.kind==="optional"){const h=r.inner?d(r.inner):"unknown";return` ${s}?: ${h};`}return` ${s}: ${d(r)};`}).join(`
2
2
  `),n=t?`
3
3
  ${t}
4
4
  `:"",N=e.commitOrdered===!0?`
@@ -14,7 +14,7 @@ ${t}
14
14
  `),T=a.vectorIndexes.map(e=>JSON.stringify(e.name)).join(" | ")||"never",$=a.tables.map(e=>v(e)).join(`
15
15
 
16
16
  `),u=a.tables.map(e=>` ${e.name}: Insert_${e.name};`).join(`
17
- `),I=a.tables.map(e=>{const t=e.relations.map(n=>(s(n.table,"relation target table"),` ${i(n.name)}: ${n.kind==="one"?"OneRelation":"ManyRelation"}<"${n.table}">;`)).join(`
17
+ `),I=a.tables.map(e=>{const t=e.relations.map(n=>(i(n.table,"relation target table"),n.kind==="one"?` ${o(n.name)}: OneRelation<"${n.table}", ${JSON.stringify(n.field)}>;`:` ${o(n.name)}: ManyRelation<"${n.table}">;`)).join(`
18
18
  `);return t?` ${e.name}: {
19
19
  ${t}
20
20
  };`:` ${e.name}: {};`}).join(`
@@ -95,7 +95,8 @@ export type Insert<T extends keyof DataModel> = InsertModel[T];
95
95
  * as type parameters only — there is no runtime value — so the \`with\` argument
96
96
  * and its return type can be inferred from {@link Relations}.
97
97
  */
98
- export interface OneRelation<Target extends keyof DataModel> {
98
+ export interface OneRelation<Target extends keyof DataModel, Field extends string> {
99
+ readonly __field: Field;
99
100
  readonly __relationKind: "one";
100
101
  readonly __target: Target;
101
102
  }
@@ -110,4 +111,4 @@ export interface Relations {
110
111
  ${I}
111
112
  }
112
113
 
113
- `,D)};export{D as SCHEMA_MODULE_PATH,w as emitDataModel};
114
+ `,_)};export{_ as SCHEMA_MODULE_PATH,w as emitDataModel};
@@ -1,4 +1,4 @@
1
- import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-DdtjdNg3.mjs";import{r as m}from"./qualifiers-DEdXn5wP.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-DnCokNcE.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
1
+ import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-BskFt9Wv.mjs";import{r as m}from"./qualifiers-DEdXn5wP.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-DnCokNcE.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
2
2
  `),n=e.indexes.length>0?`, (t) => ({
3
3
  ${e.indexes.map(o=>I(o)).join(`
4
4
  `)}
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-Ct-49zW9.mjs";import"./shard-runtime-BX0xmo0P.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as d}from"./shard-BWVyL-4A.mjs";import"./shard-runtime-BX0xmo0P.mjs";import"./shared-DnCokNcE.mjs";import"./platform-8oj7iXQy.mjs";import"./schema-BgM8A3XV.mjs";export{d as default};
@@ -0,0 +1 @@
1
+ import{Node as r}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-B81lOULB.mjs";import{b as m,d as p}from"./attribution-hVBriwzy.mjs";import{t as d}from"./database-calls-CHZbBUCZ.mjs";import{w as g,c as h}from"./classify-procedure-call-BAj0D1u2.mjs";import{a as k}from"./project-config-file-BV7RR-l6.mjs";const l=e=>{if(!(!r.isPropertyAssignment(e)&&!r.isShorthandPropertyAssignment(e)&&!r.isMethodDeclaration(e)&&!r.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(r.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&r.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!r.isObjectLiteralExpression(s))return[];const t=[];for(const i of s.getProperties()){const o=l(i);if(o===void 0||!r.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!(!n||!r.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),x=(e,s)=>{if(!r.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const i=h(t);if(!i)return;const o=i.receiver?y(i.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:i.visibility}},E=(e,s)=>{const t=[];for(const i of u(s)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i),n=f(s,i);for(const a of m(o)){const c=x(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};
@@ -1120,7 +1120,7 @@ const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.st
1120
1120
  vectors?: (env: Record<string, unknown>) => Record<string, VectorizeIndexLike>;`:"",Ge=z?`
1121
1121
  d1?: (env: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string }) => DatabaseWriterLike | undefined;`:"",Qe=j?`
1122
1122
  hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",ze=T?`
1123
- sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Xe="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",Je="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",Ye="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Ze=x?C("globalDbStub: DatabaseWriterLike",Xe,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:et,vectorsBuild:tt,vectorsStub:rt}=cr(u,Q?i.vectorIndexes.filter(s=>B.has(s.table)).map(s=>s.name):[]),at=`{
1123
+ sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",Xe="ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().",Je="ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().",Ye="ctx.storage: no storage configured. Pass `storage` to createShardDO().",Ze=x?C("globalDbStub: DatabaseWriterLike",Xe,["aggregate","count","delete","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",{vectorSyncMethod:et,vectorsBuild:tt,vectorsStub:rt}=cr(u,Q?i.vectorIndexes.filter(s=>B.has(s.table)).map(s=>s.name):[]),at=`{
1124
1124
  ...this.ctxDbTuning(),
1125
1125
  auth: { identity: identity ?? null, userId: userId ?? null },
1126
1126
  broadcast: (delta) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.294",
3
+ "version": "1.0.0-alpha.296",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.209",
50
- "@lunora/agent": "1.0.0-alpha.198",
49
+ "@lunora/advisor": "1.0.0-alpha.210",
50
+ "@lunora/agent": "1.0.0-alpha.199",
51
51
  "@lunora/container": "1.0.0-alpha.73",
52
52
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
53
- "@lunora/platform": "1.0.0-alpha.60",
54
- "@lunora/queue": "1.0.0-alpha.100",
55
- "@lunora/scheduler": "1.0.0-alpha.119",
53
+ "@lunora/platform": "1.0.0-alpha.61",
54
+ "@lunora/queue": "1.0.0-alpha.101",
55
+ "@lunora/scheduler": "1.0.0-alpha.120",
56
56
  "@lunora/values": "1.0.0-alpha.63",
57
57
  "@lunora/workflow": "1.0.0-alpha.75",
58
58
  "@visulima/fs": "6.0.29",
@@ -1 +0,0 @@
1
- import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h,CELLD_CAPABILITIES as b}from"@lunora/platform";import{r as g}from"./project-config-file-BV7RR-l6.mjs";const d="cloudflare",v=t=>{const{target:e}=g(t);return e!==void 0&&e.length>0?e:void 0},A=(t,e)=>e??v(t)??d,L=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=g(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${d}" 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: "${d}" }\`), or pass \`--target\`.`,target:d}]},u={celld:b,cloudflare:h,node:f},C=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),S={access:null,ai:"ai",aiSearch:"aiSearch",analytics:"analytics",analyticsSql:"analyticsSql",artifacts:"artifacts",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:"secrets"},w=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","containerSandboxTools","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","services","topics","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],m={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',containerSandboxTools:"container sandbox helpers — files, directory backups, bucket mounts (`defineContainer({ sandbox: true })`)",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`)",services:"service bindings to sibling Workers (`lunora.config` `services`)",topics:"pub/sub topics (`defineTopic` / `defineSubscription`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},y=(t,e,a)=>({level:"error",message:`${e.name} does not support ${m[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 ${m[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}),k=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:c,target:i}=t;for(const s of w){if(c[s]!==!0)continue;const o=r.features[s]?.level;o!=="unsupported"&&o!==void 0||(a[s]=!1,!n.has(s)&&e.push(o==="unsupported"?y(s,r,i):T(s,r,i)))}},_=(t,e,a,r={})=>{const n={...t},c={...r},i=[],s=new Set;for(const[o,l]of Object.entries(S)){if(l===null||!t[o])continue;const p=e.features[l]?.level;p==="unsupported"?(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name} does not support "${o}" (ctx.${o}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${o} usage, or deploy to a target whose capability matrix marks "${l}" as native or emulated.`,target:a})):p===void 0&&(n[o]=!1,s.add(l),i.push({feature:o,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${o}" (ctx.${o}). 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 k({diagnostics:i,gatedSignals:c,matrix:e,reported:s,signals:r,target:a}),{diagnostics:i,signals:c,usage:n}},E=(t,e,a={})=>{const r=u[e];return r===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,r,e,a)},I=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{S as CAPABILITY_TO_FEATURE,d as DEFAULT_TARGET,_ as gateAgainstMatrix,E as gatePlatformFeatures,C as platformMatrixIds,v as readProjectTarget,L as readTargetDiagnostics,A as resolveCodegenTarget,I as studioPlatformFor};
@@ -1,11 +0,0 @@
1
- import{existsSync as F,mkdirSync as sn,readFileSync as ki,writeFileSync as Ri,rmSync as mt,readdirSync as Fi}from"node:fs";import{dirname as nn,join as v,relative as Li}from"node:path";import{performance as it}from"node:perf_hooks";import{runAdvisor as Di}from"@lunora/advisor";import{LunoraError as q}from"@lunora/errors";import{serializeSchemaSnapshot as Mi}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as _i}from"./formatAdvisories-DwmUKYuc.mjs";import{Node as r,SyntaxKind as d,ts as Ki,VariableDeclarationKind as Bi}from"ts-morph";import{listLunoraSourceFiles as S,lunoraRelativePath as I,bindingKeyName as ee,collectCallRows as T,findObjectProperty as D,collectSecurityCallRows as zi,propertyInitializer as C,listSecurityScanFiles as Be,objectLiteralFromCallbackBody as rn,limitNameOf as on,optionsObjectLiteral as an,handlerOf as $i,collectNodeRows as X,chainRootOf as Tt,outermostValueWrapper as P,isWriteTarget as ze,isSameNode as y,unwrapExpression as h,isConstDeclaration as J,memberAccessOf as cn,returningFunctionOf as ht,walkChain as Vi,RUN_METHODS as ln,functionReferenceSegments as Ui,isTestPath as qi,isFunctionLike as Z,functionKeyOf as dn}from"./isTestPath-B81lOULB.mjs";import{b as G,d as V,f as O,g as Ot,c as E,a as un,w as kt,k as Wi,l as Hi,h as ji,m as Gi,j as vt,i as Yi}from"./attribution-hVBriwzy.mjs";import{a as fs,r as rt,i as W,b as Qi,m as fn,c as $e,e as Rt,E as gn,C as pn,d as Xi,f as Ji,g as Zi}from"./context-root-wBahDTzk.mjs";import{a as b,i as er,c as Y,d as mn,e as tr,f as sr}from"./classify-procedure-call-BAj0D1u2.mjs";import{a as A,r as hn,s as nr,b as ir}from"./project-config-file-BV7RR-l6.mjs";import{a as rr,b as Ve}from"./module-specifiers-WF8iAydP.mjs";import{r as Ue,s as or}from"./parse-validator-IDBKIT7M.mjs";import ar from"./discoverAuthApiCalls-xs0ONfI-.mjs";import cr from"./discoverHyperdriveCalls-BUrA_96X.mjs";import{diagnosticAt as xe}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{m as Ft,a as Fe,s as vn,d as lr}from"./index-BW4hJ4Wm.mjs";import{i as $,r as En}from"./database-calls-CHZbBUCZ.mjs";import{MUTATORS_FILENAME as dr,isDefineMutatorCallee as ur,mutatorServerImplOf as fr,discoverMutators as gr}from"./MUTATORS_FILENAME-Bw0YtaO8.mjs";import pr from"./discoverNondeterministicCalls-9ZDpRptb.mjs";import{discoverNotifyConfig as mr,discoverNotifyCalls as hr}from"./NOTIFY_FILENAME-CPjbiHQl.mjs";import vr from"./discoverR2sqlCalls-COKmDnih.mjs";import Er from"./discoverRlsProcedures-CuRLSnf9.mjs";import{s as Lt,n as xr}from"./dispatch-namespace-DwTjD7BU.mjs";import{secretKindOf as Sr,redact as Ar,isHeuristicSecretKind as yr,isSecretishName as br}from"./redact-Cy14LEnc.mjs";import{a as Ie,d as Nr,r as wr}from"./modules-CjOcuQnK.mjs";import{WORKFLOWS_FILENAME as Pr,discoverWorkflows as Ir}from"./WORKFLOWS_FILENAME-CQR8fE9B.mjs";import{r as Cr}from"./json-data-Chfs2Cz5.mjs";import{G as Tr}from"./shared-DnCokNcE.mjs";import{createCodegenProject as Or}from"./createCodegenProject-V51_yBw3.mjs";import{findTsconfig as ev,refreshCodegenProject as tv}from"./createCodegenProject-V51_yBw3.mjs";import{CAPABILITIES as kr,usedCapabilities as Rr}from"./CAPABILITY_PROBES-brcmKenl.mjs";import{isD1GlobalTable as xn,isHyperdriveGlobalTable as Sn}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Fr}from"./AGENTS_FILENAME-B6-kjzM3.mjs";import{discoverContainers as Lr}from"./CONTAINERS_FILENAME-Bk0u9QUu.mjs";import Dr from"./discoverCrons-DF7dOP9x.mjs";import{contextPropertiesRead as Mr,discoverFeatureUsage as _r}from"./capabilitiesUsedBy-QgSZyE0T.mjs";import An from"./readPackageDependencies-RHhGiz0k.mjs";import{discoverQueueDeclarations as Kr}from"./QUEUES_FILENAME-CsRy4VTF.mjs";import{discoverSandboxUsage as Br}from"./discoverSandboxUsage-w6Q3RvxZ.mjs";import{resolveServiceBindings as zr}from"./readServiceBindings-DvqIThzd.mjs";import $r from"./discoverStorageRulesMetadata-BPJplDfz.mjs";import{gatePlatformFeatures as Vr,resolveCodegenTarget as yn,readTargetDiagnostics as Ur,studioPlatformFor as qr}from"./DEFAULT_TARGET-3U7x981M.mjs";import{i as Wr}from"./schema-BgM8A3XV.mjs";import{b as bn,e as Hr}from"./shard-Ct-49zW9.mjs";import{e as jr,a as Gr}from"./server-DAvi_bv_.mjs";import{emitDataModel as Yr}from"./emitDataModel-DdtjdNg3.mjs";import{i as Qr,a as Xr,e as Jr,b as Zr,d as eo,c as to}from"./unwrap-handler-return-B-jQde6M.mjs";import so from"./discoverFunctions-DaEZl3uE.mjs";import no from"./discoverHttpRoutes-C_u9YiFb.mjs";import io from"./discoverInserts-OT_fiEGq.mjs";import{e as Nn}from"./exported-procedure-chains-DKK5HoK3.mjs";import ro from"./discoverMigrations-C9mLIhGZ.mjs";import oo from"./discoverQueries-C8V4cMIP.mjs";import ao from"./discoverRlsMetadata-Cb8JR1b4.mjs";import co from"./discoverSchema-Btu1KpBX.mjs";import{discoverShapes as lo}from"./SHAPES_FILENAME-DkBUN9dK.mjs";import{i as uo}from"./reserved-words-CW1QFbTd.mjs";import{emitApp as fo}from"./emitApp-DAZCUDbr.mjs";import{readJsonSync as go}from"@visulima/fs";import{buildSchemaSnapshot as po}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{buildOpenApiDocument as mo,emitOpenApiModule as ho}from"./buildOpenApiDocument-DFv-RYZU.mjs";import{buildOpenRpcDocument as vo,emitOpenRpcModule as Eo}from"./OPENRPC_VERSION-CCY7xqSL.mjs";import{v as xo,t as So,u as Ao,s as yo,w as bo}from"./shard-runtime-BX0xmo0P.mjs";import{emitCollections as No,emitSeed as wo,emitApi as Po,emitInternalApi as Io}from"./emitApi-Zx6VPN-7.mjs";import{emitCrons as Co,emitScheduler as To,emitShardRegistry as Oo,emitDurableObjects as ko,emitVectors as Ro,emitWranglerCronTriggers as Fo}from"./emitCrons-BQW2lviZ.mjs";import Lo from"./emitDrizzleSchema-CpOGYfyl.mjs";import Do from"./emitFunctions-BeKgL3dl.mjs";const wn=new Set(["delete","get","head","options","patch","post","put"]),Mo=new Set(["handler","stream"]),_o=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,gs=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Ko=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!wn.has(t.getName()))return;const s=t.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!r.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Bo=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||wn.has(n.getName()))break;s=n.getExpression()}return Ko(s)},zo=e=>{for(const t of e.getDescendantsOfKind(d.PropertyAccessExpression))if(gs.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=t.getExpression();if(r.isIdentifier(s)&&gs.has(s.getText()))return!0}return!1},$o=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=s.getExpression();if(!r.isPropertyAccessExpression(n)||!Mo.has(n.getName()))return;const i=Bo(s);if(!i||!_o.test(i.path))return;const o=s.getArguments()[0],a=o!==void 0&&(r.isArrowFunction(o)||r.isFunctionExpression(o))&&zo(o);return{exportName:V(e)??e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Vo=(e,t)=>{const s=[];for(const n of G(e)){const i=$o(n,t);i&&s.push(i)}return s},Uo=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Vo(i,I(t,n)))}return s},qo=e=>{const t=e.getText(),s=n=>{const i=n.getNameNode();return r.isIdentifier(i)&&i.getText()===t};for(const n of e.getAncestors())if(!(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)&&!r.isFunctionDeclaration(n)))for(const i of n.getParameters()){const o=i.getDescendantsOfKind(d.BindingElement).find(a=>s(a));if(o!==void 0)return o}},Wo=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isObjectBindingPattern(s))return;const n=s.getParent();if(r.isBindingElement(n)){t=n;continue}return r.isParameterDeclaration(n)?ee(t):void 0}},Ho=e=>{const t=e.getText();if(!e.getAncestors().some(o=>{const a=r.isFunctionLikeDeclaration(o)||r.isArrowFunction(o)?o.getParameters()[1]:void 0,c=a?.getNameNode();return a!==void 0&&(r.isIdentifier(c)?c.getText()===t:a.getDescendantsOfKind(d.BindingElement).some(l=>l.getName()===t))&&fs(a)}))return!1;const n=O(e),i=r.isParameterDeclaration(n)?n:n?.getFirstAncestorByKind(d.Parameter);return i!==void 0&&(r.isParameterDeclaration(n)||r.isBindingElement(n))&&fs(i)},ps=(e,t)=>{const s=e.getParent();if(r.isPropertyAccessExpression(s)&&s.getNameNode()===e||r.isPropertyAssignment(s)&&s.getNameNode()===e)return!1;if(e.getText()===t)return!0;const n=qo(e);return n!==void 0&&Wo(n)===t?!0:t==="args"&&Ho(e)},Pn=(e,t)=>r.isIdentifier(e)?ps(e,t):e.getDescendantsOfKind(d.Identifier).some(s=>ps(s,t)),jo=e=>{let t=e;for(;r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t)||r.isNonNullExpression(t);)t=t.getExpression();return r.isIdentifier(t)?t:void 0},ms=e=>{const t=r.isIdentifier(e)?O(e):void 0;return r.isVariableDeclaration(t)&&r.isIdentifier(t.getNameNode())&&!Ot(t)?t.getInitializer():void 0},Et=e=>Pn(e,"args"),H=e=>{if(!r.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a));if(s===void 0)return;const n=e.getStart();let i,o=-1;for(const a of s.getDescendantsOfKind(d.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<n&&l>o&&(i=c,o=l)}return i},j=e=>{if(Et(e))return!0;const t=H(e);return t!==void 0&&Et(t)},Go=e=>{if(r.isCallExpression(e)||r.isNewExpression(e))return!1;const t=H(e);return t===void 0||!(r.isCallExpression(t)||r.isNewExpression(t))},te=e=>{if(rt(e))return!0;const t=ms(e);if(t!==void 0&&rt(t))return!0;const s=t??e;return(r.isIdentifier(s)?[s]:s.getDescendantsOfKind(d.Identifier)).some(i=>{const o=ms(i);return o!==void 0&&rt(o)})},Ce=(e,t)=>Pn(e,t),Yo=(e,t)=>{if(Ce(e,t))return!0;const s=H(e);if(s!==void 0&&Ce(s,t))return!0;const n=jo(e);if(n!==void 0){const i=H(n);return i!==void 0&&Ce(i,t)}return!1},Qo=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:W(e.getExpression(),["ai"]),Xo=(e,t)=>{if(!Qo(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)||te(s)))return{scope:E(e),file:t,line:e.getStartLineNumber()}},Jo=(e,t)=>T(e,t,Xo),Zo=new Set(["generateText","streamText"]),ea=new Set(["messages","prompt","system"]),ta=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],sa=(e,t)=>ta.some(s=>s.methods.has(t)&&s.prefixes.some(n=>e===n||e.startsWith(`${n}.`))),na=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=[Qi(t.getExpression()),t.getExpression().getText()].find(i=>i!==void 0&&sa(i,s));return n===void 0?void 0:`${n}.${s}`},ia=e=>{for(const t of e.getDescendantsOfKind(d.CallExpression)){const s=na(t);if(s!==void 0)return s}},ra=e=>{const t=new Set,s=e.getFirstAncestor(o=>r.isArrowFunction(o)||r.isFunctionExpression(o)||r.isFunctionDeclaration(o)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!r.isObjectBindingPattern(i))return t;for(const o of i.getElements()){const a=ee(o),c=o.getNameNode();if(a==="args"&&r.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},oa=e=>{if(Et(e))return!0;const t=ra(e);return t.size===0?!1:e.getDescendantsOfKind(d.Identifier).some(s=>t.has(s.getText()))},aa=e=>{for(const t of e.getProperties()){if(!r.isPropertyAssignment(t)||!ea.has(A(t)))continue;const s=t.getInitializer();if(s!==void 0&&oa(s))return!0}return!1},ca=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());if(i===void 0||!Zo.has(i))continue;const[o]=n.getArguments();if(o===void 0||!r.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(d.CallExpression))if(b(c.getExpression())==="tool"&&(a=ia(c),a!==void 0))break;a!==void 0&&s.push({scope:E(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:aa(o)})}return s},la=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ca(i,I(t,n)))}return s},da=e=>W(e,["fetch"]),ua=(e,t)=>{if(!da(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!j(s)))return{scope:E(e),file:t,line:e.getStartLineNumber()}},fa=(e,t)=>T(e,t,ua),Dt=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!r.isSpreadAssignment(s))return!1;const n=Ue(s.getExpression());return n===void 0||Dt(n,t)})}finally{t.delete(e)}},ga=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=D(t,"args");if(!s)return{objects:[],opaque:!1};if(!r.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:Ue(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:Dt(i)}},pa=e=>{const t=[];let s=!1,n=e;for(;r.isCallExpression(n);){const i=n.getExpression();if(!r.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const o=n.getArguments()[0],a=o!==void 0&&r.isExpression(o)?Ue(o):void 0;a===void 0?s=!0:(t.push(a),s||=Dt(a))}n=i.getExpression()}return{objects:t,opaque:s}},Mt=(e,t)=>t?pa(t):ga(e),In=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(r.isSpreadAssignment(s)){const n=Ue(s.getExpression());return n===void 0?[]:In(n,t)}return r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)?[A(s)]:[]})}finally{t.delete(e)}},ma=e=>e.flatMap(t=>In(t,new Set)),ha=new Set(["check","length","max"]),xt=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!r.isCallExpression(n)||n.getExpression()!==s)return!1;if(ha.has(s.getName()))return!0;t=n}},St=e=>rr(e)||e==="@lunora/values",va=e=>{const t=new Set(["v"]);for(const s of er(e,"v",St))t.add(s);for(const s of e.getImportDeclarations()){const n=s.getNamespaceImport();n&&St(s.getModuleSpecifierValue())&&t.add(`${n.getText()}.v`)}return t},Ea=(e,t)=>{const s=new Map;for(const n of e.getVariableStatements())for(const i of n.getDeclarations()){const o=i.getNameNode(),a=i.getInitializer();if(!(!r.isObjectBindingPattern(o)||!a||!t.has(a.getText())))for(const c of o.getElements())c.getDotDotDotToken()||s.set(c.getName(),c.getPropertyNameNode()?.getText()??c.getName())}return s},xa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>!t.getSourceFile().isDeclarationFile()&&!r.isImportSpecifier(t)&&!r.isNamespaceImport(t)&&!r.isImportClause(t)),Sa=e=>(e.getSymbol()?.getDeclarations()??[]).some(t=>r.isNamespaceImport(t)&&St(t.getFirstAncestorByKindOrThrow(d.ImportDeclaration).getModuleSpecifierValue())),_t=(e,t)=>{if(!r.isCallExpression(e))return;const s=e.getExpression();if(r.isPropertyAccessExpression(s)){const n=s.getExpression();if(!t.namespaces.has(n.getText()))return;if(r.isIdentifier(n))return xa(n)?void 0:s.getName();const i=r.isPropertyAccessExpression(n)?n.getExpression():void 0;return r.isIdentifier(i)&&Sa(i)?s.getName():void 0}if(r.isIdentifier(s))return t.destructured.get(s.getText())},Aa=(e,t)=>{if(!r.isIdentifier(e))return;const s=e.getText(),n=t.getVariableDeclaration(s)?.getInitializer();return n&&(r.isArrowFunction(n)||r.isFunctionExpression(n))?n:t.getFunction(s)},ya=e=>{let t=e.getParent();for(;t&&!r.isFunctionLikeDeclaration(t);)t=t.getParent();return t},ba=e=>r.isReturnStatement(e)?e.getExpression():void 0,Na=e=>r.isArrowFunction(e)&&!r.isBlock(e.getBody())?[e.getBody()]:e.getDescendantsOfKind(d.ReturnStatement).filter(t=>ya(t)?.compilerNode===e.compilerNode).flatMap(t=>{const s=ba(t);return s?[s]:[]}),Cn=(e,t)=>{if(_t(e,t)!==void 0)return e;if(r.isCallExpression(e)||r.isPropertyAccessExpression(e))return Cn(e.getExpression(),t)},wa=(e,t)=>{const s=Aa(e.getExpression(),e.getSourceFile());if(!s)return[];const n=xt(e),i=new Set(Na(s).map(o=>Cn(o,t)).filter(o=>o!==void 0));return[s,...s.getDescendants()].flatMap(o=>{const a=_t(o,t);return a===void 0?[]:[{bounded:xt(o)||n&&i.has(o),factory:a}]})},Pa=(e,t)=>[e,...e.getDescendants()].flatMap(s=>{const n=_t(s,t),i=n===void 0?[]:[{bounded:xt(s),factory:n}];return r.isCallExpression(s)?[...i,...wa(s,t)]:i}),Ia=(e,t)=>{const s=[],n=[];for(const i of e)for(const o of i.getProperties()){if(!r.isPropertyAssignment(o))continue;const a=o.getInitializer();if(!a)continue;const c=Pa(a,t),l=A(o);c.some(u=>u.factory==="any")?s.push(l):c.some(u=>u.factory==="string"&&!u.bounded)&&n.push(l)}return{anyArgs:s,unboundedStringArgs:n}},Ca=(e,t,s)=>{const n=e.getInitializer();if(!n||!r.isCallExpression(n))return;const i=Y(n);if(i?.visibility!=="public")return;const{objects:o}=Mt(n,i.receiver),{anyArgs:a,unboundedStringArgs:c}=Ia(o,s);if(!(a.length===0&&c.length===0))return{anyArgs:a,exportName:V(e)??e.getName(),file:t,line:n.getStartLineNumber(),unboundedStringArgs:c}},Ta=(e,t)=>{const s=[],n=va(e),i={destructured:Ea(e,n),namespaces:n};for(const o of G(e)){const a=Ca(o,t,i);a&&s.push(a)}return s},Oa=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ta(i,I(t,n)))}return s},ot=e=>e?.getKind()===d.TrueKeyword,ka=e=>e?.getKind()===d.FalseKeyword,Ra=e=>e!==void 0&&r.isNumericLiteral(e)&&e.getLiteralValue()===0,Fa=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),La=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isCallExpression(t)&&b(t.getExpression())==="scim"),Da=e=>e!==void 0&&r.isCallExpression(e)&&Fa.has(b(e.getExpression())??""),Ma=e=>!e||!r.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>r.isStringLiteral(t)&&t.getLiteralText()==="*"),_a=e=>{const t=C(e,"advanced"),s=C(e,"emailAndPassword"),n=C(e,"session");return{analyzable:!0,disableCsrfCheck:ot(C(t,"disableCSRFCheck")),emailPasswordEnabled:ot(C(s,"enabled")),requireEmailVerification:ot(C(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:La(C(e,"plugins"))&&Da(C(e,"database")),secureCookiesDisabled:ka(C(t,"useSecureCookies")),sessionFreshAgeZero:Ra(C(n,"freshAge")),trustedOriginsWildcard:Ma(C(e,"trustedOrigins"))}},Ka=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Ba=(e,t)=>{if(b(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)&&s.getProperties().some(o=>r.isSpreadAssignment(o)),i=s!==void 0&&r.isObjectLiteralExpression(s)&&!n?_a(s):Ka();return{scope:E(e),file:t,line:e.getStartLineNumber(),...i}},za=(e,t)=>zi(e,t,Ba),$a=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return fn(e.getExpression(),t.matchReceiver)?s:void 0},Va=(e,t,s)=>{const n=$a(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!j(i)||te(i))&&!(s.requireUnmodifiedReach===!0&&!Go(i)))return{scope:E(e),file:t,line:e.getStartLineNumber(),method:n}},qe=(e,t,s)=>T(e,t,(n,i)=>Va(n,i,s)),Ua=new Set(["content","pdf","scrape","screenshot"]),qa=(e,t)=>qe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Ua}),Wa=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Ha=new Set(["RateLimiter"]),ja=new Set(["extend"]),hs="lunora",Ga=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Tn=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),i.getInitializer()?.getKind()===d.TrueKeyword&&s.push(o);continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,presentKeys:t,trueKeys:s}},At=e=>e&&r.isObjectLiteralExpression(e)?Tn(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Ya=e=>{const t=e&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,s=t&&rn(t.getBody());return s?Tn(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Qa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=b(n.getExpression());i!==void 0&&(Wa.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...At(n.getArguments()[0])}):ja.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Ya(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(d.NewExpression)){const i=b(n.getExpression());i===void 0||!Ha.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...At(n.getArguments()[0])})}return s},Xa=(e,t)=>{for(const s of Ga){const n=v(t,s);if(!F(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=[];for(const a of i.getDescendantsOfKind(d.CallExpression))b(a.getExpression())===hs&&o.push({callee:hs,file:s,line:a.getStartLineNumber(),...At(a.getArguments()[0])});return o}return[]},Ja=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Be(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Qa(o,n))}return s.push(...Xa(e,nn(t))),s},vs="ctx.containers.",Za=e=>{if(!e.startsWith(vs))return!1;const t=e.slice(vs.length);return t.length>0&&!t.includes(".")},ec=(e,t)=>qe(e,t,{argIndex:0,matchReceiver:Za,methods:new Set(["get"])}),tc=new Set(["allow","deny","setAllowed"]),sc=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return!1;const s=D(t,"enableInternet");return s!==void 0&&r.isPropertyAssignment(s)&&r.isTrueLiteral(s.getInitializerOrThrow())},nc=(e,t)=>{const s=e.getExpression();if(!(!r.isPropertyAccessExpression(s)||s.getName()!=="start"||!sc(e)))return{detail:"enableInternet: true",scope:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},ic=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||!tc.has(s.getName()))return;const n=s.getExpression();if(!(!r.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),scope:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},rc=(e,t)=>nc(e,t)??ic(e,t),oc=(e,t)=>T(e,t,rc),ac=new Set(["defineExportSink","r2Sink","webhookExportSink"]),cc=e=>{const t=e.getExpression();if(!r.isIdentifier(t))return;const s=t.getText();return ac.has(s)?s:void 0},lc=e=>{const t=[],s=[];for(const n of e.getProperties()){if(r.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(r.isPropertyAssignment(n)){const i=A(n);t.push(i);const o=n.getInitializer();o&&r.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(i);continue}(r.isShorthandPropertyAssignment(n)||r.isMethodDeclaration(n)||r.isGetAccessorDeclaration(n))&&t.push(A(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},dc=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Be(t)){const o=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of o.getDescendantsOfKind(d.CallExpression)){const c=cc(a);if(c===void 0)continue;const l=a.getArguments()[0],u=l&&r.isObjectLiteralExpression(l)?lc(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:u.analyzable,emptyKeys:u.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:u.presentKeys})}}return s},uc=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),fc=new Set(["dbRateLimit","rateLimit"]),gc=e=>{const t=an(e);if(!t)return!1;const s=D(t,"failOpen");return s!==void 0&&r.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===d.TrueKeyword},pc=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=uc.get(s);if(n!==void 0)return{callee:s,scope:E(e),failOpen:gc(e.getArguments()[n]),file:t,limitName:fc.has(s)?on(e):"",line:e.getStartLineNumber()}},mc=(e,t)=>T(e,t,pc),hc=e=>{const t=e.getInitializer();if(!t||!r.isCallExpression(t))return;const s=Y(t);if(s?.kind!=="query")return;const n=$i(t,s.receiver);return n?{exportName:V(e)??e.getName(),handler:n}:void 0},Es=e=>{const t=e.getParent();return t&&r.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},vc=e=>{const t=Es(e);if(!t)return"ctx.flags";if(t.getName()==="details"){const s=Es(t);return s?`ctx.flags.details.${s.getName()}`:"ctx.flags.details"}return`ctx.flags.${t.getName()}`},Ec=(e,t)=>{const s=[];for(const n of $e(e.handler,"flags"))s.push({callee:vc(n),exportName:e.exportName,file:t,line:n.getStartLineNumber()});return s},xc=(e,t)=>{const s=[];for(const n of G(e)){const i=hc(n);i&&s.push(...Ec(i,t))}return s},Sc=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...xc(i,I(t,n)))}return s},Ac=e=>!r.isPropertyAccessExpression(e)||e.getName()!=="boolean"?!1:W(e.getExpression(),["flags"]),yc=e=>{if(e?.getKind()===d.TrueKeyword)return!0;if(e?.getKind()===d.FalseKeyword)return!1},bc=(e,t)=>{if(!Ac(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(r.isStringLiteral(s)||r.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),o=yc(n);if(!(i.length===0||o===void 0))return{defaultValue:o,scope:E(e),file:t,key:i,line:e.getStartLineNumber()}},Nc=(e,t)=>T(e,t,bc),wc=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Pc=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},Ic=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of i.getDescendantsOfKind(d.CallExpression))wc(a)&&s.push({file:o,indexName:Pc(a),line:a.getStartLineNumber()})}return s},he=e=>e!==void 0&&(r.isArrowFunction(e)||r.isFunctionExpression(e))?e:void 0,On=e=>{const t=e.getArguments()[0],s=he(t);if(s!==void 0)return s;if(t===void 0||!r.isObjectLiteralExpression(t))return;const n=D(t,"handler");return n!==void 0&&r.isPropertyAssignment(n)?he(n.getInitializer()):void 0},Cc=new Set(["delete","get","head","options","patch","post","put"]),Tc=new Set(["handler","stream"]),Oc=new Set(["runAction","runMutation"]),kc=new Set(["delete","insert","insertManyUnsafe","patch","patchIf","replace"]),ve=(e,t)=>e!==void 0&&r.isIdentifier(e)&&e.getText()===t,kn=(e,t)=>{if(!(e===void 0||!r.isObjectBindingPattern(e))){for(const s of e.getElements())if(ee(s)===t){const i=s.getNameNode();return r.isIdentifier(i)?i.getText():void 0}}},xs=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?r.isIdentifier(s)?s.getText():void 0:kn(s,"ctx")},Ss=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&r.isIdentifier(s)?s.getText():void 0:kn(s,"request")},As=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);r.isCallExpression(s)&&n.unshift(s);for(const i of n){const o=i.getExpression();if(!r.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Oc.has(a)&&ve(c,t))return a;if(kc.has(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="db"&&ve(c.getExpression(),t))return`db.${a}`}},ys=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(d.PropertyAccessExpression))if(n.getName()==="auth"&&ve(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(d.VariableDeclaration)){const i=n.getNameNode();if(!(!r.isObjectBindingPattern(i)||!ve(n.getInitializer(),t))){for(const o of i.getElements())if(ee(o)==="auth")return!0}}return!1},Rc=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Fc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()==="headers"&&ve(n.getExpression(),t)},Lc=e=>[...r.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(d.StringLiteral).map(t=>t.getLiteralText())],Rn=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Lc(s)},Dc=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!r.isArrowFunction(n)&&!r.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!r.isCallExpression(i))return[];const o=i.getExpression();if(!r.isPropertyAccessExpression(o))return[];const a=o.getExpression();return r.isIdentifier(a)?Rn(t,a.getText()):[]}return[]},Mc=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(r.isStringLiteral(t))return[t.getLiteralText()];if(!r.isIdentifier(t))return[];const s=e.getSourceFile(),n=Rn(s,t.getText());return n.length>0?n:Dc(t,s)},bs=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(d.CallExpression);return r.isCallExpression(s)&&n.unshift(s),n.some(i=>Fc(i,t)&&Mc(i).some(o=>Rc.test(o)))},_c=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!Tc.has(t.getName()))return;let s=t.getExpression();for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))return;const i=n.getName();if(Cc.has(i)){const o=n.getExpression();return r.isIdentifier(o)&&o.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Kc=(e,t)=>{const s=e.getExpression();if(r.isIdentifier(s)&&s.getText()==="httpAction"){const c=he(e.getArguments()[0]),l=c&&xs(c,!0);if(!c||l===void 0||bs(c,Ss(c,!0)))return;const u=As(c,l);return u===void 0?void 0:{scope:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ys(c,l),sideEffect:u}}const n=_c(e);if(n===void 0)return;const i=he(e.getArguments()[0]),o=i&&xs(i,!1);if(!i||o===void 0||bs(i,Ss(i,!1)))return;const a=As(i,o);return a===void 0?void 0:{scope:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:ys(i,o),sideEffect:a}},Bc=(e,t)=>T(e,t,Kc),zc=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),$c=new Set(["append","set"]),Fn=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Ns=(e,t)=>(r.isCallExpression(e)?[e,...e.getDescendantsOfKind(d.CallExpression)]:e.getDescendantsOfKind(d.CallExpression)).some(n=>zc.has(b(n.getExpression())??"")&&Ce(n,t)),Vc=(e,t)=>{if(Ns(e,t))return!0;const s=H(e);return s!==void 0&&Ns(s,t)},yt=(e,t)=>Yo(e,t)&&!Vc(e,t),Uc=e=>{if(r.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=H(e);return t!==void 0&&r.isNewExpression(t)&&b(t.getExpression())==="Headers"},Le=e=>{if(e===void 0)return;if(r.isObjectLiteralExpression(e))return e;const t=H(e);return t!==void 0&&r.isObjectLiteralExpression(t)?t:void 0},Kt=(e,t,s)=>{for(const n of e.getProperties())if(r.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&yt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:Fn(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(r.isShorthandPropertyAssignment(n)){const i=n.getNameNode();yt(i,s.requestName)&&s.rows.push({scope:s.scope,file:s.relativePath,headerName:A(n),line:i.getStartLineNumber(),via:t})}else if(r.isSpreadAssignment(n)){const i=Le(n.getExpression());i!==void 0&&Kt(i,t,s)}},Ln=(e,t)=>{const s=Le(e);if(s===void 0)return;const n=D(s,"headers");if(n===void 0||!r.isPropertyAssignment(n))return;const i=Le(n.getInitializer());i!==void 0&&Kt(i,"response-init",t)},qc=(e,t)=>{const s=b(e.getExpression());if(s==="Response")Ln(e.getArguments()[1],t);else if(s==="Headers"){const n=Le(e.getArguments()[0]);n!==void 0&&Kt(n,"headers-ctor",t)}},Wc=(e,t)=>{const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&r.isIdentifier(i)&&i.getText()==="Response"){Ln(e.getArguments()[1],t);return}if($c.has(n)&&Uc(i)){const o=e.getArguments()[1];o!==void 0&&yt(o,t.requestName)&&t.rows.push({scope:t.scope,file:t.relativePath,headerName:Fn(e.getArguments()[0]),line:o.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Hc=(e,t)=>{for(const s of e.getDescendantsOfKind(d.NewExpression))qc(s,t);for(const s of e.getDescendantsOfKind(d.CallExpression))Wc(s,t)},jc=(e,t)=>{const s=e.getExpression();if(!r.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=he(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const o=i.getNameNode();if(!r.isIdentifier(o))return[];const a=[];return Hc(n,{scope:E(e),relativePath:t,requestName:o.getText(),rows:a}),a},Gc=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression))s.push(...jc(n,t));return s},Yc=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gc(i,I(t,n)))}return s},Dn="identity.ts",Qc=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ve(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Xc=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ve(n.getModuleSpecifierValue())}return!1},Jc=e=>{if(r.isIdentifier(e))return Qc(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&r.isIdentifier(t)&&Xc(t)}return!1},Zc=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Jc(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw xe(o,"defineIdentity exports must be plain named exports (no destructuring)")}const a=un(s,"member");a!==void 0&&t.push({exportName:a})}return t},el=(e,t)=>{const s=v(t,Dn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Zc(n);if(i.length!==0){if(i.length>1)throw xe(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},tl=new Set(["auth","context.auth"]),sl="userId",nl=e=>{const t=new Set;for(const s of e.getProperties()){if(r.isSpreadAssignment(s))return;(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s))&&t.add(A(s))}return t},il=(e,t)=>{const s=v(t,Dn);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){if(b(i.getExpression())!=="defineIdentity")continue;const[o]=i.getArguments();return o&&r.isObjectLiteralExpression(o)?nl(o):void 0}},ws=e=>{if(e===void 0||!r.isPropertyAccessExpression(e)||e.getName()!=="identity")return;const t=e.getExpression();return tl.has(t.getText())||W(t,["auth"])?e:void 0},rl=e=>{if(r.isPropertyAccessExpression(e)&&ws(e.getExpression())!==void 0)return e.getName();if(r.isElementAccessExpression(e)&&ws(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&r.isStringLiteral(t)?t.getLiteralValue():void 0}},Ps=(e,t,s)=>{const n=rl(e);return n===void 0?void 0:{declared:n===sl||s.has(n),file:t,key:n,line:e.getStartLineNumber(),scope:E(e)}},ol=(e,t)=>{const s=il(e,t);return s===void 0?[]:[...X(e,t,d.PropertyAccessExpression,(n,i)=>Ps(n,i,s)),...X(e,t,d.ElementAccessExpression,(n,i)=>Ps(n,i,s))]},al=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=C(s,"key");if(!(!n||!j(n)||te(n)))return{scope:E(e),file:t,line:e.getStartLineNumber()}},cl=(e,t)=>T(e,t,al),ll=new Set(["delete","get","getRaw","getWithMetadata","put"]),dl=(e,t,s=[])=>{const n=qe(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.kv"||i.startsWith("ctx.kv."),methods:ll});return kt(n,s)},ul=new Set(["queue","send"]),Is=new Set(["bcc","cc","to"]),fl=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(!ul.has(t))return;const s=e.getExpression();return W(s,["mail"])||W(s,["email"])?t:void 0},gl=e=>r.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(r.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Is.has(A(t))&&j(n)&&!te(n)}if(!r.isPropertyAssignment(t)||!Is.has(A(t)))return!1;const s=t.getInitializer();return s!==void 0&&j(s)&&!te(s)}):!1,pl=(e,t)=>{const s=fl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!gl(n)))return{scope:E(e),file:t,line:e.getStartLineNumber(),method:s}},ml=(e,t)=>T(e,t,pl),hl=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){const a=Fe(o);if(a===void 0||!r.isPropertyAssignment(o))continue;const c=o.getInitializer();if(!(!c||!r.isObjectLiteralExpression(c)))for(const l of c.getProperties()){const u=Fe(l);if(u===void 0)continue;const f=vn(l);f!=="custom"&&i.push({column:u,exportName:t,file:s,line:l.getStartLineNumber(),strategy:f,table:a})}}return i},vl=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Y(s):void 0;return n?.receiver?Ft(n.receiver).flatMap(i=>hl(i,V(e)??e.getName(),t)):[]},El=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of G(i))s.push(...vl(a,o))}return s},xl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return $(s)},Sl=e=>{const t=e.getArguments()[0];if(t===void 0||!r.isObjectLiteralExpression(t))return;const s=D(t,"server");if(s!==void 0)return r.isPropertyAssignment(s)?s.getInitializer():s},Al=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==d.CallExpression)return;const s=t;return ur(s.getExpression())?s:void 0},yl=e=>{const t=Al(e),s=t===void 0?void 0:Sl(t);if(s===void 0)return[];const n=e.getNameNode(),i=r.isIdentifier(n)?V(e)??n.getText():"";return s.getDescendantsOfKind(d.CallExpression).filter(o=>xl(o)).map(o=>({exportName:i,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},bl=e=>e.getVariableDeclarations().flatMap(t=>yl(t)),Nl=(e,t)=>{const s=v(t,dr);if(!F(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return bl(n)},wl=new Set(["delete","get","patch"]),Pl=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Il=new Set(["auth","identity","session","user"]),Cl=new Set([d.EqualsEqualsEqualsToken,d.EqualsEqualsToken,d.ExclamationEqualsEqualsToken,d.ExclamationEqualsToken]),Tl=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!$(t.getExpression()))return;const s=e.getArguments()[0];return s&&r.isStringLiteral(s)?s.getLiteralText():""},Ol=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(r.isAsExpression(s)||r.isParenthesizedExpression(s)||r.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!r.isVariableDeclaration(s))return;const n=s.getNameNode();return r.isIdentifier(n)?n.getText():void 0},kl=(e,t)=>e.getDescendantsOfKind(d.Identifier).some(s=>s.getText()===t),Rl=e=>r.isThrowStatement(e)||r.isReturnStatement(e)||e.getDescendantsOfKind(d.ThrowStatement).length>0||e.getDescendantsOfKind(d.ReturnStatement).length>0,Fl=(e,t)=>e.getDescendantsOfKind(d.IfStatement).some(s=>kl(s.getExpression(),t)&&Rl(s.getThenStatement())),Ll=(e,t)=>{for(const s of e.getDescendantsOfKind(d.CallExpression)){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))continue;const i=n.getName();if(!wl.has(i))continue;const o=n.getExpression();if(!($(o)||r.isPropertyAccessExpression(o)&&$(o.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&r.isIdentifier(c)&&c.getText()===t)return i}},Dl=e=>e.getDescendantsOfKind(d.CallExpression).some(t=>t.getArguments().some(s=>Rt(Tt(s))!==void 0)),Ml=e=>e.getDescendantsOfKind(d.BinaryExpression).some(t=>Cl.has(t.getOperatorToken().getKind())?r.isPropertyAccessExpression(t.getLeft())||r.isPropertyAccessExpression(t.getRight()):!1),_l=e=>{for(const t of e.getDescendantsOfKind(d.Identifier))if(Pl.has(t.getText()))return!0;return[...Il].some(t=>$e(e,t).length>0)?!0:Dl(e)||Ml(e)},Kl=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Y(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=On(s);if(i===void 0)return[];const o=n.receiver!==void 0&&mn(n.receiver,"use","rls"),a=_l(i),c=new Set,l=[];for(const u of i.getDescendantsOfKind(d.CallExpression)){const f=Tl(u);if(f===void 0)continue;const g=Ol(u);if(g===void 0||c.has(g)||!Fl(i,g))continue;const p=Ll(i,g);p!==void 0&&(c.add(g),l.push({exportName:V(e)??e.getName(),file:t,line:u.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:f,usesRls:o,visibility:n.visibility}))}return l},Bl=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of G(i))s.push(...Kl(a,o))}return s},Mn=(e,t)=>{const s=r.isIdentifier(e)&&t!==void 0?O(e):void 0;return s===void 0||t===void 0?!1:s.compilerNode===t.compilerNode?r.isIdentifier(t.getNameNode()):r.isBindingElement(s)&&s.getFirstAncestorByKind(d.Parameter)?.compilerNode===t.compilerNode},zl=e=>{const t=P(e),s=t.getParent();return(r.isPropertyAccessExpression(s)||r.isElementAccessExpression(s))&&s.getExpression()===t&&!ze(s)},$l=e=>{const t=P(e).getParent();return r.isVariableDeclaration(t)&&r.isObjectBindingPattern(t.getNameNode())},Vl=e=>{const s=P(e).getParent();if(r.isSpreadAssignment(s)||r.isSpreadElement(s)){const n=s.getParent();return(r.isObjectLiteralExpression(n)||r.isArrayLiteralExpression(n))&&!ze(n)}return r.isTemplateSpan(s)&&!r.isTaggedTemplateExpression(s.getParent().getParent())},De=e=>{const t=O(e);return t===void 0||Hi(t.getSourceFile())},bt=(e,t)=>{const s=P(e),n=s.getParent();if(!r.isCallExpression(n))return!1;const i=n.getArguments().indexOf(s),o=h(n.getExpression());if(i===-1||o===void 0)return!1;if(r.isIdentifier(o))return o.getText()==="structuredClone"&&De(o);if(Mn(Tt(o),t))return!(r.isPropertyAccessExpression(o)&&gn.has(o.getName()))||r.isExpressionStatement(P(r.isAwaitExpression(n.getParent())?n.getParentOrThrow():n).getParent());if(!r.isPropertyAccessExpression(o))return!1;const a=o.getExpression();if(!r.isIdentifier(a)||!De(a))return!1;const c=a.getText(),l=o.getName();switch(c){case"console":return!0;case"JSON":return l==="stringify";case"Object":return["entries","freeze","isFrozen","keys","values"].includes(l)||l==="assign"&&i>0;default:return!1}},Te={kind:"opaque"},Ul={kind:"unreached"},ql=e=>{const t=e.getSymbol()?.getDeclarations()??[],s=t.filter(o=>r.isFunctionDeclaration(o)&&o.hasBody()),[n]=s;return t.every(o=>r.isFunctionDeclaration(o)&&o.getSourceFile()===e.getSourceFile())&&s.length===1&&r.isFunctionDeclaration(n)?n:void 0},Nt=e=>{const t=h(e);if(r.isArrowFunction(t)||r.isFunctionExpression(t))return t;const s=r.isIdentifier(t)?O(t):void 0;if(s?.getSourceFile()!==e.getSourceFile())return;if(r.isFunctionDeclaration(s)){const i=ql(s);return i===void 0||Ot(i)?void 0:i}const n=J(s)?h(s.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},_n=(e,t,s)=>{const n=t.getArguments(),i=n.indexOf(s),o=i===-1||n.slice(0,i+1).some(l=>r.isSpreadElement(l))||e.getDescendantsOfKind(d.Identifier).some(l=>l.getText()==="arguments"),a=e.getParameters(),c=a[i];return o?Te:c===void 0?a.some(l=>l.isRestParameter())?Te:Ul:c.isRestParameter()?Te:{kind:"parameter",parameter:c}},Wl=e=>{const t=P(e),s=t.getParent();if(!r.isCallExpression(s)||s.getExpression()===t)return;const n=Nt(s.getExpression());return n===void 0?Te:_n(n,s,t)},Hl=new Set(["__defineGetter__","__defineSetter__","__proto__"]),jl=e=>r.isForInStatement(e)?e.getExpression():r.isConditionalExpression(e)?e.getCondition():r.isElementAccessExpression(e)?e.getArgumentExpression():void 0,Kn=e=>{const t=P(e),s=t.getParent();if(r.isIfStatement(s)||r.isWhileStatement(s)||r.isDoStatement(s)||r.isSwitchStatement(s)||r.isCaseClause(s)||r.isTypeOfExpression(s)||r.isVoidExpression(s)||r.isComputedPropertyName(s))return!0;if(r.isTemplateSpan(s))return!r.isTaggedTemplateExpression(s.getParent().getParent());const n=jl(s);if(n!==void 0)return y(n,t);if(r.isPrefixUnaryExpression(s))return s.getOperatorToken()!==d.PlusPlusToken&&s.getOperatorToken()!==d.MinusMinusToken;if(!r.isBinaryExpression(s))return!1;const i=s.getOperatorToken().getKind(),o=i>=d.FirstAssignment&&i<=d.LastAssignment,a=i===d.QuestionQuestionToken||i===d.BarBarToken||i===d.AmpersandAmpersandToken;return!o&&!a},Gl=4,Bn=(e,t,s=0)=>{if(Wi(e))return!0;if(zl(e)){const i=P(e).getParent(),o=r.isElementAccessExpression(i)?i.getArgumentExpression():void 0,a=r.isStringLiteral(o)?o.getLiteralValue():void 0,c=r.isPropertyAccessExpression(i)?i.getName():a;return c===void 0||!Hl.has(c)}if($l(e)||Vl(e)||Kn(e)||bt(e,t))return!0;const n=Wl(e);return n?.kind==="unreached"||n?.kind==="parameter"&&Yl(n.parameter,s+1)},Cs=new WeakMap,Yl=(e,t=0)=>{const s=e.getNameNode();if(!r.isIdentifier(s))return!0;const n=Cs.get(e.compilerNode);if(n!==void 0)return n;if(t>Gl)return!1;const o=(s.getSymbol()?.getDeclarations().length??0)===1&&e.getParentOrThrow().getDescendantsOfKind(d.Identifier).every(a=>a===s||a.getText()!==s.getText()||O(a)?.compilerNode!==e.compilerNode||Bn(a,void 0,t));return(o||t===0)&&Cs.set(e.compilerNode,o),o},Ts=new WeakMap,Ql=(e,t)=>{const s=r.isFunctionExpression(e)?e.getNameNode():void 0;if(!r.isArrowFunction(e)&&e.getFirstDescendantByKind(d.ThisKeyword)!==void 0)return!0;const n=new Set([t.getName(),...s===void 0?[]:[s.getText()]]);return e.getDescendantsOfKind(d.Identifier).some(i=>{if(i===s||!n.has(i.getText()))return!1;const o=O(i)?.compilerNode;return o!==void 0&&(o===t.compilerNode||s!==void 0&&o===e.compilerNode)})},Xl=(e,t,s)=>{const{context:n,impl:i}=e,o=Ts.get(i.compilerNode);if(o!==void 0)return o;const a=t.getNameNode(),c=r.isIdentifier(a)?[a]:a.getDescendantsOfKind(d.BindingElement).flatMap(g=>{const p=g.getNameNode();return r.isIdentifier(p)?[p]:[]}),l=new Map(c.map(g=>[g.getText(),g.getParentOrThrow().compilerNode])),u=g=>r.isIdentifier(a)?Bn(g,n):!ze(g),f=!Ql(i,s)&&c.every(g=>(g.getSymbol()?.getDeclarations().length??0)===1)&&i.getDescendantsOfKind(d.Identifier).every(g=>{const p=g.getText();if(p==="arguments")return!1;const x=l.get(p);return x===void 0||c.includes(g)||O(g)?.compilerNode!==x?!0:u(g)});return Ts.set(i.compilerNode,f),f},Os=new WeakMap,Jl=e=>{let t=Os.get(e.compilerNode);return t===void 0&&(t=new Map(e.getVariableDeclarations().flatMap(s=>{const n=fr(s);return n===void 0?[]:[[n.compilerNode,s]]})),Os.set(e.compilerNode,t)),t},Zl=e=>{const t=Jl(e.getSourceFile()),s=e.getAncestors().find(l=>t.has(l.compilerNode)),n=s===void 0?void 0:t.get(s.compilerNode);if(s===void 0||n===void 0)return;const[i,o]=s.getParameters(),a=o===void 0||o.isRestParameter()?void 0:o,c={context:i,impl:s,mutatorName:V(n)??n.getName()};return a!==void 0&&Xl(c,a,n)?{...c,parameter:a,pristine:!0}:{...c,parameter:a,pristine:!1}},at="args",ge=e=>{const t=cn(e);if(t!==void 0){const c=h(t.object);return r.isIdentifier(c)&&c.getText()===at?t.member:void 0}if(!r.isIdentifier(e))return;const s=O(e);if(!r.isBindingElement(s)||s.getDotDotDotToken()!==void 0)return;const n=s.getParent();if(!r.isObjectBindingPattern(n))return;const i=n.getParent(),o=J(i)?h(i.getInitializer()):void 0;return r.isBindingElement(i)&&ee(i)===at||r.isIdentifier(o)&&o.getText()===at?ee(s):void 0},ed=new Set(["auth","identity","user"]),wt=e=>{const t=i=>{const o=Rt(i);return o!==void 0&&o.length>0&&ed.has(o[0]??"")},s=h(e)??e;if(t(s))return!0;const n=H(s);return n!==void 0&&t(n)},zn=(e,t=2)=>{const s=new Set;for(const n of[e,...e.getDescendants()]){const i=ge(n);i!==void 0&&s.add(i);const o=t>0&&r.isIdentifier(n)?H(n):void 0;if(o!==void 0)for(const a of zn(o,t-1))s.add(a)}return s},Oe=e=>{const t=h(e)??e;if(!r.isBinaryExpression(t))return[];const s=t.getOperatorToken().getKind(),n=t.getLeft(),i=t.getRight();if(s===d.BarBarToken)return[...Oe(n),...Oe(i)];if(s===d.AmpersandAmpersandToken){const l=(u,f)=>{const g=ge(h(u)??u);return g===void 0?[]:Oe(f).filter(p=>p===g)};return[...l(n,i),...l(i,n)]}if(s!==d.ExclamationEqualsEqualsToken&&s!==d.ExclamationEqualsToken)return[];const o=[],a=ge(h(n)??n),c=ge(h(i)??i);return a!==void 0&&wt(i)&&o.push(a),c!==void 0&&wt(n)&&o.push(c),o},td=e=>{const t=h(e)??e;if(!r.isIdentifier(t))return!1;const s=t.getSymbol(),n=s?.getAliasedSymbol()?.getValueDeclaration()??s?.getValueDeclaration();if(!r.isVariableDeclaration(n))return!1;const i=h(n.getInitializer());return r.isCallExpression(i)&&tr(i.getExpression(),"defineIdentityGuard")},sd=e=>{if(!td(e.getExpression()))return[];const t=e.getArguments();return t.flatMap((s,n)=>{const i=ge(h(s)??s),o=t.some((a,c)=>c!==n&&wt(a));return i!==void 0&&o?[i]:[]})},nd=e=>{if(r.isThrowStatement(e))return!0;if(!r.isBlock(e))return!1;const t=e.getStatements().at(-1);return t!==void 0&&r.isThrowStatement(t)},id=e=>r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e),ks=(e,t)=>{for(let s=e.getParent();s!==void 0;s=s.getParent()){if(s===t||s.compilerNode===t.compilerNode)return!0;if(!(r.isBlock(s)||r.isExpressionStatement(s)||r.isAwaitExpression(s)||r.isParenthesizedExpression(s)||r.isVariableStatement(s)||r.isVariableDeclarationList(s)||r.isVariableDeclaration(s)))return!1}return!1},rd=e=>r.isAwaitExpression(e.getParent())||e.getType().isVoid(),od=(e,t)=>{const s=new Set;for(const n of e.getDescendantsOfKind(d.IfStatement))if(n.getEnd()<=t&&ks(n,e)&&nd(n.getThenStatement()))for(const i of Oe(n.getExpression()))s.add(i);for(const n of e.getDescendantsOfKind(d.CallExpression))if(n.getEnd()<=t&&rd(n)&&ks(n,e))for(const i of sd(n))s.add(i);return s},ad=(e,t)=>{const s=zn(t);if(s.size===0)return!1;const n=e.getFirstAncestor(id);if(n===void 0)return!1;const i=od(n,e.getStart());return[...s].every(o=>i.has(o))},cd=new Set(["at","concat","filter","find","findLast","flat","reverse","slice","sort","toReversed","toSorted"]),ld=new Map([["Array",new Set(["from","of"])],["Object",new Set(["entries","values"])]]),Pt=new Set(["catch","every","filter","finally","find","findIndex","findLast","findLastIndex","flatMap","forEach","map","reduce","reduceRight","some","sort","then"]),$n=e=>e.getNameNode().getDescendantsOfKind(d.BindingElement).filter(t=>r.isIdentifier(t.getNameNode())),dd=e=>{const t=P(e),s=t.getParent();if(r.isVariableDeclaration(s))return y(s.getInitializer(),t)?s:void 0;const n=r.isForOfStatement(s)&&s.getExpression()===t?s.getInitializer():void 0;return r.isVariableDeclarationList(n)?n.getDeclarations()[0]:void 0},ud=e=>{const t=dd(e);return t===void 0?void 0:r.isIdentifier(t.getNameNode())?r.isForOfStatement(t.getParent().getParent())||J(t)?[t]:void 0:$n(t)},pe=e=>e.isUnion()?e.getUnionTypes().every(t=>pe(t)):e.isIntersection()?e.getIntersectionTypes().some(t=>pe(t)):!e.isAny()&&!e.isUnknown()&&!e.isObject()&&!e.isTypeParameter(),Me=(e,t,s)=>{const n=r.isCallExpression(e)?h(e.getExpression()):void 0;return r.isPropertyAccessExpression(n)&&t.has(n.getName())&&(s===void 0||n.getExpression()===s)},ke=e=>{const t=h(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=t.getBody();return r.isBlock(s)?s.getDescendantsOfKind(d.ReturnStatement).filter(n=>n.getFirstAncestor(i=>r.isFunctionLikeDeclaration(i))===t).map(n=>n.getExpression()):[s]},fd=e=>{const t=r.isCallExpression(e)?h(e.getExpression()):void 0,s=r.isPropertyAccessExpression(t)?t.getExpression():void 0;return r.isPropertyAccessExpression(t)&&r.isIdentifier(s)&&ld.get(s.getText())?.has(t.getName())===!0&&De(s)},gd=e=>{const t=ht(e);if(!r.isArrowFunction(t)&&!r.isFunctionExpression(t))return;const s=P(t),n=s.getParent();return r.isCallExpression(n)&&n.getArguments().includes(s)&&Me(n,pn)?n:void 0},pd=(e,t)=>{if(!(r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e))||e.getExpression()!==t)return;const s=P(e),n=s.getParent();return!r.isCallExpression(n)||n.getExpression()!==s?e:Me(n,cd,t)?n:void 0},md=(e,t)=>{if(r.isAwaitExpression(e))return e;if(r.isConditionalExpression(e))return e.getCondition()===t?void 0:e;const s=r.isBinaryExpression(e)?e.getOperatorToken().getKind():void 0;return s===d.QuestionQuestionToken||s===d.BarBarToken||s===d.AmpersandAmpersandToken?e:void 0},hd=(e,t)=>{if(r.isArrayLiteralExpression(e))return e;const n=r.isSpreadElement(e)||r.isSpreadAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isPropertyAssignment(e)&&y(e.getInitializer(),t)?e.getParent():void 0;return r.isArrayLiteralExpression(n)||r.isObjectLiteralExpression(n)?n:void 0},Rs=e=>{const t=P(e),s=t.getParent();if(s===void 0)return;const n=r.isCallExpression(s)&&s.getArguments().includes(t)&&fd(s);return pd(s,t)??md(s,t)??hd(s,t)??(n?s:gd(t))},vd=5e4,Vn=()=>({inProgress:new Set,verdicts:new Map});class Ed{cuts=0;work=0;reset(){this.work=0}cut(){return this.cuts+=1,!0}spend(){return this.work+=1,this.work>vd&&this.cut()}memoized(t,s,n){const i=n.verdicts.get(t);if(i!==void 0)return i;if(n.inProgress.has(t))return this.cuts+=1,!1;if(this.spend())return!0;const o=this.cuts;n.inProgress.add(t);let a;try{a=s()}finally{n.inProgress.delete(t)}return this.cuts===o&&n.verdicts.set(t,a),a}}const xd=8,Sd=8;class Ad{budget;scope;taint;verdicts=Vn();constructor(t,s,n){this.scope=t,this.budget=s,this.taint=n}isCompromised(t){return this.flowHasCompromisingUse(t)&&!pe(t.getType())}flowHasCompromisingUse(t){return this.budget.memoized(t.compilerNode,()=>{const s=this.budget.cuts,n=[],i=new Set,o=(c,l)=>{i.has(c.compilerNode)||(i.add(c.compilerNode),n.push({binding:c,hops:l}))};let a=!1;o(t,0);for(const c of n)if(a=(c.binding===t?void 0:this.verdicts.verdicts.get(c.binding.compilerNode))??this.visitBinding(c,t,o),a)break;if(!a&&this.budget.cuts===s)for(const c of i)this.verdicts.verdicts.set(c,!1);return a},this.verdicts)}visitBinding({binding:t,hops:s},n,i){const o=t.getNameNode();if(!r.isIdentifier(o)){for(const l of r.isParameterDeclaration(t)?$n(t):[])i(l,s);return!1}if(this.budget.spend())return!0;const a=(l,u)=>u&&s>=xd?this.budget.cut():(i(l,u?s+1:s),!1);return this.taint.referencesTo(t,o.getText()).some(l=>this.valueCompromises(P(l),!0,a,0))&&(t===n||!pe(t.getType()))}valueCompromises(t,s,n,i){let o=t;for(let p=Rs(o);p!==void 0;p=Rs(o)){if(r.isCallExpression(p)&&this.callbackCompromises(p,n))return!0;o=P(p)}const a=o.getParent(),c=o===t&&s,l=()=>!c&&pe(o.getType());if(ze(o))return!c&&(!r.isBinaryExpression(a)||this.taint.isTaintedValue(a.getRight(),!1));const u=ud(o);if(u!==void 0)return u.some(p=>n(p,!0));const f=r.isPropertyAccessExpression(a)&&a.getExpression()===o?a.getParent():void 0;if(r.isCallExpression(f)&&f.getExpression()===a)return this.methodCallCompromises(f,n);const g=this.nestedReturningFunctionOf(o);return g!==void 0?this.resultCompromises(g,n,i)&&!l():this.positionCompromises(o,n)&&!l()}resultCompromises(t,s,n){const i=P(t).getParent();if(n>=Sd)return this.budget.cut();if(r.isCallExpression(i))return i.getExpression()===P(t)?this.valueCompromises(i,!1,s,n+1):!Me(i,Pt);const o=r.isFunctionDeclaration(t)?t:i,a=r.isFunctionDeclaration(o)||J(o)?o.getNameNode():void 0;return o===void 0||!r.isIdentifier(a)?!0:this.taint.referencesTo(o,a.getText()).some(c=>{const l=P(c),u=l.getParent();return!r.isCallExpression(u)||u.getExpression()!==l||this.valueCompromises(u,!1,s,n+1)})}methodCallCompromises(t,s){return t.getArguments().filter(i=>ke(i)===void 0).some(i=>this.taint.isTaintedValue(i,!1))||this.callbackCompromises(t,s)}callbackCompromises(t,s){const n=Me(t,Pt)?t.getArguments()[0]:void 0;if(n===void 0)return!1;const i=Nt(n);return i!==void 0&&this.taint.isInImpl(i)?i.getParameters().some(o=>s(o,!1)):this.taint.isTaintedValue(n,!1)}positionCompromises(t,s){const n=t.getParent();if(r.isCallExpression(n)&&n.getArguments().includes(t))return this.argumentCompromises(n,t,s);const i=r.isSpreadElement(n)?n.getParent():void 0;if(n!==void 0&&r.isCallExpression(i))return!bt(n,this.scope.context)&&this.isOpaqueCallTainted(i.getExpression(),i.getArguments(),n);if(r.isNewExpression(n))return this.isOpaqueCallTainted(n.getExpression(),n.getArguments(),t);if(r.isTemplateSpan(n)){const o=n.getParent(),a=o.getParent(),c=o.getTemplateSpans().map(l=>l.getExpression());return r.isTaggedTemplateExpression(a)&&this.isOpaqueCallTainted(a.getTag(),c,t)}return!this.isReadPosition(t)}argumentCompromises(t,s,n){if(bt(s,this.scope.context))return!1;const i=Nt(t.getExpression()),o=i===void 0?void 0:_n(i,t,s);return o?.kind==="unreached"?!1:o?.kind==="parameter"&&i!==void 0&&this.taint.isInImpl(i)?n(o.parameter,!1):this.isOpaqueCallTainted(t.getExpression(),t.getArguments(),s)}isReadPosition(t){const s=t.getParent();return s===void 0||r.isExpressionStatement(s)||r.isForStatement(s)||r.isElementAccessExpression(s)||Kn(t)||y(ht(t),this.scope.impl)}isOpaqueCallTainted(t,s,n){const i=!r.isIdentifier(h(n));return this.taint.isTaintedValue(t,!1)||s.some(o=>(o!==n||i)&&this.taint.isTaintedValue(o,!1))}nestedReturningFunctionOf(t){const s=ht(t);return y(s,this.scope.impl)?void 0:s}}const yd=new Set(["at","every","filter","finally","find","findIndex","findLast","findLastIndex","forEach","order","slice","some","sort","withIndex","withSearchIndex"]),bd=e=>{const t=h(e);if(!r.isIdentifier(t))return r.isPropertyAccessExpression(t)||r.isElementAccessExpression(t);const s=O(t),n=r.isVariableDeclaration(s)?h(s.getInitializer()):void 0;return s===void 0||r.isFunctionDeclaration(s)||r.isParameterDeclaration(s)||r.isArrowFunction(n)||r.isFunctionExpression(n)},Nd=new Set(["all","allSettled","any","race"]),Fs=e=>r.isParameterDeclaration(e)?e:r.isBindingElement(e)?e.getFirstAncestorByKind(d.Parameter):void 0,ct=8;class wd{budget=new Ed;referencesByDeclaration=new Map;referencesByName=new Map;scope;verdicts=Vn();walk;variableDepth=0;queryDepth=0;constructor(t){this.scope=t,this.walk=new Ad(t,this.budget,this);for(const s of t.impl.getDescendantsOfKind(d.Identifier)){const n=s.getText();this.referencesByName.set(n,[...this.referencesByName.get(n)??[],s])}}isTaintedValue(t,s){this.queryDepth===0&&this.budget.reset(),this.queryDepth+=1;try{return s&&this.isRootedInContext(t,ct)?!1:(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(i=>ji(i)&&this.isIdentifierTainted(i))}finally{this.queryDepth-=1}}isInImpl(t){const{impl:s}=this.scope;return t!==s&&s.getPos()<=t.getPos()&&t.getEnd()<=s.getEnd()}referencesTo(t,s){let n=this.referencesByDeclaration.get(s);if(n===void 0){n=new Map;for(const i of this.referencesByName.get(s)??[]){const o=O(i)?.compilerNode;o!==void 0&&n.set(o,[...n.get(o)??[],i])}this.referencesByDeclaration.set(s,n)}return(n.get(t.compilerNode)??[]).filter(i=>i.getParent()!==t)}flowsIntoTainted(t){if([t.getInitializer(),...t.getDescendantsOfKind(d.BindingElement).map(g=>g.getInitializer())].some(g=>g!==void 0&&this.isTaintedValue(g,!1)))return!0;const n=t.getParentOrThrow(),i=r.isFunctionLikeDeclaration(n)?n.getParameters().findIndex(g=>g.compilerNode===t.compilerNode):-1,o=P(n),a=o.getParent();if(i===-1)return!0;if(r.isCallExpression(a)){if(a.getExpression()===o)return this.isCallSiteTainted(a,i,t.isRestParameter());const g=h(a.getExpression());if(!r.isPropertyAccessExpression(g)||!Pt.has(g.getName()))return!0;const p=a.getArguments().filter(x=>x!==o);return this.isTaintedValue(g.getExpression(),!0)||p.some(x=>this.isTaintedValue(x,!1))}const c=r.isVariableDeclaration(a)&&J(a)?a:void 0,l=r.isFunctionDeclaration(n)?n:c,u=l?.getNameNode();if(l===void 0||!r.isIdentifier(u))return!0;const f=this.referencesTo(l,u.getText());return f.length===0||f.some(g=>{const p=P(g),x=p.getParent();return!r.isCallExpression(x)||x.getExpression()!==p||this.isCallSiteTainted(x,i,t.isRestParameter())})}isCallSiteTainted(t,s,n){const i=t.getArguments(),o=i.findIndex(c=>r.isSpreadElement(c)),a=c=>c===s||n&&c>s||o!==-1&&o<=s&&c>=o;return i.some((c,l)=>a(l)&&this.isTaintedValue(c,!1))}isContextRootedCombinator(t,s){const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getExpression():void 0,a=r.isPropertyAccessExpression(n)&&r.isIdentifier(i)&&i.getText()==="Promise"&&De(i)&&Nd.has(n.getName())?h(t.getArguments()[0]):void 0;if(r.isArrayLiteralExpression(a)){const f=a.getElements();return f.length>0&&f.every(g=>!r.isSpreadElement(g)&&this.isRootedInContext(g,s))}const c=r.isCallExpression(a)?h(a.getExpression()):void 0,l=r.isCallExpression(a)&&r.isPropertyAccessExpression(c)&&c.getName()==="map"?h(a.getArguments()[0]):void 0,u=l===void 0?void 0:ke(l);return u!==void 0&&u.length>0&&u.every(f=>f!==void 0&&this.isRootedInContext(f,s))}isIdentifierTainted(t){const s=t.getText();if(s==="arguments")return!0;const n=O(t),i=Fs(n);if(i!==void 0)return this.isSource(i);if(s==="args")return!0;if(n===void 0||!this.isInImpl(n))return!1;if(r.isFunctionDeclaration(n))return this.budget.memoized(n.compilerNode,()=>this.isTaintedValue(n,!1),this.verdicts);if(r.isBindingElement(n)&&this.walk.isCompromised(n))return!0;const o=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n;return r.isVariableDeclaration(o)&&this.isVariableTainted(o)}callChainVerdict(t,s){if(this.isContextRootedCombinator(t,s))return!0;const n=h(t.getExpression()),i=r.isPropertyAccessExpression(n)?n.getName():void 0;return i!==void 0&&gn.has(i)?!1:i!==void 0&&pn.has(i)?this.isCallbackResultServerScoped(t,s)?void 0:!1:t.getArguments().some(a=>ke(a)!==void 0)&&(i===void 0||!yd.has(i))?!1:void 0}isCallbackResultServerScoped(t,s){const n=(i,o=[])=>{const a=Tt(i),c=r.isIdentifier(a)?Fs(O(a)):void 0;return c!==void 0&&o.includes(c)?!0:this.isRootedInContext(i,s)||!this.isTaintedValue(i,!1)};return t.getArguments().every(i=>{const o=ke(i);if(o===void 0)return!bd(i)&&n(i);const a=h(i),c=r.isArrowFunction(a)||r.isFunctionExpression(a)?a.getParameters():[];return o.every(l=>l===void 0||n(l,c))})}isRootedInContext(t,s){const n=Vi(t,u=>this.callChainVerdict(u,s)),i=n.root;if(n.verdict!==void 0)return n.verdict;if(Mn(i,this.scope.context))return!0;const o=r.isIdentifier(i)?O(i):void 0,a=r.isBindingElement(o)?o.getFirstAncestorByKind(d.VariableDeclaration):o,c=J(a)&&this.isInImpl(a)?a.getInitializer():void 0,l=r.isBindingElement(o)?o:a;return s>0&&c!==void 0&&(r.isBindingElement(l)||r.isVariableDeclaration(l))&&!this.walk.isCompromised(l)&&this.isRootedInContext(c,s-1)}isSource(t){const{impl:s,parameter:n}=this.scope;return t.compilerNode===n?.compilerNode?!0:t.getParent()!==s&&this.isInImpl(t)&&(this.budget.memoized(t.compilerNode,()=>this.flowsIntoTainted(t),this.verdicts)||this.walk.isCompromised(t))}isVariableTainted(t){return this.budget.memoized(t.compilerNode,()=>{const s=t.getParent().getParent();if(r.isCatchClause(t.getParent())||this.walk.isCompromised(t))return!0;if(r.isForOfStatement(s)||r.isForInStatement(s))return this.isTaintedValue(s.getExpression(),!0);const n=t.getInitializer(),i=Ot(t);if(n===void 0||i)return!0;if(this.isRootedInContext(n,ct))return!1;if(this.variableDepth>=ct)return this.budget.cut();this.variableDepth+=1;try{return this.isTaintedValue(n,!1)}finally{this.variableDepth-=1}},this.verdicts)}}const Ls=new WeakMap,Pd=e=>{const t=Ls.get(e.impl.compilerNode);if(t!==void 0)return t;const s=new wd(e);return Ls.set(e.impl.compilerNode,s),s},Id=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Cd=new Set(["insert","insertManyUnsafe","patch","replace"]),Td=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();return Cd.has(t)&&Xi(e.getExpression())?t:void 0},Od=(e,t)=>{if(t!=="insertManyUnsafe")return r.isObjectLiteralExpression(e)?[e]:[];if(!r.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())r.isObjectLiteralExpression(n)&&s.push(n);return s},kd=(e,t)=>{const s=cn(e);return s?.member===t?h(s.object):void 0},Ds=(e,t)=>r.isIdentifier(e)&&O(e)?.compilerNode===t.compilerNode,Un=(e,t,s,n=1)=>{const i=kd(e,s);if(i!==void 0)return Ds(i,t);const o=r.isIdentifier(e)?O(e):void 0;if(r.isBindingElement(o)){const c=o.getParent(),l=c.getParent();return o.getDotDotDotToken()===void 0&&ee(o)===s&&r.isObjectBindingPattern(c)&&(l.compilerNode===t.compilerNode||J(l)&&Ds(h(l.getInitializer()),t))}const a=J(o)?o.getInitializer():void 0;return n>0&&a!==void 0&&Un(a,t,s,n-1)},It=e=>{const t=h(e)??e;return r.isConditionalExpression(t)?[...It(t.getWhenTrue()),...It(t.getWhenFalse())]:[t]},Rd=(e,t,s)=>{const n=[],i=s===void 0?void 0:Pd(s);for(const o of e.getProperties()){let a,c;if(r.isPropertyAssignment(o)?(a=A(o),c=o.getInitializer()):r.isShorthandPropertyAssignment(o)&&(a=A(o),c=o.getNameNode()),a===void 0||c===void 0||!Id.has(a))continue;const l=It(c).filter(f=>i===void 0?j(f)&&!Ji(f):i.isTaintedValue(f,!0));if(l.length>0){const f=t.ownerField===a&&s?.pristine===!0&&Un(c,s.parameter,a),g=l.every(p=>ad(t.call,p));n.push({field:a,file:t.relativePath,line:t.call.getStartLineNumber(),method:t.method,scope:t.scope,...f&&{ownerScoped:!0},...g&&{guarded:!0}})}}return n},Fd=(e,t,s)=>{const n=Td(e.getExpression()),i=n===void 0?void 0:e.getArguments()[1];if(n===void 0||i===void 0)return[];const o=Od(i,n);if(o.length===0)return[];const a=E(e),c=Zl(e),l={call:e,method:n,ownerField:c===void 0?void 0:s(c.mutatorName),relativePath:t,scope:a};return o.flatMap(u=>Rd(u,l,c))},Ld=(e,t,s=[],n=[])=>{const i=new Map(n.map(c=>[`${c.filePath}:${c.exportName}`,c.owner])),o=T(e,t,(c,l)=>Fd(c,l,u=>i.get(`${l}:${u}`))),a=new Map(s.map(c=>[`${c.filePath}:${c.exportName}`,c.adminOnly===!0]));return kt(o,s).map(c=>Gi(c.scope)?.every(f=>a.get(`${c.file}:${f}`)===!0)===!0?{...c,adminOnly:!0}:c)},Dd=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Md=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,_d=e=>{const t=D(e,"webhookToleranceSeconds");return t&&r.isPropertyAssignment(t)?Md(t.getInitializer()):void 0},Kd=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Dd.has(s))return;const[n]=e.getArguments(),i=n&&r.isObjectLiteralExpression(n)?_d(n):void 0;return{callee:s,scope:E(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Bd=(e,t)=>T(e,t,Kd),zd=new Map([["defineQueue",0],["defineSubscription",1],["defineWorkflow",0]]),$d=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},Vd=(e,t)=>{const s=e.getArguments()[t];if(!s||!r.isObjectLiteralExpression(s))return;const n=D(s,"handler");if(n===void 0||!r.isPropertyAssignment(n))return;const i=n.getInitializer();if(i&&(r.isArrowFunction(i)||r.isFunctionExpression(i)))return i},qn=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&r.isIdentifier(s)?s.getText():void 0},Wn=(e,t)=>e===t||e.startsWith(`${t}.`),Hn=e=>{const t=e.getDescendantsOfKind(d.PropertyAccessExpression);return r.isPropertyAccessExpression(e)&&t.push(e),t},Ms=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getNameNode()===e||r.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(r.isBindingElement(t)&&t.getNameNode()===e)},jn=e=>{const t=e.getDescendantsOfKind(d.Identifier).filter(s=>Ms(s));return r.isIdentifier(e)&&Ms(e)&&t.push(e),t},Ud=e=>{if(!r.isVariableDeclaration(e))return[];const t=e.getNameNode();return r.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(d.BindingElement).map(s=>s.getName())},qd=e=>{const t=qn(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(d.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),o=r.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;o&&r.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Wd=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:qd(e),i=new Set,o=a=>Hn(a).some(c=>n.some(l=>Wn(c.getText(),l)))?!0:jn(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(d.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Ud(a))i.add(l)}return{names:i,prefixes:n}},Hd=(e,t)=>Hn(e).some(s=>t.prefixes.some(n=>Wn(s.getText(),n)))?!0:jn(e).some(s=>t.names.has(s.getText())),jd=e=>{const t=Ui(e);return t===void 0?void 0:{exportName:String(t.at(-1)),file:t.slice(0,-1).join("/")}},Gd=(e,t,s)=>{const n=qn(e,0);if(n===void 0)return[];const i=Wd(e,t,n),o=new Set([n,...i.prefixes.filter(c=>c.endsWith(".body")).map(c=>c.slice(0,-5))]),a=[];for(const c of e.getDescendantsOfKind(d.CallExpression)){const l=c.getExpression();if(!r.isPropertyAccessExpression(l)||!ln.has(l.getName())||!o.has(l.getExpression().getText()))continue;const u=c.getArguments()[1];if(!u||!Hd(u,i))continue;const f=jd(c.getArguments()[0]);f!==void 0&&a.push({dispatchKind:t,file:s,scope:E(c),line:c.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return a},Yd=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=$d(n),o=i===void 0?void 0:zd.get(i);if(o===void 0)continue;const a=Vd(n,o);a!==void 0&&s.push(...Gd(a,i==="defineWorkflow"?"workflow":"queue",t))}return s},Qd=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Yd(i,I(t,n)))}return s},_s={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Ks=new Set(["account","credential","member","passkey","session","user"]),Xd=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Jd=e=>{const s=Xd(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Ks.has(s)||Ks.has(n)},Zd=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},eu=(e,t)=>{const{objects:s,opaque:n}=Mt(e,t);return ma(s).some(i=>Zd(i))?!0:n?void 0:!1},tu=e=>{const t=e.getArguments()[0];return!t||!r.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!D(t,"captcha"),usesRateLimit:!!D(t,"rateLimit")}},su=e=>{if(r.isCallExpression(e))return e;if(!r.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&r.isCallExpression(s)?s:void 0},Re={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},nu=e=>{const t=su(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=tu(t);return{...Re,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in _s?{...Re,[_s[s]]:!0}:Re},iu=e=>{const t={...Re};let s=e;for(;r.isCallExpression(s);){const n=s.getExpression();if(!r.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const o=nu(i);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=n.getExpression()}return t},ru=new Set(["insert","insertMany","insertManyUnsafe","replace"]),ou=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!ru.has(t.getName()))return!1;const s=t.getExpression();if(!$(s))return!1;const i=e.getArguments()[0];return!i||!(r.isStringLiteral(i)||r.isNoSubstitutionTemplateLiteral(i))?!1:Jd(i.getLiteralText())},au=new Set(["create","publish","publishBatch","runAfter","runAt","send","sendBatch"]),Bs=new Set(["queues","scheduler","topics","workflows"]),cu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!au.has(t.getName()))return!1;let s=t.getExpression();for(;r.isCallExpression(s)||r.isElementAccessExpression(s)||r.isPropertyAccessExpression(s);){if(r.isPropertyAccessExpression(s)&&Bs.has(s.getName())&&Zi(s.getExpression()))return!0;s=s.getExpression()}const n=Rt(s);return n?.length===1&&Bs.has(n[0]??"")},lu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return $(s)},Gn=new Set(["generateObject","generateText","streamObject","streamText"]),du=e=>{const t=b(e.getExpression());return t!==void 0&&Gn.has(t)},uu=e=>{const t=b(e.getExpression());if(t===void 0||!Gn.has(t))return!1;const s=e.getArguments()[0];return!s||!r.isObjectLiteralExpression(s)||s.getProperties().some(n=>r.isSpreadAssignment(n))?!1:!D(s,"maxOutputTokens")},fu=new Set(["log","span","trace"]),gu=new Set(["ai"]),pu=new Set(["email","mail"]),mu=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","topics","workflows"]),lt=(e,t)=>[...t].some(s=>$e(e,s).length>0),Yn=new Set([d.ArrowFunction,d.FunctionDeclaration,d.FunctionExpression,d.GetAccessor,d.MethodDeclaration,d.SetAccessor]),hu=new Set(["every","filter","flatMap","forEach","map","some"]),vu=new Set(["all","allSettled","race"]),Qn=e=>{const t=e.getParent();if(!t||!r.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getName();if(hu.has(n))return t;const i=s.getExpression();if(r.isIdentifier(i)&&i.getText()==="Promise"&&vu.has(n))return t},Eu=e=>{let t=e.getParent();for(;t;){if(r.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Yn.has(t.getKind())){const s=Qn(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},xu=e=>{let t=e.getParent();for(;t!==void 0;){if(r.isCallExpression(t)&&t.getExpression().getText()==="Promise.allSettled")return!0;if(Yn.has(t.getKind())){if(t=Qn(t),t===void 0)return!1;continue}t=t.getParent()}return!1},Su=e=>{const t=e.getFirstAncestor(u=>r.isArrowFunction(u)||r.isFunctionExpression(u)),s=t?.getParent();if(!t||!r.isCallExpression(s)||!s.getArguments().includes(t))return!1;const n=s.getExpression();if(!r.isIdentifier(n))return!1;const i=n.getSymbol(),o=i?.getAliasedSymbol()?.getValueDeclaration()??i?.getValueDeclaration(),a=r.isVariableDeclaration(o)?o.getInitializer():o;if(!r.isArrowFunction(a)&&!r.isFunctionExpression(a)&&!r.isFunctionDeclaration(a))return!1;const c=s.getArguments().indexOf(t),l=a.getParameters()[c]?.getName();return l===void 0?!1:a.getDescendantsOfKind(d.TryStatement).some(u=>{const f=u.getTryBlock().getDescendantsOfKind(d.CallExpression).some(p=>{const x=p.getExpression();return r.isIdentifier(x)&&x.getText()===l&&r.isAwaitExpression(p.getParent())}),g=u.getCatchClause();return f&&g!==void 0&&g.getDescendantsOfKind(d.ThrowStatement).length>0})},Au=e=>{let t=e;for(;;){const s=t.getParent();if(!r.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!r.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},yu=e=>{let t=e;for(;;){const s=t.getParent();if(r.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return r.isCallExpression(s)&&s.getExpression()===t?s:void 0}},bu=e=>{let t=!1,s=!0;for(const n of[...mu].flatMap(i=>$e(e,i))){const i=yu(n);i&&(t=!0,!Eu(i)&&!Au(i)&&!Su(i)&&!xu(i)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Nu=e=>e.getDescendantsOfKind(d.ThrowStatement).some(t=>{const s=t.getExpression();if(!r.isNewExpression(s))return!1;const n=s.getExpression();return r.isIdentifier(n)&&n.getText()==="Error"}),zs="lunora-advisor-exempt",wu=/^[\s*/]+/u,Pu=/[\w-]/u,Iu=e=>{const s=(e.getFirstAncestorByKind(d.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
2
- `);for(const n of s.split(`
3
- `)){const i=n.replace(wu,"");if(!i.startsWith(zs))continue;const o=i.slice(zs.length);if(Pu.test(o.charAt(0)))continue;const a=o.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":o.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Cu=e=>{const[t]=e.getArguments();if(t){if(r.isObjectLiteralExpression(t)){const s=D(t,"handler");return s?r.isPropertyAssignment(s)?s.getInitializer():r.isShorthandPropertyAssignment(s)?s.getNameNode():r.isMethodDeclaration(s)?s:void 0:void 0}return t}},Tu=(e,t)=>{const s=Cu(t);if(!s)return;if(r.isArrowFunction(s)||r.isFunctionExpression(s)||r.isMethodDeclaration(s))return e;if(!r.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),o=n.getVariableDeclaration(i)?.getInitializer();return o&&(r.isArrowFunction(o)||r.isFunctionExpression(o))?o:n.getFunction(i)},Ou=e=>{let t=!1,s=!1,n=!1,i=!1,o=!1;for(const l of e.getDescendantsOfKind(d.CallExpression))if(ou(l)&&(o=!0),cu(l)&&(t=!0),lu(l)&&(i=!0),du(l)&&(s=!0),uu(l)&&(n=!0),o&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=bu(e);return{callsMail:lt(e,pu),emitsEvent:lt(e,fu),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||lt(e,gu),throwsBareError:Nu(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:o}},ku=(e,t)=>{const s=e.getInitializer();if(!s||!r.isCallExpression(s))return;const n=Y(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?iu(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},o=Tu(e,s);return{...o?Ou(o):{},...Iu(e),...i,analyzableBody:o!==void 0,exportName:V(e)??e.getName(),file:t,hasEmailArg:eu(s,n.receiver),kind:n.kind,visibility:n.visibility}},Ru=(e,t)=>{const s=[];for(const n of G(e)){const i=ku(n,t);i&&s.push(i)}return s},Fu=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ru(i,I(t,n)))}return s},Lu=new Set(["dbRateLimit","rateLimit"]),Du=e=>r.isArrowFunction(e)?e.getBody():e,Mu=e=>{if(!r.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&r.isIdentifier(t)?t:void 0},Xn=e=>{const t=e.getParent();return r.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},Jn=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(d.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const i=n.getParent();return!(r.isPropertyAccessExpression(i)&&i.getNameNode()===n)})},_u=(e,t)=>j(e)||t!==void 0&&Jn(e,t).some(s=>Xn(s)),Ku=(e,t)=>t===void 0?te(e):Jn(e,t).some(s=>!Xn(s)),Bu=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Lu.has(s))return;const n=C(an(e.getArguments()[2]),"key");if(!n)return;const i=Du(n),o=Mu(n);if(!(!_u(i,o)||Ku(i,o)))return{callee:s,scope:E(e),file:t,limitName:on(e),line:e.getStartLineNumber()}},zu=(e,t)=>T(e,t,Bu),$u=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Vu=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||!$u.has(t.getName()))return;const s=t.getExpression();if($(s)){const n=e.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}if(r.isPropertyAccessExpression(s)&&$(s.getExpression()))return s.getName()},Uu=e=>{let t=e;for(;r.isCallExpression(t);){const s=t.getExpression();if(!r.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&$(s.getExpression())){const n=t.getArguments()[0];return n&&r.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},qu=e=>{let t=h(e)??e;for(;r.isAwaitExpression(t);)t=h(t.getExpression())??t.getExpression();return t},Zn=(e,t=!1)=>{const s=qu(e);if(r.isIdentifier(s)){if(t)return;const n=H(s);return n===void 0?void 0:Zn(n,!0)}if(r.isCallExpression(s))return Vu(s)??Uu(s)},Wu=e=>{const t=e.getBody();if(!r.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(d.ReturnStatement)){const i=n.getFirstAncestor(a=>r.isArrowFunction(a)||r.isFunctionExpression(a)||r.isFunctionDeclaration(a)),o=n.getExpression();i===e&&o!==void 0&&s.push(o)}return s},Hu=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!r.isCallExpression(s))return[];const n=Y(s);if(n?.kind!=="query")return[];const i=On(s);if(i===void 0)return[];const o=n.receiver!==void 0&&sr(n.receiver,"output"),a=n.receiver!==void 0&&mn(n.receiver,"use","mask"),c=new Set,l=[];for(const u of Wu(i)){const f=Zn(u);f===void 0||c.has(f)||(c.add(f),l.push({exportName:V(e)??e.getName(),file:t,line:u.getStartLineNumber(),table:f,usesMask:a,usesOutput:o,visibility:n.visibility}))}return l},ju=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of G(i))s.push(...Hu(a,o))}return s},Gu=e=>{if(!e||!r.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(r.isPropertyAssignment(s)||r.isShorthandPropertyAssignment(s)||r.isMethodDeclaration(s)||r.isGetAccessorDeclaration(s))&&t.push(A(s));return t},Yu=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Y(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=En(o);if(a===void 0)continue;const c=Gu(C(a.options,"with"));c.length!==0&&i.push({exportName:V(e)??e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},Qu=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of G(i))s.push(...Yu(a,o))}return s},z=(e,t)=>`${e}:${t}`,$s=(e,t,s,n)=>s===void 0?void 0:{endLine:e.getEndLineNumber(),exported:n,file:t,name:s,node:e,startLine:e.getStartLineNumber()},Xu=(e,t)=>[...X(e,t,d.FunctionDeclaration,(s,n)=>s.getParent().getKind()===d.SourceFile?$s(s,n,s.getName(),s.isExported()):void 0),...X(e,t,d.VariableDeclaration,(s,n)=>{const i=s.getVariableStatement();return i?.getParent().getKind()===d.SourceFile?$s(i,n,s.getName(),i.isExported()):void 0})],Ju=(e,t,s)=>{const n=e.getExpression();if(!r.isIdentifier(n))return;const i=n.getSymbol(),o=(i?.getAliasedSymbol()??i)?.getDeclarations()[0];if(o===void 0||!(r.isFunctionDeclaration(o)||r.isVariableDeclaration(o)))return;const a=o.getName(),c=I(s,o.getSourceFile().getFilePath());return a===void 0?void 0:t.get(z(c,a))},Zu=e=>`${e.table}|${e.method}|${e.fields?.join(",")??"*"}`,ef=(e,t)=>{const s=new Map(e.map(n=>[z(n.file,n.name),new Map]));for(const n of t){const i=e.find(o=>o.file===n.file&&o.startLine<=n.line&&n.line<=o.endLine);i!==void 0&&n.table!==""&&s.get(z(i.file,i.name))?.set(Zu(n),{fields:n.fields,method:n.method,table:n.table})}return s},tf=(e,t,s)=>e.node.getDescendantsOfKind(d.CallExpression).map(n=>Ju(n,t,s)).filter(n=>n!==void 0),sf=(e,t,s,n)=>{for(const i of e){const o=i.scope.kind==="module"?void 0:t.get(z(i.file,i.scope.name)),a=i.target===void 0?void 0:s.get(i.target);i.kind==="call"&&o!==void 0&&a!==void 0&&n.get(z(o.file,o.name))?.push(a)}},nf=(e,t,s)=>{const n=new Map(e.map(a=>[z(a.file,a.name),a])),i=new Map(e.map(a=>[`${Lt(a.file)}:${a.name}`,a])),o=new Map(e.map(a=>[z(a.file,a.name),tf(a,n,t)]));return sf(s,n,i,o),o},rf=(e,t)=>{let s=!1;for(const[n,i]of t??[])e!==void 0&&!e.has(n)&&(e.set(n,i),s=!0);return s},of=(e,t,s)=>{let n=!0;for(;n;){n=!1;for(const i of e)for(const o of s.get(z(i.file,i.name))??[])rf(t.get(z(i.file,i.name)),t.get(z(o.file,o.name)))&&(n=!0)}},af=(e,t,s,n)=>{const i=Xu(e,t),o=ef(i,s);return of(i,o,nf(i,t,n)),i.filter(a=>a.exported).flatMap(a=>[...o.get(z(a.file,a.name))?.values()??[]].map(c=>({...c,exportName:a.name,file:a.file})))},_e=e=>{if(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(r.isBinaryExpression(e)&&e.getOperatorToken().getKind()===d.PlusToken){const t=_e(e.getLeft()),s=_e(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},cf=e=>{let t=e,s=t.getParent();for(;s!==void 0&&r.isBinaryExpression(s)&&s.getOperatorToken().getKind()===d.PlusToken;)t=s,s=t.getParent();return t!==e&&_e(t)!==void 0},lf=e=>{const t=e.getParent();if(t!==void 0){if(r.isVariableDeclaration(t)||r.isPropertyAssignment(t)||r.isPropertySignature(t))return A(t);if(r.isBinaryExpression(t)&&t.getOperatorToken().getKind()===d.EqualsToken)return t.getLeft().getText()}},df=(e,t,s)=>yr(e)?!qi(s)&&br(lf(t)):!0,uf=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(d.BinaryExpression),...e.getDescendantsOfKind(d.StringLiteral),...e.getDescendantsOfKind(d.NoSubstitutionTemplateLiteral)],i=new Set;for(const o of n){if(cf(o))continue;const a=_e(o);if(a===void 0)continue;const c=Sr(a);if(c===void 0||!df(c,o,t))continue;const l=o.getStartLineNumber(),u=`${String(l)}:${c}`;i.has(u)||(i.add(u),s.push({file:t,kind:c,line:l,preview:Ar(a)}))}return s},ff=(e,t)=>{const s=[];for(const n of S(t,{includeSkipped:!0})){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...uf(i,I(t,n)))}return s},gf=(e,t)=>{if(!r.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&r.isCallExpression(s)?Y(s):void 0;if(!n)return[];const i=[];for(const o of e.getDescendantsOfKind(d.CallExpression)){const a=En(o);if(a===void 0)continue;const c=C(a.options,"includeDeleted");if(c===void 0)continue;const l=r.isTrueLiteral(c),u=!l&&j(c);!l&&!u||i.push({exportName:V(e)??e.getName(),file:t,fromArgs:u,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},pf=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),o=I(t,n);for(const a of G(i))s.push(...gf(a,o))}return s},mf=new Set(["query","unsafe"]),hf=e=>!r.isPropertyAccessExpression(e)||!mf.has(e.getName())?!1:W(e.getExpression(),["sql"]),vf=e=>r.isBinaryExpression(e)||r.isTemplateExpression(e),Ef=(e,t)=>{if(!hf(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!vf(s)))return{file:t,line:s.getStartLineNumber(),scope:E(e)}},xf=(e,t)=>T(e,t,Ef),Sf=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Af=e=>{for(const[t,s]of Sf)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},yf=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getImportDeclarations()){const a=o.getModuleSpecifierValue(),c=Af(a);c!==void 0&&s.push({file:I(t,n),line:o.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},bf=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Nf=(e,t,s=[])=>{const n=qe(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:bf,requireUnmodifiedReach:!0});return kt(n,s)},wf=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Pf=e=>e&&r.isNumericLiteral(e)?Number(e.getText()):void 0,If=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!r.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(r.isSpreadAssignment(i)){n=!0;continue}if(r.isPropertyAssignment(i)){const o=A(i);t.push(o),o==="expiresInSeconds"&&(s=Pf(i.getInitializer()));continue}(r.isShorthandPropertyAssignment(i)||r.isMethodDeclaration(i))&&t.push(A(i))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Cf=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName(),s=wf.get(t);return s===void 0?void 0:fn(e.getExpression(),i=>i==="ctx.storage"||i.startsWith("ctx.storage."))?{method:t,optionsIndex:s}:void 0},Tf=(e,t)=>{const s=Cf(e.getExpression());if(s!==void 0)return{scope:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...If(e.getArguments()[s.optionsIndex])}},Of=(e,t)=>T(e,t,Tf),kf=e=>r.isDoStatement(e)||r.isForInStatement(e)||r.isForOfStatement(e)||r.isForStatement(e)||r.isWhileStatement(e),ei=e=>{const t=e.getLabel()?.getText(),s=i=>t!==void 0?r.isLabeledStatement(i)&&i.getLabel().getText()===t:kf(i)||r.isBreakStatement(e)&&r.isSwitchStatement(i);let n=e.getFirstAncestor(i=>Z(i)||s(i));if(!(n===void 0||Z(n))){for(;r.isContinueStatement(e)&&r.isLabeledStatement(n);)n=n.getStatement();return n}},Bt=(e,t)=>y(e.getFirstAncestor(s=>y(s,t)||Z(s)),t),Rf=(e,t)=>y(e,t)||e.getFirstAncestor(s=>y(s,t))!==void 0,ti=(e,t)=>{if(r.isReturnStatement(e)||r.isThrowStatement(e))return y(e,t)||Bt(e,t);if(r.isBreakStatement(e)||r.isContinueStatement(e)){const s=ei(e);return s!==void 0&&!Rf(s,t)}return!1},si=e=>[...r.isBreakStatement(e)||r.isContinueStatement(e)||r.isReturnStatement(e)||r.isThrowStatement(e)?[e]:[],...e.getDescendantsOfKind(d.BreakStatement),...e.getDescendantsOfKind(d.ContinueStatement),...e.getDescendantsOfKind(d.ReturnStatement),...e.getDescendantsOfKind(d.ThrowStatement)],Ff=e=>si(e).some(t=>ti(t,e)),Lf=e=>{const t=r.isCallExpression(e)?e.getExpression():void 0;return r.isPropertyAccessExpression(t)&&t.getName()==="throwIfAborted"},Df=e=>si(e).some(t=>ti(t,e)||r.isBreakStatement(t)&&y(ei(t),e))||e.getDescendantsOfKind(d.CallExpression).some(t=>Lf(t)&&Bt(t,e)),Mf=e=>e.getDescendantsOfKind(d.YieldExpression).some(t=>Bt(t,e)),_f=e=>r.isDoStatement(e)||r.isWhileStatement(e)?e.getExpression():e.getCondition(),Kf=e=>r.isDoStatement(e)?"do":r.isWhileStatement(e)?"while":"for",dt=(e,t)=>{const s=_f(e);if(!(s===void 0||r.isTrueLiteral(h(s)))||Df(e)||Mf(e))return;const i=E(e);if(!(i.kind==="module"&&e.getFirstAncestor(Z)!==void 0))return{file:t,kind:Kf(e),line:e.getStartLineNumber(),scope:i}},Bf=(e,t)=>[...X(e,t,d.WhileStatement,dt),...X(e,t,d.ForStatement,dt),...X(e,t,d.DoStatement,dt)].toSorted((s,n)=>s.file.localeCompare(n.file)||s.line-n.line),zf=new Set(["when","where"]),ut=new Set(["definePolicy","defineShape"]),$f=e=>{if(!r.isCallExpression(e))return;const t=e.getExpression();if(r.isPropertyAccessExpression(t)){const n=t.getName();return ut.has(n)?n:void 0}if(!r.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(r.isImportSpecifier(n)){const i=n.getNameNode().getText();return ut.has(i)?i:void 0}const s=t.getText();return ut.has(s)?s:void 0},Vf=e=>r.isObjectLiteralExpression(e)&&e.getProperties().length===0,ni=e=>{if(e!==void 0){if(r.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===d.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Vf(e))return"empty-object";if(r.isParenthesizedExpression(e))return ni(e.getExpression())}},zt=e=>e.getAncestors().find(t=>r.isArrowFunction(t)||r.isFunctionExpression(t)||r.isFunctionDeclaration(t)),Uf=e=>e.getDescendantsOfKind(d.ReturnStatement).filter(t=>zt(t)===e),ii=e=>e.getDescendantsOfKind(d.ConditionalExpression).filter(t=>zt(t)===e),qf=e=>{const t=Uf(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(d.IfStatement)!==void 0)||ii(e).length>0},Wf=e=>e.getDescendantsOfKind(d.IfStatement).filter(t=>zt(t)===e),Ct=e=>e.getKind()===d.NullKeyword||e.getKind()===d.FalseKeyword||r.isIdentifier(e)&&e.getText()==="undefined"?!0:r.isNumericLiteral(e)?e.getLiteralValue()===0:r.isStringLiteral(e)&&e.getLiteralValue()==="",Hf=(e,t)=>Ct(e)||Ct(t),jf=new Map([[d.EqualsEqualsEqualsToken,"positive"],[d.EqualsEqualsToken,"positive"],[d.ExclamationEqualsEqualsToken,"negative"],[d.ExclamationEqualsToken,"negative"]]),Vs=e=>!Ct(e)&&(r.isLiteralExpression(e)||e.getKind()===d.TrueKeyword),Gf=(e,t,s)=>{const n=jf.get(e);if(n!==void 0)return Hf(t,s)?n==="positive"?"negative":"positive":Vs(t)||Vs(s)?void 0:n},me=e=>{if(r.isParenthesizedExpression(e))return me(e.getExpression());if(r.isPrefixUnaryExpression(e)&&e.getOperatorToken()===d.ExclamationToken)return"negative";if(r.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Gf(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===d.AmpersandAmpersandToken||t===d.BarBarToken){const n=me(e.getLeft()),i=me(e.getRight());return n===i?n:"indeterminate"}}return r.isIdentifier(e)||r.isPropertyAccessExpression(e)||r.isElementAccessExpression(e)||r.isCallExpression(e)?"positive":"indeterminate"},Us=e=>{if(e!==void 0){if(r.isReturnStatement(e))return e;if(r.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&r.isReturnStatement(t)?t:void 0}}},Yf=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(d.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Qf=e=>r.isReturnStatement(e)?e.getExpression()??e:e,Xf=e=>{const t=[];for(const s of ii(e)){const n=me(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Wf(e)){const n=me(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Us(s.getThenStatement()):Us(s.getElseStatement())??Yf(s);i!==void 0&&t.push(Qf(i))}return t},Jf=e=>{for(const t of e.getAncestors())if(r.isVariableDeclaration(t)){const s=t.getNameNode();if(r.isIdentifier(s))return s.getText()}return"<anonymous>"},Zf=(e,t,s)=>{if(!r.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!r.isObjectLiteralExpression(n))return[];const i=[];for(const o of n.getProperties()){if(!r.isPropertyAssignment(o)||!zf.has(A(o)))continue;const a=o.getInitializer();if(!(!a||!(r.isArrowFunction(a)||r.isFunctionExpression(a)))&&qf(a))for(const c of Xf(a)){const l=ni(c);l!==void 0&&i.push({exportName:Jf(e),file:s,form:l,key:A(o),line:c.getStartLineNumber(),owner:t})}}return i},eg=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(d.CallExpression)){const i=$f(n);i!==void 0&&s.push(...Zf(n,i,t))}return s},tg=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...eg(i,I(t,n)))}return s},sg=new Set(["query","upsert","upsertNow"]),ng=e=>{if(!r.isPropertyAccessExpression(e))return;const t=e.getName();if(sg.has(t))return W(e.getExpression(),["vectors"])?t:void 0},ig=(e,t)=>{const s=ng(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=C(n,"namespace");if(!(!i||!j(i)||te(i)))return{scope:E(e),file:t,line:e.getStartLineNumber(),method:s}},rg=(e,t)=>T(e,t,ig),og=(e,t,s)=>{const{callSites:n,containers:i,crons:o,functions:a,modules:c,mutators:l,queues:u,schema:f,shapes:g,wranglerVariables:p,workflows:x}=s;return _i({adminRoutes:Uo(e,t),aiRawRuns:Jo(e,t),aiToolSideEffects:la(e,t),argumentDerivedFetches:fa(e,t),argumentValidators:Oa(e,t),authApiCalls:ar(e,t),authConfigs:za(e,t),browserUrlAccesses:qa(e,t),callEdges:n.callEdges,configCalls:Ja(e,t),containerKeyAccesses:ec(e,t),containerOverrides:oc(e,t),containers:i,cronTargets:o.flatMap(k=>k.functionPath===void 0?[]:[k.functionPath]),exportSinks:dc(e,t),staleMigrationImports:yf(e,t),failOpenGuards:mc(e,t),flagReads:Sc(e,t),flagSecurityDefaults:Nc(e,t),geoIndexUsages:Ic(e,t),httpActionGuards:Bc(e,t),httpHeaderWrites:Yc(e,t),hyperdriveCalls:cr(e,t),identityClaimReads:ol(e,t),imageDeliveryUrlAccesses:cl(e,t),inserts:n.inserts,kvKeyAccesses:dl(e,t,a),mailRecipientAccesses:ml(e,t),maskProcedures:lr(e,t),maskStrategies:El(e,t),mutatorWrites:Nl(e,t),nondeterministicCalls:pr(e,t),normalizeIdAuthorizations:Bl(e,t),notifyCalls:hr(e,t),notifyConfig:mr(e,t),mutators:l,ownerFieldWrites:Ld(e,t,a,l),unrestrictedWhereBranches:tg(e,t),paymentWebhooks:Bd(e,t),privilegedDispatches:Qd(e,t),procedureProtections:Fu(e,t),queries:n.queries,queues:u,r2sqlCalls:vr(e,t),ratelimitKeySelectors:zu(e,t),rawRowReturns:ju(e,t),relationLoads:Qu(e,t),rlsProcedures:Er(e,t),schema:f,secretLiterals:ff(e,t),modules:c,shapes:g,softDeleteReads:pf(e,t),sqlInterpolations:xf(e,t),storageKeyAccesses:Nf(e,t,a),storageUploads:Of(e,t),tableWrites:n.tableWrites,rowEffects:af(e,t,n.tableWrites,n.callEdges),unboundedLoops:Bf(e,t),vectorNamespaceAccesses:rg(e,t),workflowCalls:n.workflowCalls,workflows:x,wranglerVariables:p})},ag=e=>({cacheKey:`advisor_accept_unused:${e.rule}:${e.file}:${e.exportName}`,categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` accepts a finding the advisor does not report as an error.",detail:`No ERROR \`${e.rule}\` in \`${e.file}\` for \`${e.exportName}\` — the acceptance no longer applies.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,file:e.file,rule:e.rule},name:"advisor_accept_unused",remediation:"Remove the entry, or correct the rule, file and export name it names.",title:"An accepted advisor finding matches no error"}),cg=(e,t)=>{const s=new Set;return[...e.map(i=>{if(i.level!=="ERROR")return i;const o=t.find(a=>a.rule===i.name&&a.file===i.metadata.file&&a.exportName===i.metadata.exportName);return o===void 0?i:(s.add(o),{...i,detail:`Accepted: ${o.reason}. ${i.detail}`,level:"INFO",metadata:{...i.metadata,accepted:o.reason}})}),...t.filter(i=>!s.has(i)).map(i=>ag(i))]},lg=()=>({cacheKey:"advisor_accept_invalid",categories:["SCHEMA"],description:"`advisor.accept` in `lunora.config.*` is read by parsing the file, so every entry must be a literal.",detail:"`advisor.accept` is not an array of literal `{ rule, file, exportName, reason }` objects with non-empty strings, so codegen ignored all of it and every ERROR still fails the gate.",facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_accept_invalid",remediation:'Write `advisor: { accept: [{ rule: "owner_field_from_args_not_auth", file: "lunora/auth/team.ts", exportName: "addTeamMember", reason: "…" }] }` as literals on the config\'s default export.',title:"`advisor.accept` is not a list codegen can read, so no acceptance applies"}),dg=e=>e.metadata.accepted!==void 0||e.name==="advisor_accept_unused"||e.name==="advisor_accept_invalid",qs={error:"ERROR",info:"INFO",warn:"WARN"},Ws={ERROR:2,INFO:0,WARN:1},ug=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"}),fg=(e,t)=>{const{advisor:s}=hn(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,i=n!==void 0&&Object.hasOwn(qs,n)?qs[n]:void 0;return i===void 0?[...t,ug(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(o=>dg(o)||Ws[o.level]>=Ws[i])},gg=(e,t)=>{const{advisor:s}=hn(e),n=cg(t,s?.accept??[]);return fg(e,s?.acceptUnreadable===!0?[...n,lg()]:n)},pg={call:"function",enqueue:"queue",invoke:"service",publish:"topic",schedule:"function"},mg="crons",hg=Pr.replace(/\.ts$/u,""),ae=(e,t)=>`${Lt(e)}:${t}`,ft=(e,t,s)=>t===""?{reason:`the ${s} is not a string literal`}:{to:`${e}:${t}`},vg=e=>[...e.callEdges.map(t=>{const s=t.target===void 0?{reason:t.reason??"unreadable target"}:{to:`${pg[t.kind]}:${t.target}`};return{file:t.file,kind:t.kind,line:t.line,scope:t.scope,...s}}),...e.queries.map(t=>({file:t.file,kind:"read",line:t.line,scope:t.scope,...ft("table",t.table,"table name")})),...[...e.inserts,...e.tableWrites].map(t=>({file:t.file,kind:"write",line:t.line,scope:t.scope,...ft("table",t.table,"written table")})),...e.workflowCalls.map(t=>({file:t.file,kind:"start",line:t.line,scope:t.scope,...ft("workflow",t.workflow,"workflow name")}))],Eg=e=>e.untracked===!0?"inside a helper only code outside any export calls":"inside a non-exported helper",xg=e=>{const{scope:t}=e;switch(t.kind){case"export":return[{...e,exportName:t.name}];case"helper":return t.callers.length===0?[{...e,unattributed:Eg(t)}]:t.callers.map(s=>({...e,exportName:s}));default:return[{...e,unattributed:"at module scope"}]}},Sg=e=>vg(e).flatMap(t=>xg(t)),Ag=e=>[...e.queues.flatMap(t=>t.topic===void 0?[]:[{file:t.filePath,from:`topic:${t.topic}`,kind:"subscribe",line:0,to:`queue:${t.exportName}`}]),...e.crons.map(t=>{const s=t.workflow===void 0?void 0:`workflow:${t.workflow.exportName}`,n=t.functionPath===void 0?void 0:`function:${t.functionPath}`,i=s??n;return{file:mg,from:`cron:${t.name}`,kind:"trigger",line:0,...i===void 0?{reason:"the cron has no target"}:{to:i}}})],yg=e=>new Map(e.flatMap(t=>t.tables.map(s=>[s,t.name]))),fe=(e,t)=>t===void 0?e:{...e,module:t},bg=e=>{const t=new Map,s=new Map,n=yg(e.modules),i=(c,l)=>{s.set(c,[...s.get(c)??[],l])},o=(c,l)=>{t.set(c.id,c),l!==void 0&&i(l,c.id)},a=(c,l)=>{c!==void 0&&i(ae(c.file,c.exportName),l)};for(const c of e.functions){const l=ae(c.filePath,c.exportName),u=[...xr(c.filePath),c.exportName].join(".");o(fe({detail:c.kind,id:`function:${l}`,kind:"function",name:u},Ie(e.modules,c.filePath)),l)}for(const c of e.httpRoutes){const l=ae(c.filePath,c.exportName);o(fe({id:`http:${l}`,kind:"http",name:`${c.method} ${c.path}`},Ie(e.modules,c.filePath)),l)}for(const c of e.schema.tables)o(fe({id:`table:${c.name}`,kind:"table",name:c.name},n.get(c.name)));for(const c of e.queues){const l=c.topic===void 0?{}:{detail:"subscription"};o(fe({...l,id:`queue:${c.exportName}`,kind:"queue",name:c.exportName},Ie(e.modules,c.filePath)),ae(c.filePath,c.exportName)),a(c.handlerSite,`queue:${c.exportName}`)}for(const c of e.topics)o(fe({id:`topic:${c.exportName}`,kind:"topic",name:c.exportName},Ie(e.modules,c.filePath)));for(const c of e.workflows)o({id:`workflow:${c.exportName}`,kind:"workflow",name:c.exportName},ae(hg,c.exportName)),a(c.handlerSite,`workflow:${c.exportName}`);for(const c of e.crons)o({detail:c.cron,id:`cron:${c.name}`,kind:"cron",name:c.name});for(const c of e.services){const l=c.rpcEntrypoint===void 0?"fetch":"rpc";o({detail:c.entrypoint===void 0?l:`${l} · ${c.entrypoint}`,id:`service:${c.name}`,kind:"service",name:c.worker})}return{nodes:t,sites:s}},Ng=e=>e==="default"?"the default export is not a registered function":`"${e}" is not a registered function`,wg=(e,t)=>"from"in e?[e.from]:"unattributed"in e?{reason:e.unattributed}:t.get(ae(e.file,e.exportName))??{reason:Ng(e.exportName)},Pg=(e,t,s)=>{if("reason"in e)return{reason:e.reason};const n=wg(e,t);if("reason"in n)return n;const{to:i}=e;return s.has(i)?{drawn:n.map(o=>({from:o,kind:e.kind,to:i}))}:{reason:`${i} is not declared`}},gt=e=>`${e.from}|${e.kind}|${e.to}`,Ig=e=>`${e.file}|${String(e.line)}|${e.kind}|${e.reason}`,Cg=e=>{const{nodes:t,sites:s}=bg(e),n=new Map,i=new Map;for(const o of[...Ag(e),...Sg(e)]){const a=Pg(o,s,t);if("drawn"in a)for(const c of a.drawn)n.set(gt(c),c);else{const c={file:o.file,kind:o.kind,line:o.line,reason:a.reason};i.set(Ig(c),c)}}return{edges:[...n.values()].toSorted((o,a)=>gt(o).localeCompare(gt(a))),nodes:[...t.values()].toSorted((o,a)=>o.id.localeCompare(a.id)),modules:e.modules.map(o=>({...o.description===void 0?{}:{description:o.description},...o.installed===!0?{installed:!0}:{},...o.ownsFolder===!1?{ownsFolder:!1}:{},name:o.name,tables:[...o.tables]})),unresolved:[...i.values()].toSorted((o,a)=>o.file.localeCompare(a.file)||o.line-a.line),version:1}},Tg=e=>`${Tr}export const architecture = ${Cr(e,"Record<string, unknown>")};
4
- `,Hs=(e,t="api")=>{const s=new Map;for(const n of e){const i=Lt(n),o=s.get(i);if(o===void 0){s.set(i,n);continue}if(o!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new q("INTERNAL",`@lunora/codegen: "${o}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Og=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:o}=t,a=[];e.tables.some(c=>xn(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=>Sn(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of o===void 0?[]:kr)c.requiredPackage!==void 0&&o?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,l)=>a.findIndex(u=>u.name===c.name)===l)},kg=(e,t,s={})=>{if(t===void 0)return;const n=Og(e,s).filter(o=>!t.has(o.name));if(n.length===0)return;const i=n.map(o=>` - ${o.name} — ${o.reason}`).join(`
5
- `);throw new q("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
6
- ${i}
7
-
8
- Install them with your package manager, then re-run codegen.`)},Rg="env.ts",Fg=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(r.isImportSpecifier(s))return Ve(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Lg=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!r.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(d.ImportDeclaration);return n!==void 0&&Ve(n.getModuleSpecifierValue())}return!1},Dg=e=>{if(r.isIdentifier(e))return Fg(e);if(r.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&r.isIdentifier(t)&&Lg(t)}return!1},Mg=e=>{const t=[];for(const s of e.getVariableDeclarations()){const n=s.getInitializer();if(n?.getKind()!==d.CallExpression||!Dg(n.getExpression()))continue;const o=s.getNameNode();if(!r.isIdentifier(o)){if(s.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw xe(o,"defineEnv exports must be plain named exports (no destructuring)")}const a=un(s,"member");a!==void 0&&t.push({exportName:a})}return t},_g=(e,t)=>{const s=v(t,Rg);if(!F(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Mg(n);if(i.length!==0){if(i.length>1)throw xe(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Kg=new Set(["allowedHosts","deniedHosts","interceptHttps"]),Bg=(e,t)=>{const s=h(t);if(s===void 0||!r.isIdentifier(s))return s;const n=s.getText();return h(e.getDescendantsOfKind(d.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},zg=(e,t)=>e!==void 0&&r.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(r.isShorthandPropertyAssignment(s))return t.has(A(s));if(!r.isPropertyAssignment(s)||!t.has(A(s)))return!1;const n=h(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),$g=new Set(["durable"]),Vg=new Set(["rollback"]),Ug=e=>{const t=e.getExpression();return r.isPropertyAccessExpression(t)?t.getName():t.getText()},qg=new Map([["defineContainer",{keys:Kg,signal:"containerEgressPolicy"}],["defineStep",{keys:Vg,signal:"workflowRollback"}],["stream",{keys:$g,signal:"durableStreams"}]]),Wg=(e,t)=>{const s=qg.get(Ug(t));if(s!==void 0)return t.getArguments().some(n=>zg(Bg(e,n),s.keys))?s.signal:void 0},Hg=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Mr(i).has("secrets"));for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=Wg(i,o);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},jg="createWorker",Gg="extend",js=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,Gs=e=>{const t=[],s=js(C(e,"backupCron"));s!==void 0&&t.push(s);const n=C(e,"crons");if(n===void 0||!r.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isMethodDeclaration(i))continue;const o=js(i.getNameNode());o!==void 0&&t.push(o)}return t},Yg=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===jg)return r.isObjectLiteralExpression(s)?Gs(s):[];if(t!==Gg||!(r.isArrowFunction(s)||r.isFunctionExpression(s)))return[];const n=rn(s.getBody());return n===void 0?[]:Gs(n)},Qg=(e,t)=>{const s=[];for(const{filePath:n}of Be(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression))s.push(...Yg(o))}return[...new Set(s)]},ri=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:ri(e.inner)},Xg=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=ri(n);return i!==void 0&&t.has(i)}))},Jg=(e,t)=>{const s=new Map,n=new Map;for(const i of e)s.set(i.name,`workflow "${i.exportName}"`),n.set(i.className,`workflow "${i.exportName}"`);for(const i of t){const o=s.get(i.name);if(o!==void 0)throw new q("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${i.name}": produced by both ${o} and agent "${i.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(i.className);if(a!==void 0)throw new q("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${i.className}": produced by both ${a} and agent "${i.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Zg=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,o=el(s,t),a=_g(s,t),c=Ir(s,t),{queues:l,topics:u}=Kr(s,t),f=zr(n),g=Fr(s,t);Jg(c,g);const p=Lr(s,t),x=$r(s,t),k=Dr(s,t,c,g),Q=Qg(s,t),L=Hg(s,t),N=Br(s,t),B=_r(s,t);B.browser=B.browser||N.usesSandboxBrowser;const M=Vr(B,yn(n,e.target),{agents:g.length>0,commitOrderedTables:i.tables.some(R=>R.commitOrdered===!0),cronTriggers:k.length>0,crossShardFanout:i.tables.some(R=>Wr(R)),containerEgressPolicy:L.containerEgressPolicy,containerRuntimeScheduling:p.some(R=>R.schedulingPolicy==="durable_object"),containerSandboxTools:p.some(R=>R.sandbox===!0),durableStreams:L.durableStreams,globalTables:i.tables.some(R=>R.shardMode==="global"),queues:l.length>0,relationGraph:Xg(i),secrets:L.secrets,services:f.length>0,topics:u.length>0,vectorStore:i.vectorIndexes.length>0,workerLoaders:N.usesSandboxLoader,workflowRollback:L.workflowRollback,workflowSchedules:c.some(R=>R.schedules!==void 0)}),w=M.usage,se=Rr(w),ne=M.signals.vectorStore!==!1,le=M.signals.services===!1?[]:f,ie=An(n),Se=ie??new Set,U=Se.has("lunorash");kg(i,ie,{hasVectors:ne,scheduler:w.scheduler||k.length>0,storage:w.storage||x.rules.length>0||Object.keys(bn(i)).length>0,usage:w});const _=F(v(t,"flags.ts")),K=F(v(t,"notify.ts"));return{agents:g,capabilities:se,containers:p,crons:k,dataModelContent:Yr(i),declaredDependencies:ie,dependencies:Se,entryCronTriggers:Q,env:a,featureUsage:w,hasFlags:_,hasNotify:K,identity:o,platformGate:{...M,diagnostics:[...Ur(n,e.target),...M.diagnostics]},queues:l,serverContent:jr({agents:g,capabilities:se,containers:p,env:a,hasVectors:ne,hasFlags:_,hasNotify:K,identity:o,queues:l,schema:i,services:le,storageRuleBuckets:x.rules.map(R=>R.bucket),topics:u,useUmbrella:U,workflows:c}),services:le,storageRulesMetadata:x,topics:u,usesSandbox:N.usesSandboxBrowser||N.usesSandboxContainer||N.usesSandboxFs,useUmbrella:U,workflows:c}},oi=(e,t)=>{if(!r.isPropertyAccessExpression(e))return;const s=e.getExpression();if(!r.isPropertyAccessExpression(s))return;const n=s.getExpression();return r.isPropertyAccessExpression(n)&&n.getName()===t?s.getName():void 0},ep=e=>{if(!r.isPropertyAccessExpression(e))return!1;const t=e.getExpression();return r.isPropertyAccessExpression(t)&&t.getName()==="scheduler"||r.isIdentifier(t)&&t.getText()==="scheduler"},tp=new Map([["publish",{kind:"publish",surface:"topics"}],["publishBatch",{kind:"publish",surface:"topics"}],["send",{kind:"enqueue",surface:"queues"}],["sendBatch",{kind:"enqueue",surface:"queues"}]]),sp=/^[\w$]+:[\w$]+$/u,np=(e,t)=>{const s=dn(t);return s!==void 0?{kind:"call",target:s}:e!=="run"&&t!==void 0?{kind:"call",reason:'the function reference is not a static api.* / internal.* chain or a "namespace:export" key'}:void 0},Ys=e=>{const t=[];for(const s of e.getProperties()){if(!r.isPropertyAssignment(s)&&!r.isShorthandPropertyAssignment(s))return;t.push(s.getName())}return t},ip=e=>{if(e===void 0)return[];if(r.isObjectLiteralExpression(e))return Ys(e);if(r.isIdentifier(e)){const t=e.getSymbol()?.getDeclarations()[0];if(r.isVariableDeclaration(t)&&t.getVariableStatement()?.getDeclarationKind()===Bi.Const){const s=t.getInitializer();return r.isObjectLiteralExpression(s)?Ys(s):void 0}}},rp=(e,t,s)=>({schedule:{argKeys:ip(s),...e==="runAfter"&&t!==void 0&&r.isNumericLiteral(t)?{delayMs:t.getLiteralValue()}:{}}}),op=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),[n,i,o]=e.getArguments();if(ln.has(s))return np(s,n);if((s==="runAfter"||s==="runAt")&&ep(t)){const l=dn(i)??(r.isStringLiteral(i)&&sp.test(i.getLiteralText())?i.getLiteralText():void 0);return l===void 0?{kind:"schedule",reason:'the scheduled function is not a static api.* / internal.* chain or a "namespace:export" key'}:{kind:"schedule",target:l,...rp(s,n,o)}}const a=tp.get(s),c=a===void 0?void 0:oi(t,a.surface);return a===void 0||c===void 0?void 0:{kind:a.kind,target:c}},ap=new Set([d.AmpersandAmpersandEqualsToken,d.AmpersandAmpersandToken,d.BarBarEqualsToken,d.BarBarToken,d.QuestionQuestionEqualsToken,d.QuestionQuestionToken]),ai=e=>Ki.isOptionalChain(e.compilerNode),cp=(e,t)=>r.isIfStatement(t)?!y(e,t.getExpression()):r.isWhileStatement(t)||r.isForInStatement(t)||r.isForOfStatement(t)?y(e,t.getStatement()):r.isForStatement(t)?y(e,t.getStatement())||y(t.getIncrementor(),e):r.isCaseClause(t)||r.isDefaultClause(t)||r.isCatchClause(t)?!0:Z(t)?t.getFirstAncestor(Z)!==void 0:r.isConditionalExpression(t)?!y(e,t.getCondition()):r.isBinaryExpression(t)?!y(e,t.getLeft())&&ap.has(t.getOperatorToken().getKind()):(r.isCallExpression(t)||r.isElementAccessExpression(t))&&ai(t)?!y(e,t.getExpression()):r.isBlock(t)&&t.getStatements().some(s=>s.getEnd()<=e.getStart()&&Ff(s)),lp=e=>{let t=e,s=e.getParent();for(;s!==void 0&&(r.isAwaitExpression(s)||r.isParenthesizedExpression(s));)t=s,s=s.getParent();const n=r.isVariableDeclaration(s)||r.isBinaryExpression(s)&&y(t,s.getRight())&&s.getOperatorToken().getKind()===d.EqualsToken,i=e.getFirstAncestor(Z);return n||i?.getDescendantsOfKind(d.ThrowStatement).some(o=>o.getStart()>=e.getEnd()&&y(o.getFirstAncestor(Z),i))===!0},dp=(e,t)=>{if(ai(e)||t==="schedule"&&lp(e))return!0;let s=e;for(let n=s.getParent();n!==void 0&&!r.isSourceFile(n);n=n.getParent()){if(cp(s,n))return!0;s=n}return!1},Qs=(e,t,s)=>s===void 0?void 0:{...s,...dp(e,s.kind)?{conditional:!0}:{},file:t,line:e.getStartLineNumber(),scope:E(e)},up=(e,t)=>[...T(e,t,(s,n)=>Qs(s,n,op(s))),...X(e,t,d.PropertyAccessExpression,(s,n)=>{const i=oi(s,"services");return Qs(s,n,i===void 0?void 0:{kind:"invoke",target:i})})],fp=new Set(["boolean","number","object","string"]),gp=e=>{const t=e.getName();if(!fp.has(t))return;const s=e.getExpression();return W(s,["flags"])||W(s,["flags","details"])?t:void 0},pp=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=gp(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(r.isStringLiteral(n)||r.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},mp=(e,t)=>{const s=new Map;for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const o of i.getDescendantsOfKind(d.CallExpression)){const a=pp(o);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},hp=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),o=i.getText(e);if(!o||o==="any"||o==="never"||Qr(o))return;const a=e.getSourceFile().getFilePath();if(Xr(i,e,a)){const c=Jr(i,e,a,0,new Set);return c===void 0&&Zr(o),c}return o},vp=e=>e.getProperties().some(t=>{if(r.isSpreadAssignment(t))return!0;const s=nr(t.getNameNode());return s===void 0||s==="namespace"}),Ep=(e,t)=>{for(const{filePath:s}of Be(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(d.CallExpression)){const o=i.getExpression(),[a]=i.getArguments();if(!(!r.isPropertyAccessExpression(o)||o.getName()!=="auth"||a===void 0)&&(!r.isObjectLiteralExpression(a)||vp(a)))return i}}},xp="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",Sp=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw xe(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${xp}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},Ap=e=>r.isPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?r.isComputedPropertyName(e.getNameNode()):!1,yp=e=>r.isPropertyAssignment(e)||r.isShorthandPropertyAssignment(e)||r.isMethodDeclaration(e)||r.isGetAccessorDeclaration(e)?Ap(e):!0,ci=(e,t=!1)=>{for(const s of e.getProperties()){if(yp(s))return!0;if(t)continue;if(!r.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!r.isObjectLiteralExpression(n)||ci(n,!0))return!0}return!1},bp=(e,t)=>{for(const s of S(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Nn(n))for(const o of Ft(i)){const a=o.getArguments()[0];if(a!==void 0&&(!r.isObjectLiteralExpression(a)||ci(a)))return!0}}return!1},Np=e=>{const t=e.getArguments()[0];if(!t||!r.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Fe(n);if(i===void 0||!r.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!(!o||!r.isObjectLiteralExpression(o)))for(const a of o.getProperties()){const c=Fe(a);c!==void 0&&s.push({column:c,strategy:vn(a),table:i})}}return s},wp=(e,t)=>{const s=new Map;for(const n of S(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:o}of Nn(i))for(const a of Ft(o))for(const c of Np(a)){const l=`${c.table}\0${c.column}`;s.has(l)||s.set(l,c)}}return{columns:[...s.values()]}},Pp=["providerSubscriptionId","state"],Ip=["providerEventId","processedAt"],Xs=(e,t)=>t.every(s=>s in e.shape),Cp=e=>{const t=e.find(n=>n.name==="payment_subscriptions"),s=e.find(n=>n.name==="payment_events");return t!==void 0&&s!==void 0&&Xs(t,Pp)&&Xs(s,Ip)},Tp=["account","apikey","member","passkey","session","teamMember","twoFactor","user"],Op=(e,t)=>{const s={};for(const[n,i]of e)s[n]={dataset:i};for(const[n,i]of t)s[n]={excluded:i};return s},kp=(e,t)=>{const s=[];for(const n of e){const i=t[n];i===void 0?s.push({code:"unclassified",table:n}):"excluded"in i&&i.excluded.trim()===""&&s.push({code:"excluded_without_reason",table:n})}return s},Rp="@lunora/privacy",li="userId",Fp=e=>e.replaceAll("\\","/"),Lp="privacy",Dp=new Set(["actionCacheDataset","authDataset","documentHistoryDataset"]),We=e=>e!==void 0&&(r.isStringLiteral(e)||r.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():void 0,He=e=>r.isPropertyAssignment(e)?e.getName().replaceAll(/^["']|["']$/gu,""):"",$t=e=>e.getProperties().filter(t=>r.isPropertyAssignment(t)),Mp=(e,t)=>{const s=e.getProperty(t),n=r.isPropertyAssignment(s)?s.getInitializer():void 0;return n!==void 0&&r.isObjectLiteralExpression(n)?n:void 0},je=e=>{const t=e.getExpression();return r.isIdentifier(t)?t.getText():void 0},_p=(e,t)=>{const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=Mp(s,"tables"),i=We(e.getArguments()[0])??"defineDataset";for(const o of n===void 0?[]:$t(n).map(a=>He(a)))t.datasets.set(o,i)},Kp=(e,t)=>{const s=e.getArguments()[0],n=s!==void 0&&r.isObjectLiteralExpression(s)?$t(s):[],i=new Set(n.map(o=>He(o)));for(const o of Tp)i.has(o)||t.datasets.set(o,"authDataset");for(const o of n){const a=r.isPropertyAssignment(o)?We(o.getInitializer()):void 0;a!==void 0&&t.datasets.set(a,"authDataset")}},Js=(e,t,s)=>{t.datasets.set(We(e.getArguments()[0])??s,s)},Vt=8,Ee=(e,t=0)=>{if(t>Vt)return;if(r.isAsExpression(e)||r.isSatisfiesExpression(e)||r.isParenthesizedExpression(e))return Ee(e.getExpression(),t+1);if(!r.isIdentifier(e))return e;const s=e.getSymbol(),n=(s?.isAlias()===!0?s.getAliasedSymbol():s)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return i===void 0?void 0:Ee(i,t+1)},Bp=e=>{if(r.isPropertyAssignment(e)){const t=e.getInitializer();return t===void 0?void 0:[He(e),t]}if(r.isShorthandPropertyAssignment(e)){const t=e.getValueSymbol(),s=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),n=r.isVariableDeclaration(s)?s.getInitializer():void 0;return[e.getName(),n??e.getNameNode()]}},di=(e,t=0)=>{const s=Ee(e,t);if(s===void 0||!r.isObjectLiteralExpression(s)||t>Vt)return;const n=new Map;for(const i of s.getProperties()){const o=r.isSpreadAssignment(i)?di(i.getExpression(),t+1):[Bp(i)];if(o===void 0)return;for(const a of o)a!==void 0&&n.set(a[0],a[1])}return n},zp=e=>{const t=e.getArguments()[0];return t===void 0?void 0:di(t)},$p=(e,t)=>{const s=e?.get("exclude"),n=s===void 0?void 0:Ee(s);for(const i of n!==void 0&&r.isObjectLiteralExpression(n)?$t(n):[])t.excluded.set(He(i),r.isPropertyAssignment(i)?We(i.getInitializer())??"":"")},Vp=(e,t)=>{switch(je(e)){case"actionCacheDataset":{Js(e,t,"actionCache");break}case"authDataset":{Kp(e,t);break}case"defineDataset":{_p(e,t);break}case"documentHistoryDataset":{Js(e,t,"documentHistory");break}}},Ut=e=>e!==void 0&&r.isCallExpression(e)&&je(e)==="defineDataset",ui=e=>e!==void 0&&r.isCallExpression(e)&&Dp.has(je(e)??""),Up=e=>{const t=e.getSymbol(),n=(t?.isAlias()===!0?t.getAliasedSymbol():t)?.getValueDeclaration(),i=r.isVariableDeclaration(n)?n.getInitializer():void 0;return r.isVariableDeclaration(n)&&(Ut(i)||ui(i))?n:void 0},fi=(e,t,s=0)=>{const n=Ee(e,s);if(n===void 0||!r.isArrayLiteralExpression(n)||s>Vt)return!1;for(const i of n.getElements())if(r.isSpreadElement(i)){if(!fi(i.getExpression(),t,s+1))return!1}else if(!Ut(i)&&!ui(i)){const o=r.isIdentifier(i)?Up(i):void 0;if(o===void 0)return!1;t.add(o)}return!0},qp=e=>{if(e===void 0)return;const t=e.get("datasets"),s=new Set;return t===void 0||fi(t,s)?s:void 0},Wp=(e,t)=>{const s=[];for(const i of e.getDescendantsOfKind(d.CallExpression))if(Vp(i,t),je(i)==="definePrivacy"){const o=zp(i);$p(o,t),s.push({location:`${e.getFilePath()}:${String(i.getStartLineNumber())}`,passed:qp(o)})}return{declared:e.getDescendantsOfKind(d.VariableDeclaration).filter(i=>Ut(i.getInitializer())).map(i=>({declaration:i,name:i.getName()})),privacyCalls:s}},Hp=(e,t)=>{const s=v(t,"schema.ts"),n=[...S(t),...F(s)?[s]:[]];for(const o of n)e.getSourceFile(o)===void 0&&e.addSourceFileAtPath(o);const i=new Set(n.map(o=>Fp(o)));return e.getSourceFiles().filter(o=>i.has(o.getFilePath()))},jp=(e,t,s)=>{if(s?.has(Rp)!==!0)return{classifications:{},enabled:!1,unusedDatasets:[]};const n={datasets:new Map,excluded:new Map},i=[],o=[];for(const f of Hp(e,t)){const g=Wp(f,n);i.push(...g.declared),o.push(...g.privacyCalls)}const a=new Set;for(const f of o){for(const g of f.passed??[])a.add(g);f.passed===void 0&&console.warn(`@lunora/codegen: privacy_datasets_unresolved: the definePrivacy call at ${f.location} passes datasets codegen cannot read, so a defineDataset it leaves out is not reported. Pass an array of dataset constants, directly or through a spread of a config object literal.`)}const l=o.every(f=>f.passed!==void 0)?i.filter(f=>!a.has(f.declaration)).map(f=>f.name):[];return{classifications:Op(n.datasets,n.excluded),enabled:o.length>0,unusedDatasets:l}},Gp=e=>e.extensionKey!==Lp&&li in e.shape,Yp=e=>e.code==="excluded_without_reason"?`privacy_exclusion_unexplained: "${e.table}" is excluded without a reason. Give one in definePrivacy({ exclude }).`:`privacy_table_unclassified: "${e.table}" holds user data (it has a "${li}" column) but no dataset exports it. Add it to a defineDataset, or exclude it in definePrivacy({ exclude }) with a reason.`,Qp=(e,t)=>{if(!t.enabled)return;const s=e.filter(o=>Gp(o)).map(o=>o.name),[n]=kp(s,t.classifications);if(n!==void 0)throw new q("PRIVACY_COVERAGE",Yp(n));const[i]=t.unusedDatasets;if(i!==void 0)throw new q("PRIVACY_COVERAGE",`privacy_dataset_unused: "${i}" is declared with defineDataset but never passed to definePrivacy({ datasets }). Pass it, or delete it.`)},Xp=(e,t)=>{const s=qr(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,privacy:t.dependencies.has("@lunora/privacy"),queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}},Jp=new Set(["delete","hardDelete","patch","replace","restore"]),Zp=new Set(["insertMany","insertManyUnsafe","patchIf","patchWhere"]),em=new Set(["delete","deleteMany","hardDelete","insert","insertMany","patch","patchMany","replace","restore","upsert","upsertMany"]),Zs=(e,t)=>{const s=e.getNonNullableType().getProperty("__table")?.getTypeAtLocation(t);if(s===void 0)return[];const n=s.isUnion()?s.getUnionTypes():[s],i=n.map(o=>o.getLiteralValue()).filter(o=>typeof o=="string");return i.length===n.length?i:[]},tm=(e,t)=>{const s=e.getType();if(t==="deleteMany"||t==="patchMany"){const n=s.getArrayElementType();if(n===void 0)return[];const i=t==="patchMany"?n.getProperty("id")?.getTypeAtLocation(e):n;return i===void 0?[]:Zs(i,e)}return Zs(s,e)},en="",sm=(e,t)=>{if(t!=="patch"&&t!=="patchMany")return;const s=e.getArguments()[1];if(s===void 0||!r.isObjectLiteralExpression(s))return;const n=[];for(const i of s.getProperties()){if(!r.isPropertyAssignment(i)&&!r.isShorthandPropertyAssignment(i))return;n.push(i.getName())}return n},nm=(e,t)=>{if(Zp.has(e))return{method:e,tables:[t!==void 0&&r.isStringLiteral(t)?t.getLiteralText():en]};if(Jp.has(e)||e==="deleteMany"||e==="patchMany"){const s=t===void 0?[]:tm(t,e);return{method:e,tables:s.length===0?[en]:s}}},tn=(e,t)=>e===void 0?void 0:{...e,fields:sm(t,e.method)},im=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression();if($(n))return tn(nm(s,e.getArguments()[0]),e);if(em.has(s)&&r.isPropertyAccessExpression(n)&&$(n.getExpression()))return tn({method:s,tables:[n.getName()]},e)},rm=(e,t)=>T(e,t,(s,n)=>{const i=im(s);if(i===void 0)return;const o=E(s),a=s.getStartLineNumber();return i.tables.map(c=>({...i.fields===void 0?{}:{fields:i.fields},file:n,line:a,method:i.method,scope:o,table:c}))}),om=(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"}),am=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!r.isObjectLiteralExpression(s)||D(s,"args")===void 0)return!1}return Mt(e,t).opaque},cm=(e,t)=>{const s=[],n=(i,o)=>{const a=i.getInitializer();if(a===void 0||!r.isCallExpression(a))return;const c=Y(a);c!==void 0&&am(a,c.receiver)&&s.push(om(t,o,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(o=>o.isExported()))for(const o of i.getDeclarations())n(o,o.getName());return s},lm=(e,t)=>{const s=[];for(const n of S(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...cm(i,I(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},dm=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["SubscriptionDefinition",{call:"defineSubscription(topic, { … })",file:"queues",note:"A dropped subscription is never published to — its topic's messages simply never reach it."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ke=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),gi=e=>!e.isAny(),pi=e=>{const t=e.getType();if(!gi(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:dm.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},um=e=>{const t=e.getInitializer();return t===void 0?!1:r.isCallExpression(t)||r.isIdentifier(t)||r.isPropertyAccessExpression(t)},mi={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."},fm=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.`}),gm={cause:"it is exported only under a string name that is not an identifier, which the generated `api.ts` and dispatch table cannot address as `<module>.<name>`",remediation:"Export it under an identifier name as well (or instead)."},pm=new Set(["AgentDefinition","ContainerDefinition","QueueDefinition","RegisteredShape","SubscriptionDefinition","WorkflowDefinition"]),mm={cause:"it is exported only as `default` or under a reserved word, and this kind's name becomes an import binding and a generated class / binding name, where that is a syntax error",remediation:"Export it under a plain identifier: `export const <name> = …` (an extra `export default <name>` is fine)."},hm=(e,t,s)=>{if(!t.some(i=>Yi(i)))return gm;const n=e.getVariableStatement()?.hasExportKeyword()===!0;return pm.has(s.typeName)&&!n&&!t.some(i=>uo(i))?mm:mi},hi=(e,t,s,n,i)=>{const{call:o,file:a,note:c,typeName:l}=s,u=a!==void 0&&e!==a?a:void 0,f=u===void 0?i:fm(u),g=c===void 0?f.remediation:`${c} ${f.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when its initializer is literally the registering call and the module exports it under an identifier name — by the `export` keyword, a local `export { … }`, or `export default`. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${l}\` but was not registered — ${f.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:l},name:"procedure_not_registered",remediation:u===void 0?`Assign the registration directly: \`export const ${t} = ${o};\`. ${g}`:g,title:"Procedure exists at runtime but is missing from the generated API"}},vm=(e,t,s)=>{const n=[];for(const i of G(e)){const o=r.isIdentifier(i.getNameNode())?vt(i):[i.getName()],c=o.some(u=>Ke(s,t,u))||!um(i)?void 0:pi(i),[l=i.getName()]=o;c!==void 0&&n.push(hi(t,l,c,i.getStartLineNumber(),hm(i,o,c)))}return n},Em=(e,t,s)=>{if(Ke(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(o=>!o.isExportEquals()&&!r.isIdentifier(o.getExpression()))){const o=pi(i.getExpression());o!==void 0&&n.push(hi(t,"default",o,i.getStartLineNumber(),mi))}return n},xm=(e,t,s)=>[...vm(e,t,s),...Em(e,t,s)],Sm=(e,t,s)=>e.getVariableStatements().flatMap(n=>n.getDeclarations()).filter(n=>r.isIdentifier(n.getNameNode())).filter(n=>vt(n).some(i=>Ke(s,t,i))).filter(n=>{const i=n.getInitializer();return i!==void 0&&r.isCallExpression(i)&&r.isPropertyAccessExpression(i.getExpression())}).map(n=>{const i=vt(n).find(o=>Ke(s,t,o))??n.getName();return{declaration:n,exportName:i,relativePath:t}}),Am=({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"}),ym=(e,t,s)=>{const n=[],i=[];for(const a of S(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const l=I(t,a);n.push(...xm(c,l,s)),i.push(...Sm(c,l,s))}const[o]=i;return o!==void 0&&i.every(({declaration:a})=>!gi(a.getType()))&&n.push(Am(o)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},bm=e=>{const t=e.getExpression();if(!r.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return r.isPropertyAccessExpression(s)?s.getName()==="workflows":r.isIdentifier(s)&&s.getText()==="workflows"},Nm=e=>{const t=e.getArguments()[0];return t&&r.isStringLiteral(t)?t.getLiteralText():""},wm=(e,t)=>T(e,t,(s,n)=>bm(s)?{file:n,line:s.getStartLineNumber(),scope:E(s),workflow:Nm(s)}:void 0),Ge=(e,t)=>{F(e)&&ki(e,"utf8")===t||Ri(e,t,"utf8")},Pm=(e,t)=>{if(t===""){mt(e,{force:!0});return}Ge(e,t)},Im=(e,t)=>{const s=v(e,"services");if(Object.keys(t).length===0){mt(s,{force:!0,recursive:!0});return}if(F(s))for(const n of Fi(s,{recursive:!0,withFileTypes:!0})){const i=v(n.parentPath,n.name);n.isFile()&&t[Li(e,i)]===void 0&&mt(i)}for(const[n,i]of Object.entries(t))sn(nn(v(e,n)),{recursive:!0}),Ge(v(e,n),i)},Cm=e=>{try{const t=go(v(e,"package.json"));return typeof t.version=="string"&&t.version!==""?t.version:void 0}catch{return}},ce=(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)},pt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Tm=(e,t)=>{F(e)||sn(e,{recursive:!0});const s=[];for(const n of t)n.kind==="services"?(Im(e,n.files),s.push(...Object.keys(n.files))):n.kind==="always"?(Ge(v(e,n.name),n.content),s.push(n.name)):(Pm(v(e,n.name),n.content),n.content!==""&&s.push(n.name));return s},Om=e=>{const t=Cm(e.projectRoot),s=e.wantsArchitecture?e.modules:[],n=mo({functions:e.functions,httpRoutes:e.httpRoutes,modules:s,version:t}),i=vo({functions:e.functions,modules:s,version:t});return{openApiContent:`${JSON.stringify(n,void 0,2)}
9
- `,openApiModuleContent:ho(n),openRpcContent:`${JSON.stringify(i,void 0,2)}
10
- `,openRpcModuleContent:Eo(i)}},km=".lunora-schema.json",Rm=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Fm=(e,t,s)=>{if(s&&e.length>0){const o=e.map(a=>`"${a.exportName}"`).join(", ");throw new q("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${o}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const o of t.columns){const a=n.get(o.table)??[];a.push(o.column),n.set(o.table,a)}const i=t.columns.length>0;for(const o of e){if(o.table===void 0){if(i)throw new q("MASK_UNSUPPORTED",`defineShape "${o.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${o.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(o.table);if(a===void 0)continue;const c=a.map(l=>`"${l}"`).join(", ");throw new q("MASK_UNSUPPORTED",`defineShape "${o.exportName}" replicates table "${o.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},Lm=8,Dm=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,internalPath:i,lunoraDirectory:o,migrations:a,project:c,shapes:l,usesSandbox:u,useUmbrella:f,workflows:g}=e,p=()=>to(()=>{const N=so(c,o),B=gr(c,o);return{functions:N,httpRoutes:no(c,o),mutators:B}});let{erased:x,value:{functions:k,httpRoutes:Q,mutators:L}}=p();Hs([...k,...L].map(N=>N.filePath)),Hs(Q.filter(N=>N.stream).map(N=>N.filePath),"http-stream");for(let N=1;;N+=1){const B=Po({agents:t,functions:k,httpRoutes:Q,mutators:L,useUmbrella:f,workflows:g}),M=Do({agents:t,functions:k,migrations:a,mutators:L,shapes:l,useUmbrella:f,usesSandbox:u}),w=Io({functions:k,useUmbrella:f});if(N>=Lm||pt(c,s,B)&&pt(c,i,w)&&pt(c,n,M))return{apiContent:B,erased:x,functions:k,functionsContent:M,httpRoutes:Q,internalContent:w,mutators:L};ce(c,s,B),ce(c,i,w),ce(c,n,M),{erased:x,value:{functions:k,httpRoutes:Q,mutators:L}}=p()}},Xh=e=>{const t=Rm(),s=t?it.now():0,n=v(e.projectRoot,e.lunoraDirectory??"lunora"),i=v(n,"schema.ts");if(!F(i))throw new q("INTERNAL",`schema.ts not found at ${i}`);const o=e.project??Or(n);or(hp);const a=co(o,i,e.projectRoot);Qp(a.tables,jp(o,n,An(e.projectRoot)));const{agents:c,capabilities:l,containers:u,crons:f,dataModelContent:g,dependencies:p,entryCronTriggers:x,env:k,featureUsage:Q,hasFlags:L,hasNotify:N,identity:B,platformGate:M,queues:w,serverContent:se,services:ne,storageRulesMetadata:le,topics:ie,usesSandbox:Se,useUmbrella:U,workflows:_}=Zg({lunoraDirectory:n,project:o,projectRoot:e.projectRoot,schema:a,target:e.target});Sp(a,a.jurisdiction===void 0?void 0:Ep(o,n));const K=v(n,"_generated"),R=v(K,"dataModel.ts"),vi=v(K,"server.ts"),Ei=v(K,"api.ts"),xi=v(K,"internal.ts"),Si=v(K,"functions.ts");ce(o,R,g),ce(o,vi,se);const qt=Object.fromEntries(ne.filter(m=>m.rpcEntrypoint!==void 0).flatMap(m=>Object.entries(Gr(m,K))));for(const[m,nt]of Object.entries(qt))ce(o,v(K,m),nt);const Ae=ro(o,n),re=lo(o,n),{apiContent:Wt,erased:Ai,functions:oe,functionsContent:Ht,httpRoutes:Ye,internalContent:jt,mutators:Qe}=Dm({agents:c,apiPath:Ei,generatedFunctionsPath:Si,internalPath:xi,lunoraDirectory:n,migrations:Ae,project:o,shapes:re,useUmbrella:U,usesSandbox:Se,workflows:_}),Gt=Nr(o,n),Xe=wr(Gt,a,[...oe,...Ye].map(m=>m.filePath)),ye=Gt.length>0,be=e.lint===!1&&!ye?void 0:{callEdges:up(o,n),inserts:io(o,n),queries:oo(o,n,oe),tableWrites:rm(o,n),workflowCalls:wm(o,n)},Ne=e.lint===!1||be===void 0?void 0:og(o,n,{callSites:be,containers:u,crons:f,functions:oe,modules:Xe,mutators:Qe,queues:w,schema:a,shapes:re,workflows:_,wranglerVariables:e.wranglerVariables}),Yt=Ne===void 0?[]:gg(e.projectRoot,[...Di(Ne,{source:"static"}),...ym(o,n,{byName:new Set([..._,...w,...c,...u].map(m=>m.exportName)),byPath:new Set([...oe,...Qe,...re,...Ae].map(m=>`${m.filePath}:${m.exportName}`))}),...lm(o,n),...eo(Ai,n),...xo(w,e.wranglerQueueProducers)]),yi=ao(o,n),Qt=wp(o,n);Fm(re,Qt,bp(o,n));const bi=L?mp(o,n):[],Je=M.signals.vectorStore!==!1,de=Xp(Q,{containerCount:u.length,cronCount:f.length,dependencies:p,hasPaymentTables:Cp(a.tables),queueCount:w.length,storageColumnCount:Object.keys(bn(a)).length,storageRuleCount:le.rules.length,vectorIndexCount:a.vectorIndexes.length,target:yn(e.projectRoot,e.target),vectorStoreSupported:Je,workflowCount:_.length}),Xt=t?it.now():0,Ze=po(a,Ae.map(m=>m.id)),Jt=Hr({advisories:Yt.filter(m=>m.name!=="procedure_type_check_unavailable"),advisorProcedures:Ne?.procedureProtections??[],agents:c,capabilities:l,containers:u,env:k,flagKeys:bi,hasFlags:L,hasNotify:N,hasVectors:Je,maskMetadata:Qt,mutators:Qe,queues:w,rlsMetadata:yi,schema:a,schemaSnapshot:Ze,shapes:re,services:ne,storageRules:le,studioFeatures:de,topics:ie,useUmbrella:U,workflows:_}),Zt=No(re,p.has("@lunora/db"),U),es=So(u,a.jurisdiction),ts=Ao(_),ss=yo(c),ns=bo(w,e.wranglerQueueProducers),is=Co(f),Ni=To(de.scheduler),wi=Oo(a.tables,U),Pi=ir(e.projectRoot)?ko(U):"",rs=Ro(a.vectorIndexes),we=Lo(a,U),os=wo(p.has("@lunora/seed")),Pe=e.apiSpec??"openapi",et=Pe==="openapi"||Pe==="both",tt=Pe==="openrpc"||Pe==="both",as=fo({capabilities:l,emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({className:m.className,exportName:m.exportName})),hasAccess:p.has("@lunora/cloudflare-access"),hasAuth:p.has("@lunora/auth"),hasFramework:p.has("@lunora/astro")||p.has("@lunora/svelte")||p.has("@lunora/vue")||F(v(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(m=>xn(m)),hasHyperdriveGlobal:a.tables.some(m=>Sn(m)),hasKvIntrospector:de.kv,hasNotify:N,hasQueue:w.some(m=>m.mode==="push"),hasScheduler:de.scheduler,hasSourcedTables:a.tables.some(m=>m.externalSource!==void 0),hasStorage:de.storage,hasVectors:Je,hasWorkflow:_.length>0,identity:B,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(m=>({name:m.name,shardMode:m.shardMode})),useUmbrella:U,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsArchitecture:ye,wantsOpenApi:et,wantsOpenRpc:tt}),{openApiContent:cs,openApiModuleContent:ls,openRpcContent:ds,openRpcModuleContent:us}=Om({functions:oe,httpRoutes:Ye,modules:Xe,projectRoot:e.projectRoot,wantsArchitecture:ye}),ue=ye&&be!==void 0?Cg({...be,crons:f,functions:oe,httpRoutes:Ye,modules:Xe,queues:w,schema:a,services:ne,topics:ie,workflows:_}):void 0,st=v(n,km),Ii=F(st),Ci=e.dryRun?[]:Tm(K,[{content:as,kind:"always",name:"app.ts"},{content:g,kind:"always",name:"dataModel.ts"},{content:Wt,kind:"always",name:"api.ts"},{content:jt,kind:"always",name:"internal.ts"},{content:se,kind:"always",name:"server.ts"},{content:Ht,kind:"always",name:"functions.ts"},{content:Jt,kind:"always",name:"shard.ts"},{content:is,kind:"always",name:"crons.ts"},{content:rs,kind:"always",name:"vectors.ts"},{content:we.global,kind:"always",name:"drizzle.global.ts"},{content:we.shard,kind:"always",name:"drizzle.shard.ts"},{content:es,kind:"optional",name:"containers.ts"},{content:ts,kind:"optional",name:"workflows.ts"},{content:ss,kind:"optional",name:"agents.ts"},{content:ns,kind:"optional",name:"queues.ts"},{content:Ni,kind:"optional",name:"scheduler.ts"},{content:wi,kind:"optional",name:"shardRegistry.ts"},{content:Pi,kind:"optional",name:"durableObjects.ts"},{content:os,kind:"optional",name:"seed.ts"},{content:Zt,kind:"optional",name:"collections.ts"},{files:qt,kind:"services"},{content:et?cs:"",kind:"optional",name:"openapi.json"},{content:et?ls:"",kind:"optional",name:"openapi.ts"},{content:tt?ds:"",kind:"optional",name:"openrpc.json"},{content:tt?us:"",kind:"optional",name:"openrpc.ts"},{content:ue===void 0?"":`${JSON.stringify(ue,void 0,2)}
11
- `,kind:"optional",name:"architecture.json"},{content:ue===void 0?"":Tg(ue),kind:"optional",name:"architecture.ts"}]);if(!e.dryRun&&(!Ii||e.updateSchemaBaseline===!0)&&Ge(st,Mi(Ze)),t){const m=it.now(),nt=Math.round(m-s),Ti=Math.round(Xt-s),Oi=Math.round(m-Xt);console.error(`@lunora/codegen: codegen took ${nt.toString()}ms (discovery ${Ti.toString()}ms, emit ${Oi.toString()}ms)`)}return{advisories:Yt,advisorContext:Ne,agents:c,architecture:ue,containers:u,cronTriggers:[...new Set([...Fo(f),...x])],generated:{agents:ss,api:Wt,app:as,collections:Zt,containers:es,crons:is,dataModel:g,drizzleGlobal:we.global,drizzleShard:we.shard,functions:Ht,internal:jt,openApi:cs,openApiModule:ls,openRpc:ds,openRpcModule:us,queues:ns,seed:os,server:se,shard:Jt,vectors:rs,workflows:ts},migrations:Ae,outputDirectory:K,platformDiagnostics:M.diagnostics,queues:w,schemaSnapshot:Ze,schemaSnapshotPath:st,workflows:_,writtenFiles:Ci}};export{km as SCHEMA_SNAPSHOT_FILENAME,Or as createCodegenProject,ev as findTsconfig,tv as refreshCodegenProject,Xh as runCodegen};
@@ -1 +0,0 @@
1
- import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-B81lOULB.mjs";import{b as p,d}from"./attribution-hVBriwzy.mjs";import{t as m}from"./database-calls-CHZbBUCZ.mjs";import{c as b}from"./classify-procedure-call-BAj0D1u2.mjs";import{r as h}from"./chain-CRDaTj2c.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=h(e);return{rlsTables:t.flatMap(r=>g(r)),usesRls:t.length>0}},v=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),P=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),T=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=m(e,v,P);return{exportName:d(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},M=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=T(a,n);l&&r.push(l)}}return r};export{M as default};
@@ -1 +0,0 @@
1
- import{LunoraError as R}from"@lunora/errors";import{Node as i,SyntaxKind as F}from"ts-morph";import{diagnosticAt as d}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as C}from"node:module";import{join as _}from"node:path";import{fileURLToPath as B}from"node:url";import{createJiti as V}from"jiti";import{findObjectProperty as u}from"./isTestPath-B81lOULB.mjs";import{r as q,p as J}from"./parse-validator-IDBKIT7M.mjs";import{R as U}from"./reserved-words-CW1QFbTd.mjs";import{a as I}from"./project-config-file-BV7RR-l6.mjs";const K=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,W=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},Z=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),m=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:Z(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=m(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=W(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,m(a)]));break}case"record":{s.valueType=m(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=m(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>m(o));break}}return s},G=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",X=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},H=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return X(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,m(o)])),shardMode:G(e.shardMode),vectorIndexes:[]}},Q=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>H(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},Y=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},ee=e=>{const t=Y(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},te=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ne=(e,t)=>{const n=ee(e);if(n)try{const s=V(_(t,"noop.js")).esmResolve(n.moduleSpecifier),r=C(_(t,"noop.cjs"))(s.startsWith("file:")?B(s):s),o=te(r,n);return typeof o!="object"||o===null?void 0:Q(o)}catch{return}},re=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},x=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},O=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},h=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},A=e=>e&&re.has(e)?e:void 0,y=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",se=(e,t)=>{const n=h(e,t);return n!==void 0&&n.length>0?n:void 0},N=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw d(l,`\`.${t}(...)\` expects a string literal (${r})`);const g=c.getLiteralText();if(!s.has(g))throw d(c,`unknown ${n} ${JSON.stringify(g)} — expected ${r}`);return g}o=l}},ie=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,oe=/^(?:sqlite_|_cf_|__)/u,ae=/__(?:agg|rank|geo|fts)_/u,le=e=>oe.test(e)||ae.test(e),ce=new Set(["cascade","restrict","set null"]),de=new Set(["aggregate","asId","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteWhere","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","replace","restore","system","wipeShard"]),P=/^[A-Za-z_$][\w$]*$/u,S=(e,t)=>{if(de.has(e))throw d(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(U.has(e))throw d(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!P.test(e))throw d(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(le(e))throw d(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},fe=e=>e&&ce.has(e)?e:void 0,ue=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},pe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw d(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",g;return o&&i.isObjectLiteralExpression(o)&&(l=f(o,"field")??l,c=f(o,"references")??c,g=s==="one"?fe(f(o,"onDelete")):void 0),{field:l,kind:s,name:I(e),onDelete:g,references:c,table:a}},ge=e=>{const t=ue(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=pe(s);r&&n.push(r)}return n},me=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw d(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},be=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw d(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},xe=e=>{const[t,n,s]=e,r=be(s),o=y(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw d(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>i.isStringLiteral(c));for(const c of l)me(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},he=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=h(n,"filterFields"),o=f(n,"language"),a=O(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:y(t),staged:a,strategy:l}},ye=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=x(n,"precision")),{field:s,name:y(t),precision:r}},ve=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=x(n,"after")),{after:r,field:s}},Ee=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},Ie=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Ee(l)).filter(l=>l!==void 0))}r=h(n,"partitionBy")}return{name:y(t),partitionBy:r,sortBy:s}},Se=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:x(s,"dimensions"),field:r,metadata:h(s,"metadata"),metric:A(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},ke=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},we=e=>{if(e&&i.isObjectLiteralExpression(e)){const t=u(e,"field");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isStringLiteral(n))return n.getLiteralText()}}return"deletedAt"},Te=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:se(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},_e=(e,t,n,s)=>{switch(t){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ye(n));break}case"global":{e.shardMode="global",e.globalBackend=ke(n);break}case"index":{e.indexes.push(xe(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(Ie(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ge(r));break}case"searchIndex":{e.searchIndexes.push(he(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:we(n[0])};break}case"source":{e.externalSource=Te(n),e.externallyManaged=!0;break}case"ttl":{e.ttl=ve(n);break}case"vectorize":{const r=Se(n,s);r&&e.vectorIndexes.push(r);break}}},L=["__vocab","_config","_content","_data","_docsize","_idx"],Le=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of L){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw d(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${L.join(", ")}.`)}},Oe=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw d(e,ie(t))},$=(e,t)=>{const n={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))_e(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=J(l);else if(l)throw d(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return n.softDelete&&!(n.softDelete.field in s)&&(s={...s,[n.softDelete.field]:{inner:{column:{notNull:!1},kind:"number"},kind:"optional"}}),Le(e,t,n.searchIndexes),Oe(e,t,n),{commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},j=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=q(r.getExpression());a!==void 0&&!s.has(a)&&j(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=I(r);if(S(a,r.getNameNode()),n.has(a))throw d(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push($(o,a))}}return t},Ae=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},Ne=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:x(s,"dimensions"),metric:A(f(s,"metric")),name:o,table:Ae(s)}},D=e=>{const t=[];for(const n of e.getProperties()){const s=Ne(n);s&&t.push(s)}return t},k=(e,t)=>`${e}_${t}`,Pe=(e,t)=>{if(!P.test(e))throw d(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},E=(e,t,n)=>n.has(e)?k(t,e):e,$e=(e,t,n,s)=>{const r=k(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,relations:e.relations.map(o=>({...o,table:E(o.table,t,n)})),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:E(o.table,t,n)}))}},je=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},De=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},ze=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Me=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Re=(e,t)=>{const n=je(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Me(n);return s?b(s,t.getName()):void 0}return n}},Fe=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,De(t))return t;const s=ze(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=Re(a,t)}},Ce=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Be=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=I(r);S(a,r.getNameNode()),s.push($(o,a))}return s},Ve=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:D(n)},z=(e,t,n,s,r)=>{Pe(e,s);const o=new Set(t.map(c=>c.name)),a=t.map(c=>$e(c,e,o,r)),l=n.map(c=>({...c,name:k(e,c.name),table:E(c.table,e,o)}));return{tables:a,vectorIndexes:l}},qe=(e,t,n)=>z(e,Be(n),Ve(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Je=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Fe(n);if(!s){if(t!==void 0){const o=ne(n,t);if(o){for(const a of o.bareTables)S(a.name,n);return z(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Ce(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return qe(r.key,r.keyNode,r.options)},Ue=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},Ke=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ue(e)){const a=Je(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw d(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},We=new Set(["eu","fedramp","us"]),Ze=e=>N(e,"jurisdiction","jurisdiction",We,'"eu", "us", or "fedramp"'),Ge=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&O(r,"pinAuth")===!0}t=s}},Xe=new Set(["required"]),He=e=>N(e,"rls","rls mode",Xe,'"required"'),ct=(e,t,n)=>{const r=e.addSourceFileAtPath(t).getDescendantsOfKind(F.CallExpression).find(p=>{const T=p.getExpression();return i.isIdentifier(T)&&T.getText()==="defineSchema"});if(!r)throw new R("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw d(r,"defineSchema() expects an object literal");const a=j(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?D(l):[],g=Ke(r,a,n),w=[...a.flatMap(p=>p.vectorIndexes),...c,...g],M=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),v=w.find(p=>M.has(p.table));if(v)throw d(r,K(v.table,v.name));return{jurisdiction:Ze(r),...Ge(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:He(r),tables:a,vectorIndexes:w}};export{ct as default};
@@ -1 +0,0 @@
1
- import{Node as i}from"ts-morph";import{listLunoraSourceFiles as u,lunoraRelativePath as f}from"./isTestPath-B81lOULB.mjs";import{b as m,d as p}from"./attribution-hVBriwzy.mjs";import{t as d}from"./database-calls-CHZbBUCZ.mjs";import{w as g,c as h}from"./classify-procedure-call-BAj0D1u2.mjs";import{a as k}from"./project-config-file-BV7RR-l6.mjs";const l=e=>{if(!(!i.isPropertyAssignment(e)&&!i.isShorthandPropertyAssignment(e)&&!i.isMethodDeclaration(e)&&!i.isGetAccessorDeclaration(e)))return k(e)},v=e=>g(e,"use","mask"),D=e=>{if(i.isPropertyAssignment(e)){const s=e.getInitializer();if(s&&i.isStringLiteral(s)){const t=s.getLiteralText();if(t==="redact"||t==="hash")return t}}return"custom"},P=e=>{const s=e.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return[];const t=[];for(const r of s.getProperties()){const o=l(r);if(o===void 0||!i.isPropertyAssignment(r))continue;const n=r.getInitializer();if(!(!n||!i.isObjectLiteralExpression(n)))for(const a of n.getProperties()){const c=l(a);c!==void 0&&t.push({column:c,table:o})}}return t},y=e=>{const s=v(e);return{maskColumns:s.flatMap(t=>P(t)),usesMask:s.length>0}},C=new Set(["findFirst","findFirstOrThrow","findMany","get","query"]),M=new Set(["delete","insert","patch","replace"]),b=(e,s)=>{if(!i.isVariableDeclaration(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const r=h(t);if(!r)return;const o=r.receiver?y(r.receiver):{maskColumns:[],usesMask:!1},{tablesRead:n,tablesWritten:a}=d(e,C,M);return{exportName:p(e)??e.getName(),file:s,maskColumns:o.maskColumns,tablesRead:n,tablesWritten:a,usesMask:o.usesMask,visibility:r.visibility}},E=(e,s)=>{const t=[];for(const r of u(s)){const o=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=f(s,r);for(const a of m(o)){const c=b(a,n);c&&t.push(c)}}return t};export{l as a,E as d,v as m,D as s};