@lunora/codegen 1.0.0-alpha.197 → 1.0.0-alpha.199
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 +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-VOvxb_1e.mjs → GENERATED_HEADER-CEgr9fSF.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-Cm2-NfDm.mjs → MUTATORS_FILENAME-B7EXNAFK.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-COQLvoDY.mjs → OPENRPC_VERSION-D6-0Hn3B.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-D4JKkyfD.mjs → SCHEMA_SNAPSHOT_FILENAME-BpSBAMAb.mjs} +4 -4
- package/dist/packem_shared/{buildOpenApiDocument-D_-3ZGH1.mjs → buildOpenApiDocument-DCGde3iO.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-C9O2RBTz.mjs → discoverFunctions-DRf4ucil.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-S81Iv_iB.mjs → discoverHttpRoutes-_ME7hLcW.mjs} +1 -1
- package/dist/packem_shared/{emit-CTDEkEXh.mjs → emit-BuaY_1hY.mjs} +30 -19
- package/dist/packem_shared/{emitApp-dpkp-O2j.mjs → emitApp-nInCbDo8.mjs} +14 -9
- package/dist/packem_shared/unwrap-handler-return-Da99uRXX.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/unwrap-handler-return-CmIWbykC.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -3417,6 +3417,18 @@ interface EmitAppOptions {
|
|
|
3417
3417
|
hasR2sql: boolean;
|
|
3418
3418
|
/** App imports `@lunora/scheduler` / declares crons → emit `.scheduler()`. */
|
|
3419
3419
|
hasScheduler: boolean;
|
|
3420
|
+
/**
|
|
3421
|
+
* Schema declares `.source(...)` tables → emit `.sourceClient()` (the resolver
|
|
3422
|
+
* the shard's ingest poll turns a wrangler Hyperdrive binding into a SQL client
|
|
3423
|
+
* with).
|
|
3424
|
+
*
|
|
3425
|
+
* Same shape as `cdc`: `ShardDOConfig` declares `sourceClient` and the emitted
|
|
3426
|
+
* poll loop reads it, but nothing on the builder reached it — and
|
|
3427
|
+
* `createShardDO` is called from this file and nowhere else in a `defineApp()`
|
|
3428
|
+
* project. So every sourced table hit the "no sourceClient resolved for
|
|
3429
|
+
* binding" branch on every tick forever, stayed empty, and codegen exited 0.
|
|
3430
|
+
*/
|
|
3431
|
+
hasSourcedTables: boolean;
|
|
3420
3432
|
/** App uses `@lunora/storage` → emit `.storage()` (DO `ctx.storage` + studio file browser). */
|
|
3421
3433
|
hasStorage: boolean;
|
|
3422
3434
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -3417,6 +3417,18 @@ interface EmitAppOptions {
|
|
|
3417
3417
|
hasR2sql: boolean;
|
|
3418
3418
|
/** App imports `@lunora/scheduler` / declares crons → emit `.scheduler()`. */
|
|
3419
3419
|
hasScheduler: boolean;
|
|
3420
|
+
/**
|
|
3421
|
+
* Schema declares `.source(...)` tables → emit `.sourceClient()` (the resolver
|
|
3422
|
+
* the shard's ingest poll turns a wrangler Hyperdrive binding into a SQL client
|
|
3423
|
+
* with).
|
|
3424
|
+
*
|
|
3425
|
+
* Same shape as `cdc`: `ShardDOConfig` declares `sourceClient` and the emitted
|
|
3426
|
+
* poll loop reads it, but nothing on the builder reached it — and
|
|
3427
|
+
* `createShardDO` is called from this file and nowhere else in a `defineApp()`
|
|
3428
|
+
* project. So every sourced table hit the "no sourceClient resolved for
|
|
3429
|
+
* binding" branch on every tick forever, stayed empty, and codegen exited 0.
|
|
3430
|
+
*/
|
|
3431
|
+
hasSourcedTables: boolean;
|
|
3420
3432
|
/** App uses `@lunora/storage` → emit `.storage()` (DO `ctx.storage` + studio file browser). */
|
|
3421
3433
|
hasStorage: boolean;
|
|
3422
3434
|
/**
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as h}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as D}from"./packem_shared/discoverFunctions-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-DwmUKYuc.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as h}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as D}from"./packem_shared/discoverFunctions-DRf4ucil.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-_ME7hLcW.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-DP3Vb0HC.mjs";import{default as y}from"./packem_shared/discoverInserts-COk-Sm_n.mjs";import{d as W}from"./packem_shared/index-C4eKBBMk.mjs";import{default as V}from"./packem_shared/discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-B7EXNAFK.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-Dy6k2aPS.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-Bgq52CnU.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-CPlxXagL.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-FaK1-wbV.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-D_J8cH-m.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-DwULXx5T.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-DskdDbkM.mjs";import{default as xe}from"./packem_shared/discoverSchema-DoZtXwLg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-C3ywuLJd.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-BaSbufF2.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-BuaY_1hY.mjs";import{emitApp as We}from"./packem_shared/emitApp-nInCbDo8.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-DCGde3iO.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-D6-0Hn3B.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-DtzlGawL.mjs";import{PROJECT_CONFIG_FILENAMES as ir,findProjectConfigFile as mr,loadProjectConfig as dr,readProjectConfigLiterals as fr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,createCodegenProject as nr,findTsconfig as lr,refreshCodegenProject as Sr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BpSBAMAb.mjs";import{SchemaSnapshotParseError as Ar,buildSchemaSnapshot as ur,evaluateSchemaDrift as vr,parseSchemaSnapshot as Nr}from"./packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs";import{schemaFromIr as Cr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Mr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as _r,SDK_TARGETS as hr,generateSdk as Lr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ir,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Gr,findSolutionByMessage as Ur}from"@lunora/errors";import{isTypedSchema as Hr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Gr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,ir as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,_r as SDK_LANGUAGES,hr as SDK_TARGETS,Ae as SHAPES_FILENAME,Ar as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,ur as buildSchemaSnapshot,nr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,vr as evaluateSchemaDrift,Ur as findLunoraSolution,mr as findProjectConfigFile,lr as findTsconfig,m as formatAdvisories,Lr as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,Hr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,dr as loadProjectConfig,Nr as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,fr as readProjectConfigLiterals,tr as readProjectTarget,Ir as redact,Sr as refreshCodegenProject,sr as resolveCodegenTarget,xr as runCodegen,Cr as schemaFromIr,Pr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Mr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{G as r,U as o,o as n,e as l,a as A,b as E,c as S,d as p,f as c,g as d,h as g,p as u,i as C,q as h,j as D,k as f,l as G,m as R,n as _}from"./emit-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{G as r,U as o,o as n,e as l,a as A,b as E,c as S,d as p,f as c,g as d,h as g,p as u,i as C,q as h,j as D,k as f,l as G,m as R,n as _}from"./emit-BuaY_1hY.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./paths-C-9fwEgQ.mjs";import"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,l as emitAgents,A as emitApi,E as emitCollections,S as emitContainers,p as emitCrons,c as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,C as emitScheduler,h as emitSeed,D as emitServer,f as emitShard,G as emitVectors,R as emitWorkflows,_ as emitWranglerCronTriggers};
|
package/dist/packem_shared/{MUTATORS_FILENAME-Cm2-NfDm.mjs → MUTATORS_FILENAME-B7EXNAFK.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as p}from"node:fs";import{join as f}from"node:path";import{Node as o,SyntaxKind as c}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as g}from"./module-specifiers-WF8iAydP.mjs";import{a as d}from"./parse-validator-tdRHHDzh.mjs";import{u as x}from"./unwrap-handler-return-
|
|
1
|
+
import{existsSync as p}from"node:fs";import{join as f}from"node:path";import{Node as o,SyntaxKind as c}from"ts-morph";import{diagnosticAt as l}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as g}from"./module-specifiers-WF8iAydP.mjs";import{a as d}from"./parse-validator-tdRHHDzh.mjs";import{u as x}from"./unwrap-handler-return-Da99uRXX.mjs";const y="mutators.ts",m=g,M=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineMutator";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return m(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineMutator":!1;return!1},S=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(c.ImportDeclaration);return i!==void 0&&m(i.getModuleSpecifierValue())}return!1},N=r=>{if(o.isIdentifier(r))return M(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineMutator"&&o.isIdentifier(t)&&S(t)}return!1},I=r=>{const t=r.getArguments()[0];return t&&o.isObjectLiteralExpression(t)?t:void 0},P=r=>{const t=r?.getProperty("args");if(!t||!o.isPropertyAssignment(t))return{};const e=t.getInitializer();return e&&o.isObjectLiteralExpression(e)?d(e):{}},b=r=>{const t=r?.getProperty("server");if(!t||!o.isPropertyAssignment(t))return"unknown";const e=t.getInitializer();return!e||!(o.isArrowFunction(e)||o.isFunctionExpression(e))?"unknown":x(e)},A=r=>{const t=r?.getProperty("owner");if(!t||!o.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&o.isStringLiteral(e)?e.getLiteralValue():void 0},E=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==c.CallExpression)continue;const n=i,a=n.getExpression();if(!N(a))continue;const s=e.getNameNode();if(!o.isIdentifier(s))throw l(s,"defineMutator exports must be plain named exports (no destructuring)");const u=I(n);t.push({args:P(u),exportName:s.getText(),filePath:"mutators",line:n.getStartLineNumber(),owner:A(u),returnType:b(u)})}return t},h=(r,t)=>{const e=f(t,y);if(!p(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=E(i);return n.sort((a,s)=>a.exportName.localeCompare(s.exportName)),n};export{y as MUTATORS_FILENAME,h as discoverMutators,N as isDefineMutatorCallee};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-BuaY_1hY.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
2
|
`,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{existsSync as b,mkdirSync as Is,readFileSync as _t,writeFileSync as ws,rmSync as Ts}from"node:fs";import{join as E,dirname as ne}from"node:path";import{performance as Ae}from"node:perf_hooks";import{runAdvisor as Cs}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{SyntaxKind as l,Node as o,VariableDeclarationKind as Fs,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as Os}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Rs}from"./formatAdvisories-DwmUKYuc.mjs";import{s as Ls}from"./paths-C-9fwEgQ.mjs";import{C as re,o as zt,j as Ds,f as ks,k as Ms,b as Ks,c as _s,m as zs,e as $s,p as Us,d as qs,i as Bs,l as Vs,g as Ws,q as js,n as Hs,a as Gs,h as Ys}from"./emit-
|
|
1
|
+
import{existsSync as b,mkdirSync as Is,readFileSync as _t,writeFileSync as ws,rmSync as Ts}from"node:fs";import{join as E,dirname as ne}from"node:path";import{performance as Ae}from"node:perf_hooks";import{runAdvisor as Cs}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{SyntaxKind as l,Node as o,VariableDeclarationKind as Fs,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as Os}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Rs}from"./formatAdvisories-DwmUKYuc.mjs";import{s as Ls}from"./paths-C-9fwEgQ.mjs";import{C as re,o as zt,j as Ds,f as ks,k as Ms,b as Ks,c as _s,m as zs,e as $s,p as Us,d as qs,i as Bs,l as Vs,g as Ws,q as js,n as Hs,a as Gs,h as Ys}from"./emit-BuaY_1hY.mjs";import{isD1GlobalTable as $t,isHyperdriveGlobalTable as Ut}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Qs}from"./AGENTS_FILENAME-B78F7DuQ.mjs";import{discoverContainers as Xs}from"./CONTAINERS_FILENAME-CQoUu7n7.mjs";import Zs from"./discoverCrons-CMu0sA8k.mjs";import{diagnosticAt as ue}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as de}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,unwrapExpression as G,listSecurityScanFiles as Re,objectLiteralFromCallbackBody as qt,propertyInitializer as A,lunoraRelativePath as x,collectCallRows as w,collectSecurityCallRows as Js,limitNameOf as Bt,isContextIdentifier as Ie,handlerOf as en,isDatabaseAccessor as D,readTargetOf as Vt,enclosingExportName as tn}from"./listLunoraSourceFiles-D4xthUf-.mjs";import sn from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as nn}from"./QUEUES_FILENAME-Q3CF3uYr.mjs";import{discoverSandboxUsage as rn}from"./discoverSandboxUsage-DskdDbkM.mjs";import on from"./discoverStorageRulesMetadata-C3ywuLJd.mjs";import{a as S,c as k,d as Wt,e as an}from"./classify-procedure-call-BIlyTUBD.mjs";import{discoverWorkflows as cn}from"./WORKFLOWS_FILENAME-BaSbufF2.mjs";import{gatePlatformFeatures as ln,resolveCodegenTarget as un,readTargetDiagnostics as dn}from"./DEFAULT_TARGET-DtzlGawL.mjs";import{i as R,a as _,e as v,r as fn,b as gn,s as fe,c as pn,f as mn,d as hn}from"./queries-CPlxXagL.mjs";import{r as ge,s as xn}from"./parse-validator-tdRHHDzh.mjs";import vn from"./discoverAuthApiCalls-DoblmzUW.mjs";import lt from"./discoverFunctions-DRf4ucil.mjs";import{i as En,r as Sn,e as yn}from"./unwrap-handler-return-Da99uRXX.mjs";import ut from"./discoverHttpRoutes-_ME7hLcW.mjs";import An from"./discoverHyperdriveCalls-DP3Vb0HC.mjs";import Nn from"./discoverInserts-COk-Sm_n.mjs";import{m as Le,a as oe,s as jt,d as bn}from"./index-C4eKBBMk.mjs";import{e as Ht}from"./exported-procedure-chains-Bqdp4ywr.mjs";import Pn from"./discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as In,isDefineMutatorCallee as wn,discoverMutators as dt}from"./MUTATORS_FILENAME-B7EXNAFK.mjs";import Tn from"./discoverNondeterministicCalls-Dy6k2aPS.mjs";import{discoverNotifyConfig as Cn,discoverNotifyCalls as Fn}from"./NOTIFY_FILENAME-Bgq52CnU.mjs";import On from"./discoverR2sqlCalls-FaK1-wbV.mjs";import Rn from"./discoverRlsProcedures-D_J8cH-m.mjs";import Ln from"./discoverRlsMetadata-DwULXx5T.mjs";import Dn from"./discoverSchema-DoZtXwLg.mjs";import{secretKindOf as kn,redact as Mn,isHeuristicSecretKind as Kn,isSecretishName as _n}from"./redact-Cy14LEnc.mjs";import{discoverShapes as zn}from"./SHAPES_FILENAME-Bvd5kgsF.mjs";import{emitApp as $n}from"./emitApp-nInCbDo8.mjs";import{buildOpenApiDocument as Un,emitOpenApiModule as qn}from"./buildOpenApiDocument-DCGde3iO.mjs";import{buildOpenRpcDocument as Bn,emitOpenRpcModule as Vn}from"./OPENRPC_VERSION-D6-0Hn3B.mjs";import{buildSchemaSnapshot as Wn}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const ft=(e,t="api")=>{const s=new Map;for(const n of e){const i=Ls(n),r=s.get(i);if(r===void 0){s.set(i,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new L("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},jn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:i=!1,usage:r}=t,a=[];e.tables.some(c=>$t(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=>Ut(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),i&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:re)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Hn=(e,t,s={})=>{if(t===void 0)return;const n=jn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const i=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
2
|
`);throw new L("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${i}
|
|
4
4
|
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},Gn="env.ts",Yn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Qn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},Xn=e=>{if(o.isIdentifier(e))return Yn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&Qn(t)}return!1},Zn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Xn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ue(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Jn=(e,t)=>{const s=E(t,Gn);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Zn(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},gt="ctx",Gt=e=>{const t=new Set,s=new Set([gt]),n=r=>{if(o.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==gt)continue;const a=r.getNameNode();o.isIdentifier(a)?s.add(a.getText()):n(a)}const i=r=>o.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))i(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&i(a)&&n(r.getNameNode())}return t},er=(e,t)=>{const s=Object.fromEntries(re.map(n=>[n.key,!1]));for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Gt(i);for(const c of re)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(re.every(c=>s[c.key]))break}return s},Yt="identity.ts",tr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},sr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},nr=e=>{if(o.isIdentifier(e))return tr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&sr(t)}return!1},rr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!nr(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ue(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},ir=(e,t)=>{const s=E(t,Yt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=rr(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},or=(e,t)=>{const s=G(t);if(s===void 0||!o.isIdentifier(s))return s;const n=s.getText();return G(e.getDescendantsOfKind(l.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},ar=e=>e!==void 0&&o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!o.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||G(s)?.getText()!=="false"}),cr=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Gt(i).has("secrets")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>ar(or(i,u)))})),s.durableStreams&&s.secrets)break}return s},lr="createWorker",ur="extend",pt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,mt=e=>{const t=[],s=pt(A(e,"backupCron"));s!==void 0&&t.push(s);const n=A(e,"crons");if(n===void 0||!o.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!o.isPropertyAssignment(i)&&!o.isMethodDeclaration(i))continue;const r=pt(i.getNameNode());r!==void 0&&t.push(r)}return t},dr=e=>{const t=y(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===lr)return o.isObjectLiteralExpression(s)?mt(s):[];if(t!==ur||!(o.isArrowFunction(s)||o.isFunctionExpression(s)))return[];const n=qt(s.getBody());return n===void 0?[]:mt(n)},fr=(e,t)=>{const s=[];for(const{filePath:n}of Re(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression))s.push(...dr(r))}return[...new Set(s)]},Qt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Qt(e.inner)},gr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Qt(n);return i!==void 0&&t.has(i)}))},pr=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new L("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new L("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new L("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},mr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=ir(s,t),a=Jn(s,t),c=cn(s,t),u=nn(s,t),d=Qs(s,t);pr(c,d);const h=Xs(s,t),m=on(s,t),P=Zs(s,t,c,d),M=fr(s,t),g=cr(s,t),T=rn(s,t),F=er(s,t);F.browser=F.browser||T.usesSandboxBrowser;const U=ln(F,un(n,e.target),{agents:d.length>0,commitOrderedTables:i.tables.some(N=>N.commitOrdered===!0),cronTriggers:P.length>0,crossShardFanout:i.tables.some(N=>typeof N.shardMode=="object"),durableStreams:g.durableStreams,globalTables:i.tables.some(N=>N.shardMode==="global"),queues:u.length>0,relationGraph:gr(i),secrets:g.secrets,vectorStore:i.vectorIndexes.length>0}),S=U.usage,O=U.signals.vectorStore!==!1,z=sn(n),W=z??new Set,X=W.has("lunorash");Hn(i,z,{hasVectors:O,scheduler:S.scheduler||P.length>0,storage:S.storage||m.rules.length>0||Object.keys(zt(i)).length>0,usage:S});const K=b(E(t,"flags.ts")),C=b(E(t,"notify.ts"));return{agents:d,containers:h,crons:P,dataModelContent:ks(i),declaredDependencies:z,dependencies:W,entryCronTriggers:M,env:a,featureUsage:S,hasFlags:K,hasNotify:C,identity:r,platformGate:{...U,diagnostics:[...dn(n,e.target),...U.diagnostics]},queues:u,serverContent:Ds({agents:d,containers:h,env:a,hasAccessFacade:S.access,hasAi:S.ai,hasAnalytics:S.analytics,hasBrowser:S.browser,hasVectors:O,hasFlags:K,hasHyperdrive:S.hyperdrive,hasImages:S.images,hasKv:S.kv,hasNotify:C,hasPayments:S.payments,hasPipelines:S.pipelines,hasR2sql:S.r2sql,hasX402:S.x402,identity:r,queues:u,schema:i,storageRuleBuckets:m.rules.map(N=>N.bucket),useUmbrella:X,workflows:c}),storageRulesMetadata:m,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer||T.usesSandboxFs,useUmbrella:X,workflows:c}},Xt=new Set(["delete","get","head","options","patch","post","put"]),hr=new Set(["handler","stream"]),xr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ht=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),vr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Xt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Er=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||Xt.has(n.getName()))break;s=n.getExpression()}return vr(s)},yr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(ht.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&ht.has(s.getText()))return!0}return!1},Sr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!hr.has(n.getName()))return;const i=Er(s);if(!i||!xr.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&yr(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Ar=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Sr(i,t);r&&s.push(r)}return s},Nr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ar(i,x(t,n)))}return s},br=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Pr=(e,t)=>{if(!br(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)||_(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Ir=(e,t)=>w(e,t,Pr),wr=new Set(["generateText","streamText"]),Tr=new Set(["messages","prompt","system"]),Cr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Fr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of Cr)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Or=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Fr(t);if(s!==void 0)return s}},Rr=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Lr=e=>{if(fn(e))return!0;const t=Rr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Dr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!Tr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Lr(s))return!0}return!1},kr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=y(n.getExpression());if(i===void 0||!wr.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=Or(c),a!==void 0))break;a!==void 0&&s.push({exportName:v(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Dr(r)})}return s},Mr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kr(i,x(t,n)))}return s},Kr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},_r=(e,t)=>{if(!Kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},zr=(e,t)=>w(e,t,_r),De=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!o.isSpreadAssignment(s))return!1;const n=ge(s.getExpression());return n===void 0||De(n,t)})}finally{t.delete(e)}},$r=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ge(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:De(i)}},Ur=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&o.isExpression(r)?ge(r):void 0;a===void 0?s=!0:(t.push(a),s||=De(a))}n=i.getExpression()}return{objects:t,opaque:s}},ke=(e,t)=>t?Ur(t):$r(e),Zt=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(o.isSpreadAssignment(s)){const n=ge(s.getExpression());return n===void 0?[]:Zt(n,t)}return o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},qr=e=>e.flatMap(t=>Zt(t,new Set)),Br=new Set(["check","length","max"]),we=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Vr=e=>[e,...e.getDescendants()].filter(t=>we(t)!==void 0),Wr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(Br.has(s.getName()))return!0;t=n}},jr=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=Vr(r),c=i.getName();a.some(u=>we(u)==="any")?t.push(c):a.some(u=>we(u)==="string"&&!Wr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Hr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=k(s);if(n?.visibility!=="public")return;const{objects:i}=ke(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=jr(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Gr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Hr(i,t);r&&s.push(r)}return s},Yr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gr(i,x(t,n)))}return s},Ne=e=>e?.getKind()===l.TrueKeyword,Qr=e=>e?.getKind()===l.FalseKeyword,Xr=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Zr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Jr=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&y(t.getExpression())==="scim"),ei=e=>e!==void 0&&o.isCallExpression(e)&&Zr.has(y(e.getExpression())??""),ti=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),si=e=>{const t=A(e,"advanced"),s=A(e,"emailAndPassword"),n=A(e,"session");return{analyzable:!0,disableCsrfCheck:Ne(A(t,"disableCSRFCheck")),emailPasswordEnabled:Ne(A(s,"enabled")),requireEmailVerification:Ne(A(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Jr(A(e,"plugins"))&&ei(A(e,"database")),secureCookiesDisabled:Qr(A(t,"useSecureCookies")),sessionFreshAgeZero:Xr(A(n,"freshAge")),trustedOriginsWildcard:ti(A(e,"trustedOrigins"))}},ni=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),ri=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?si(s):ni();return{exportName:v(e),file:t,line:e.getStartLineNumber(),...i}},ii=(e,t)=>Js(e,t,ri),oi=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},ai=(e,t,s)=>{const n=oi(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!R(i)||_(i))&&!(s.requireUnmodifiedReach===!0&&!gn(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:n}},ci=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=ai(i,t,s);r&&n.push(r)}return n},pe=(e,t,s)=>{const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...ci(r,x(t,i),s))}return n},li=new Set(["content","pdf","scrape","screenshot"]),ui=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:li}),di=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),fi=new Set(["RateLimiter"]),gi=new Set(["extend"]),xt="lunora",pi=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Jt=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Te=e=>e&&o.isObjectLiteralExpression(e)?Jt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},mi=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&qt(t.getBody());return s?Jt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},hi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=y(n.getExpression());i!==void 0&&(di.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])}):gi.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...mi(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=y(n.getExpression());i===void 0||!fi.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])})}return s},xi=(e,t)=>{for(const s of pi){const n=E(t,s);if(!b(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of i.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===xt&&r.push({callee:xt,file:s,line:a.getStartLineNumber(),...Te(a.getArguments()[0])});return r}return[]},vi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Re(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...hi(r,n))}return s.push(...xi(e,ne(t))),s},vt="ctx.containers.",Ei=e=>{if(!e.startsWith(vt))return!1;const t=e.slice(vt.length);return t.length>0&&!t.includes(".")},yi=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:Ei,methods:new Set(["get"])}),Si=new Set(["allow","deny","setAllowed"]),Ai=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Ni=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Ai(e)))return{detail:"enableInternet: true",exportName:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},bi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Si.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Pi=(e,t)=>Ni(e,t)??bi(e,t),Ii=(e,t)=>w(e,t,Pi),wi=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Ti=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return wi.has(s)?s:void 0},Ci=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=n.getName();t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Fi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Re(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Ti(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?Ci(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Oi=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ri=new Set(["dbRateLimit","rateLimit"]),Li=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Di=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=Oi.get(s);if(n!==void 0)return{callee:s,exportName:v(e),failOpen:Li(e.getArguments()[n]),file:t,limitName:Ri.has(s)?Bt(e):"",line:e.getStartLineNumber()}},ki=(e,t)=>w(e,t,Di),Mi=new Set(["boolean","number","object","string"]),Ki=e=>{const t=e.getName();if(!Mi.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ie(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ie(n.getExpression()))return t},_i=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=Ki(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},zi=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=_i(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},$i=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=k(t);if(s?.kind!=="query")return;const n=en(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},Et=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Ui=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=Et(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=Et(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},qi=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=Ui(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},Bi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=$i(i);r&&s.push(...qi(r,t))}return s},Vi=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Bi(i,x(t,n)))}return s},Wi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ie(t.getExpression())},ji=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Hi=(e,t)=>{if(!Wi(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=ji(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:v(e),file:t,key:i,line:e.getStartLineNumber()}},Gi=(e,t)=>w(e,t,Hi),Yi=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||En(r))return;const a=e.getSourceFile().getFilePath();return yn(i,e,a)?Sn(i,e,a,0,new Set):r},Qi=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Xi=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Zi=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))Qi(a)&&s.push({file:r,indexName:Xi(a),line:a.getStartLineNumber()})}return s},Y=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,es=e=>{const t=e.getArguments()[0],s=Y(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&o.isPropertyAssignment(n)?Y(n.getInitializer()):void 0},Ji=new Set(["delete","get","head","options","patch","post","put"]),eo=new Set(["handler","stream"]),to=new Set(["runAction","runMutation"]),so=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,ts=(e,t)=>{if(!(e===void 0||!o.isObjectBindingPattern(e))){for(const s of e.getElements())if((s.getPropertyNameNode()?.getText()??s.getNameNode().getText())===t){const i=s.getNameNode();return o.isIdentifier(i)?i.getText():void 0}}},yt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?o.isIdentifier(s)?s.getText():void 0:ts(s,"ctx")},St=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&o.isIdentifier(s)?s.getText():void 0:ts(s,"request")},At=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(to.has(a)&&Q(c,t))return a;if(so.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},Nt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Q(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!Q(n.getInitializer(),t))){for(const r of i.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},no=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ro=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return o.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Q(n.getExpression(),t)},io=e=>[...o.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],ss=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:io(s)},oo=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!o.isArrowFunction(n)&&!o.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!o.isCallExpression(i))return[];const r=i.getExpression();if(!o.isPropertyAccessExpression(r))return[];const a=r.getExpression();return o.isIdentifier(a)?ss(t,a.getText()):[]}return[]},ao=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(o.isStringLiteral(t))return[t.getLiteralText()];if(!o.isIdentifier(t))return[];const s=e.getSourceFile(),n=ss(s,t.getText());return n.length>0?n:oo(t,s)},bt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return o.isCallExpression(s)&&n.unshift(s),n.some(i=>ro(i,t)&&ao(i).some(r=>no.test(r)))},co=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!eo.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(Ji.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},lo=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Y(e.getArguments()[0]),u=c&&yt(c,!0);if(!c||u===void 0||bt(c,St(c,!0)))return;const d=At(c,u);return d===void 0?void 0:{exportName:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Nt(c,u),sideEffect:d}}const n=co(e);if(n===void 0)return;const i=Y(e.getArguments()[0]),r=i&&yt(i,!1);if(!i||r===void 0||bt(i,St(i,!1)))return;const a=At(i,r);return a===void 0?void 0:{exportName:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Nt(i,r),sideEffect:a}},uo=(e,t)=>w(e,t,lo),fo=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),go=new Set(["append","set"]),ns=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Pt=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>fo.has(y(n.getExpression())??"")&&mn(n,t)),po=(e,t)=>{if(Pt(e,t))return!0;const s=fe(e);return s!==void 0&&Pt(s,t)},Ce=(e,t)=>pn(e,t)&&!po(e,t),mo=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=fe(e);return t!==void 0&&o.isNewExpression(t)&&y(t.getExpression())==="Headers"},ae=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=fe(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Ce(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:ns(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Ce(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=ae(n.getExpression());i!==void 0&&Me(i,t,s)}},rs=(e,t)=>{const s=ae(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=ae(n.getInitializer());i!==void 0&&Me(i,"response-init",t)},ho=(e,t)=>{const s=y(e.getExpression());if(s==="Response")rs(e.getArguments()[1],t);else if(s==="Headers"){const n=ae(e.getArguments()[0]);n!==void 0&&Me(n,"headers-ctor",t)}},xo=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){rs(e.getArguments()[1],t);return}if(go.has(n)&&mo(i)){const r=e.getArguments()[1];r!==void 0&&Ce(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:ns(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},vo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))ho(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))xo(s,t)},Eo=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Y(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return vo(n,{exportName:v(e),relativePath:t,requestName:r.getText(),rows:a}),a},yo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Eo(n,t));return s},So=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...yo(i,x(t,n)))}return s},Ao=new Set(["auth","context.auth","ctx.auth"]),No="userId",bo=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},Po=(e,t)=>{const s=E(t,Yt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(y(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?bo(r):void 0}},It=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ao.has(e.getExpression().getText())?e:void 0},Io=e=>{if(o.isPropertyAccessExpression(e)&&It(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&It(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},wo=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Io(i);r!==void 0&&n.push({declared:r===No||s.has(r),exportName:v(i),file:t,key:r,line:i.getStartLineNumber()})}return n},To=(e,t)=>{const s=Po(e,t);if(s===void 0)return[];const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...wo(r,x(t,i),s))}return n},Co=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=A(s,"key");if(!(!n||!R(n)||_(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Fo=(e,t)=>w(e,t,Co),Oo=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ro=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Oo}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Lo=new Set(["queue","send"]),wt=new Set(["bcc","cc","to"]),Do=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Lo.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},ko=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return wt.has(t.getName())&&R(n)&&!_(n)}if(!o.isPropertyAssignment(t)||!wt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&R(s)&&!_(s)}):!1,Mo=(e,t)=>{const s=Do(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!ko(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},Ko=(e,t)=>w(e,t,Mo),_o=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,zo=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?_o(e):!0,is=(e,t=!1)=>{for(const s of e.getProperties()){if(zo(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||is(n,!0))return!0}return!1},$o=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ht(n))for(const r of Le(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||is(a)))return!0}}return!1},Uo=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=oe(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=oe(a);c!==void 0&&s.push({column:c,strategy:jt(a),table:i})}}return s},qo=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Ht(i))for(const a of Le(r))for(const c of Uo(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Bo=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=oe(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=oe(u);if(d===void 0)continue;const h=jt(u);h!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:h,table:a})}}return i},Vo=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?k(s):void 0;return n?.receiver?Le(n.receiver).flatMap(i=>Bo(i,e.getName(),t)):[]},Wo=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Vo(c,r))}return s},jo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return D(s)},Ho=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},Go=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return wn(s.getExpression())?s:void 0},Yo=e=>{const t=Go(e),s=t===void 0?void 0:Ho(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>jo(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Qo=e=>e.getVariableDeclarations().flatMap(t=>Yo(t)),Xo=(e,t)=>{const s=E(t,In);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Qo(n)},Zo=new Set(["delete","get","patch"]),Jo=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),ea=new Set(["auth","identity","session","user"]),ta=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),sa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!D(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},na=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},ra=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),ia=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,oa=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>ra(s.getExpression(),t)&&ia(s.getThenStatement())),aa=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Zo.has(i))continue;const r=n.getExpression();if(!(D(r)||o.isPropertyAccessExpression(r)&&D(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},ca=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},la=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>ca(s)==="ctx")),ua=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>ta.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),da=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Jo.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&ea.has(t.getName()))return!0}return la(e)||ua(e)},fa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=k(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=es(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Wt(n.receiver,"use","rls"),a=da(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const h=sa(d);if(h===void 0)continue;const m=na(d);if(m===void 0||c.has(m)||!oa(i,m))continue;const P=aa(i,m);P!==void 0&&(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:P,table:h,usesRls:r,visibility:n.visibility}))}return u},ga=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...fa(c,r))}return s},pa=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ma=new Set(["insert","insertManyUnsafe","patch","replace"]),ha=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ma.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},xa=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},Tt=(e,t)=>{if(o.isPropertyAccessExpression(e)){const s=e.getExpression();return o.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(o.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return o.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&o.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},va=e=>{if(!o.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(o.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let i,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!o.isVariableDeclarationList(c)||c.getDeclarationKind()!==Fs.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(i=u,r=d)}return i},Ea=(e,t)=>{if(Tt(e,t))return!0;const s=va(e);return s!==void 0&&Tt(s,t)},ya=(e,t,s,n,i)=>{const r=[];for(const a of e.getProperties()){let c,u;if(o.isPropertyAssignment(a)?(c=a.getName(),u=a.getInitializer()):o.isShorthandPropertyAssignment(a)&&(c=a.getName(),u=a.getNameNode()),!(c===void 0||u===void 0||!pa.has(c))&&R(u)&&!_(u)){const d=v(s),h=i(d)===c&&Ea(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...h&&{ownerScoped:!0}})}}return r},Sa=(e,t,s)=>{const n=ha(e.getExpression());if(n===void 0)return[];const i=e.getArguments()[1];return i?xa(i,n).flatMap(r=>ya(r,n,e,t,s)):[]},Aa=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of Sa(i,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Na=(e,t,s=[],n=[])=>{const i=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);i.push(...Aa(c,u,d=>r.get(`${u}:${d}`)??{}))}return i},ba=["providerSubscriptionId","state"],Pa=["providerEventId","processedAt"],Ct=(e,t)=>t.every(s=>s in e.shape),Ia=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Ct(t,ba)&&Ct(s,Pa)},wa=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Ta=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ca=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Ta(t.getInitializer()):void 0},Fa=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!wa.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Ca(n):void 0;return{callee:s,exportName:v(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Oa=(e,t)=>w(e,t,Fa),Ra=new Set(["defineQueue","defineWorkflow"]),La=new Set(["run","runAction","runMutation","runQuery"]),Da=new Set(["api","internal"]),ka=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},Ma=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},os=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},as=(e,t)=>e===t||e.startsWith(`${t}.`),cs=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},Ft=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},ls=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Ft(s));return o.isIdentifier(e)&&Ft(e)&&t.push(e),t},Ka=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},_a=e=>{const t=os(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},za=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:_a(e),i=new Set,r=a=>cs(a).some(c=>n.some(u=>as(c.getText(),u)))?!0:ls(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of Ka(a))i.add(u)}return{names:i,prefixes:n}},$a=(e,t)=>cs(e).some(s=>t.prefixes.some(n=>as(s.getText(),n)))?!0:ls(e).some(s=>t.names.has(s.getText())),Ua=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!Da.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},qa=(e,t,s)=>{const n=os(e,0);if(n===void 0)return[];const i=za(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!La.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!$a(u,i))continue;const d=Ua(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:v(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},Ba=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=ka(n);if(i===void 0||!Ra.has(i))continue;const r=Ma(n);r!==void 0&&s.push(...qa(r,i==="defineQueue"?"queue":"workflow",t))}return s},Va=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ba(i,x(t,n)))}return s},Ot={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Rt=new Set(["account","credential","member","passkey","session","user"]),Wa=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ja=e=>{const s=Wa(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Rt.has(s)||Rt.has(n)},Ha=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Ga=(e,t)=>{const{objects:s,opaque:n}=ke(e,t);return qr(s).some(i=>Ha(i))?!0:n?void 0:!1},Ya=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Qa=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},ie={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Xa=e=>{const t=Qa(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Ya(t);return{...ie,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ot?{...ie,[Ot[s]]:!0}:ie},Za=e=>{const t={...ie};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=Xa(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Ja=new Set(["insert","insertMany","insertManyUnsafe","replace"]),ec=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Ja.has(t.getName()))return!1;const s=t.getExpression();if(!D(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:ja(i.getLiteralText())},tc=new Set(["create","runAfter","runAt","send","sendBatch"]),sc=new Set(["queues","scheduler","workflows"]),nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!tc.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&sc.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},rc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return D(s)},us=new Set(["generateObject","generateText","streamObject","streamText"]),ic=e=>{const t=y(e.getExpression());return t!==void 0&&us.has(t)},oc=e=>{const t=y(e.getExpression());if(t===void 0||!us.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},ac=new Set(["log","span","trace"]),cc=new Set(["ai"]),lc=new Set(["email","mail"]),uc=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),be=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),dc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),fc=new Set(["every","filter","flatMap","forEach","map","some"]),gc=new Set(["all","allSettled","race"]),pc=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(fc.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&gc.has(n))return t},mc=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(dc.has(t.getKind())){const s=pc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},hc=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},xc=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},vc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!uc.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=xc(n);r&&(t=!0,!mc(r)&&!hc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ec=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),Lt="lunora-advisor-exempt",yc=/^[\s*/]+/u,Sc=/[\w-]/u,Ac=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
5
|
+
Install them with your package manager, then re-run codegen.`)},Gn="env.ts",Yn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Qn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},Xn=e=>{if(o.isIdentifier(e))return Yn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&Qn(t)}return!1},Zn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Xn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ue(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Jn=(e,t)=>{const s=E(t,Gn);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Zn(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},gt="ctx",Gt=e=>{const t=new Set,s=new Set([gt]),n=r=>{if(o.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==gt)continue;const a=r.getNameNode();o.isIdentifier(a)?s.add(a.getText()):n(a)}const i=r=>o.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))i(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&i(a)&&n(r.getNameNode())}return t},er=(e,t)=>{const s=Object.fromEntries(re.map(n=>[n.key,!1]));for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Gt(i);for(const c of re)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(re.every(c=>s[c.key]))break}return s},Yt="identity.ts",tr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},sr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},nr=e=>{if(o.isIdentifier(e))return tr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&sr(t)}return!1},rr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!nr(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ue(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},ir=(e,t)=>{const s=E(t,Yt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=rr(n);if(i.length!==0){if(i.length>1)throw ue(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},or=(e,t)=>{const s=G(t);if(s===void 0||!o.isIdentifier(s))return s;const n=s.getText();return G(e.getDescendantsOfKind(l.VariableDeclaration).find(i=>i.getName()===n)?.getInitializer())},ar=e=>e!==void 0&&o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!o.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||G(s)?.getText()!=="false"}),cr=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Gt(i).has("secrets")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>ar(or(i,u)))})),s.durableStreams&&s.secrets)break}return s},lr="createWorker",ur="extend",pt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,mt=e=>{const t=[],s=pt(A(e,"backupCron"));s!==void 0&&t.push(s);const n=A(e,"crons");if(n===void 0||!o.isObjectLiteralExpression(n))return t;for(const i of n.getProperties()){if(!o.isPropertyAssignment(i)&&!o.isMethodDeclaration(i))continue;const r=pt(i.getNameNode());r!==void 0&&t.push(r)}return t},dr=e=>{const t=S(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===lr)return o.isObjectLiteralExpression(s)?mt(s):[];if(t!==ur||!(o.isArrowFunction(s)||o.isFunctionExpression(s)))return[];const n=qt(s.getBody());return n===void 0?[]:mt(n)},fr=(e,t)=>{const s=[];for(const{filePath:n}of Re(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression))s.push(...dr(r))}return[...new Set(s)]},Qt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Qt(e.inner)},gr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const i=Qt(n);return i!==void 0&&t.has(i)}))},pr=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new L("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new L("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new L("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},mr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=ir(s,t),a=Jn(s,t),c=cn(s,t),u=nn(s,t),d=Qs(s,t);pr(c,d);const h=Xs(s,t),m=on(s,t),P=Zs(s,t,c,d),M=fr(s,t),g=cr(s,t),T=rn(s,t),F=er(s,t);F.browser=F.browser||T.usesSandboxBrowser;const U=ln(F,un(n,e.target),{agents:d.length>0,commitOrderedTables:i.tables.some(N=>N.commitOrdered===!0),cronTriggers:P.length>0,crossShardFanout:i.tables.some(N=>typeof N.shardMode=="object"),durableStreams:g.durableStreams,globalTables:i.tables.some(N=>N.shardMode==="global"),queues:u.length>0,relationGraph:gr(i),secrets:g.secrets,vectorStore:i.vectorIndexes.length>0}),y=U.usage,O=U.signals.vectorStore!==!1,z=sn(n),W=z??new Set,X=W.has("lunorash");Hn(i,z,{hasVectors:O,scheduler:y.scheduler||P.length>0,storage:y.storage||m.rules.length>0||Object.keys(zt(i)).length>0,usage:y});const K=b(E(t,"flags.ts")),C=b(E(t,"notify.ts"));return{agents:d,containers:h,crons:P,dataModelContent:ks(i),declaredDependencies:z,dependencies:W,entryCronTriggers:M,env:a,featureUsage:y,hasFlags:K,hasNotify:C,identity:r,platformGate:{...U,diagnostics:[...dn(n,e.target),...U.diagnostics]},queues:u,serverContent:Ds({agents:d,containers:h,env:a,hasAccessFacade:y.access,hasAi:y.ai,hasAnalytics:y.analytics,hasBrowser:y.browser,hasVectors:O,hasFlags:K,hasHyperdrive:y.hyperdrive,hasImages:y.images,hasKv:y.kv,hasNotify:C,hasPayments:y.payments,hasPipelines:y.pipelines,hasR2sql:y.r2sql,hasX402:y.x402,identity:r,queues:u,schema:i,storageRuleBuckets:m.rules.map(N=>N.bucket),useUmbrella:X,workflows:c}),storageRulesMetadata:m,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer||T.usesSandboxFs,useUmbrella:X,workflows:c}},Xt=new Set(["delete","get","head","options","patch","post","put"]),hr=new Set(["handler","stream"]),xr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ht=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),vr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Xt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Er=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||Xt.has(n.getName()))break;s=n.getExpression()}return vr(s)},Sr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(ht.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&ht.has(s.getText()))return!0}return!1},yr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!hr.has(n.getName()))return;const i=Er(s);if(!i||!xr.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&Sr(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Ar=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=yr(i,t);r&&s.push(r)}return s},Nr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ar(i,x(t,n)))}return s},br=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Pr=(e,t)=>{if(!br(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)||_(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Ir=(e,t)=>w(e,t,Pr),wr=new Set(["generateText","streamText"]),Tr=new Set(["messages","prompt","system"]),Cr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],Fr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of Cr)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Or=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Fr(t);if(s!==void 0)return s}},Rr=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Lr=e=>{if(fn(e))return!0;const t=Rr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Dr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!Tr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Lr(s))return!0}return!1},kr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=S(n.getExpression());if(i===void 0||!wr.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(S(c.getExpression())==="tool"&&(a=Or(c),a!==void 0))break;a!==void 0&&s.push({exportName:v(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:Dr(r)})}return s},Mr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...kr(i,x(t,n)))}return s},Kr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},_r=(e,t)=>{if(!Kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},zr=(e,t)=>w(e,t,_r),De=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!o.isSpreadAssignment(s))return!1;const n=ge(s.getExpression());return n===void 0||De(n,t)})}finally{t.delete(e)}},$r=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),i=n===void 0?void 0:ge(n);return i===void 0?{objects:[],opaque:!0}:{objects:[i],opaque:De(i)}},Ur=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&o.isExpression(r)?ge(r):void 0;a===void 0?s=!0:(t.push(a),s||=De(a))}n=i.getExpression()}return{objects:t,opaque:s}},ke=(e,t)=>t?Ur(t):$r(e),Zt=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(o.isSpreadAssignment(s)){const n=ge(s.getExpression());return n===void 0?[]:Zt(n,t)}return o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},qr=e=>e.flatMap(t=>Zt(t,new Set)),Br=new Set(["check","length","max"]),we=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Vr=e=>[e,...e.getDescendants()].filter(t=>we(t)!==void 0),Wr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(Br.has(s.getName()))return!0;t=n}},jr=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=Vr(r),c=i.getName();a.some(u=>we(u)==="any")?t.push(c):a.some(u=>we(u)==="string"&&!Wr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Hr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=k(s);if(n?.visibility!=="public")return;const{objects:i}=ke(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=jr(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Gr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Hr(i,t);r&&s.push(r)}return s},Yr=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Gr(i,x(t,n)))}return s},Ne=e=>e?.getKind()===l.TrueKeyword,Qr=e=>e?.getKind()===l.FalseKeyword,Xr=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Zr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Jr=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&S(t.getExpression())==="scim"),ei=e=>e!==void 0&&o.isCallExpression(e)&&Zr.has(S(e.getExpression())??""),ti=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),si=e=>{const t=A(e,"advanced"),s=A(e,"emailAndPassword"),n=A(e,"session");return{analyzable:!0,disableCsrfCheck:Ne(A(t,"disableCSRFCheck")),emailPasswordEnabled:Ne(A(s,"enabled")),requireEmailVerification:Ne(A(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Jr(A(e,"plugins"))&&ei(A(e,"database")),secureCookiesDisabled:Qr(A(t,"useSecureCookies")),sessionFreshAgeZero:Xr(A(n,"freshAge")),trustedOriginsWildcard:ti(A(e,"trustedOrigins"))}},ni=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),ri=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?si(s):ni();return{exportName:v(e),file:t,line:e.getStartLineNumber(),...i}},ii=(e,t)=>Js(e,t,ri),oi=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},ai=(e,t,s)=>{const n=oi(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!R(i)||_(i))&&!(s.requireUnmodifiedReach===!0&&!gn(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:n}},ci=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=ai(i,t,s);r&&n.push(r)}return n},pe=(e,t,s)=>{const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...ci(r,x(t,i),s))}return n},li=new Set(["content","pdf","scrape","screenshot"]),ui=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:li}),di=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),fi=new Set(["RateLimiter"]),gi=new Set(["extend"]),xt="lunora",pi=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Jt=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Te=e=>e&&o.isObjectLiteralExpression(e)?Jt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},mi=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&qt(t.getBody());return s?Jt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},hi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=S(n.getExpression());i!==void 0&&(di.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])}):gi.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...mi(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=S(n.getExpression());i===void 0||!fi.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])})}return s},xi=(e,t)=>{for(const s of pi){const n=E(t,s);if(!b(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of i.getDescendantsOfKind(l.CallExpression))S(a.getExpression())===xt&&r.push({callee:xt,file:s,line:a.getStartLineNumber(),...Te(a.getArguments()[0])});return r}return[]},vi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Re(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...hi(r,n))}return s.push(...xi(e,ne(t))),s},vt="ctx.containers.",Ei=e=>{if(!e.startsWith(vt))return!1;const t=e.slice(vt.length);return t.length>0&&!t.includes(".")},Si=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:Ei,methods:new Set(["get"])}),yi=new Set(["allow","deny","setAllowed"]),Ai=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Ni=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Ai(e)))return{detail:"enableInternet: true",exportName:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},bi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!yi.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Pi=(e,t)=>Ni(e,t)??bi(e,t),Ii=(e,t)=>w(e,t,Pi),wi=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Ti=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return wi.has(s)?s:void 0},Ci=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=n.getName();t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Fi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Re(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=Ti(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?Ci(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Oi=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ri=new Set(["dbRateLimit","rateLimit"]),Li=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Di=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const n=Oi.get(s);if(n!==void 0)return{callee:s,exportName:v(e),failOpen:Li(e.getArguments()[n]),file:t,limitName:Ri.has(s)?Bt(e):"",line:e.getStartLineNumber()}},ki=(e,t)=>w(e,t,Di),Mi=new Set(["boolean","number","object","string"]),Ki=e=>{const t=e.getName();if(!Mi.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ie(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ie(n.getExpression()))return t},_i=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=Ki(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},zi=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=_i(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},$i=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=k(t);if(s?.kind!=="query")return;const n=en(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},Et=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Ui=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=Et(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=Et(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},qi=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=Ui(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},Bi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=$i(i);r&&s.push(...qi(r,t))}return s},Vi=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Bi(i,x(t,n)))}return s},Wi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ie(t.getExpression())},ji=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Hi=(e,t)=>{if(!Wi(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=ji(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:v(e),file:t,key:i,line:e.getStartLineNumber()}},Gi=(e,t)=>w(e,t,Hi),Yi=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||En(r))return;const a=e.getSourceFile().getFilePath();return Sn(i,e,a)?yn(i,e,a,0,new Set):r},Qi=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Xi=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Zi=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))Qi(a)&&s.push({file:r,indexName:Xi(a),line:a.getStartLineNumber()})}return s},Y=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,es=e=>{const t=e.getArguments()[0],s=Y(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&o.isPropertyAssignment(n)?Y(n.getInitializer()):void 0},Ji=new Set(["delete","get","head","options","patch","post","put"]),eo=new Set(["handler","stream"]),to=new Set(["runAction","runMutation"]),so=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,ts=(e,t)=>{if(!(e===void 0||!o.isObjectBindingPattern(e))){for(const s of e.getElements())if((s.getPropertyNameNode()?.getText()??s.getNameNode().getText())===t){const i=s.getNameNode();return o.isIdentifier(i)?i.getText():void 0}}},St=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?o.isIdentifier(s)?s.getText():void 0:ts(s,"ctx")},yt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&o.isIdentifier(s)?s.getText():void 0:ts(s,"request")},At=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(to.has(a)&&Q(c,t))return a;if(so.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},Nt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Q(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!Q(n.getInitializer(),t))){for(const r of i.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},no=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ro=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return o.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Q(n.getExpression(),t)},io=e=>[...o.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],ss=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:io(s)},oo=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!o.isArrowFunction(n)&&!o.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const i=n.getParent();if(!o.isCallExpression(i))return[];const r=i.getExpression();if(!o.isPropertyAccessExpression(r))return[];const a=r.getExpression();return o.isIdentifier(a)?ss(t,a.getText()):[]}return[]},ao=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(o.isStringLiteral(t))return[t.getLiteralText()];if(!o.isIdentifier(t))return[];const s=e.getSourceFile(),n=ss(s,t.getText());return n.length>0?n:oo(t,s)},bt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return o.isCallExpression(s)&&n.unshift(s),n.some(i=>ro(i,t)&&ao(i).some(r=>no.test(r)))},co=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!eo.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(Ji.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},lo=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Y(e.getArguments()[0]),u=c&&St(c,!0);if(!c||u===void 0||bt(c,yt(c,!0)))return;const d=At(c,u);return d===void 0?void 0:{exportName:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Nt(c,u),sideEffect:d}}const n=co(e);if(n===void 0)return;const i=Y(e.getArguments()[0]),r=i&&St(i,!1);if(!i||r===void 0||bt(i,yt(i,!1)))return;const a=At(i,r);return a===void 0?void 0:{exportName:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Nt(i,r),sideEffect:a}},uo=(e,t)=>w(e,t,lo),fo=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),go=new Set(["append","set"]),ns=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Pt=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>fo.has(S(n.getExpression())??"")&&mn(n,t)),po=(e,t)=>{if(Pt(e,t))return!0;const s=fe(e);return s!==void 0&&Pt(s,t)},Ce=(e,t)=>pn(e,t)&&!po(e,t),mo=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=fe(e);return t!==void 0&&o.isNewExpression(t)&&S(t.getExpression())==="Headers"},ae=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=fe(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Ce(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:ns(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Ce(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=ae(n.getExpression());i!==void 0&&Me(i,t,s)}},rs=(e,t)=>{const s=ae(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=ae(n.getInitializer());i!==void 0&&Me(i,"response-init",t)},ho=(e,t)=>{const s=S(e.getExpression());if(s==="Response")rs(e.getArguments()[1],t);else if(s==="Headers"){const n=ae(e.getArguments()[0]);n!==void 0&&Me(n,"headers-ctor",t)}},xo=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){rs(e.getArguments()[1],t);return}if(go.has(n)&&mo(i)){const r=e.getArguments()[1];r!==void 0&&Ce(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:ns(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},vo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))ho(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))xo(s,t)},Eo=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Y(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return vo(n,{exportName:v(e),relativePath:t,requestName:r.getText(),rows:a}),a},So=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Eo(n,t));return s},yo=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...So(i,x(t,n)))}return s},Ao=new Set(["auth","context.auth","ctx.auth"]),No="userId",bo=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},Po=(e,t)=>{const s=E(t,Yt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(S(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?bo(r):void 0}},It=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Ao.has(e.getExpression().getText())?e:void 0},Io=e=>{if(o.isPropertyAccessExpression(e)&&It(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&It(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},wo=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Io(i);r!==void 0&&n.push({declared:r===No||s.has(r),exportName:v(i),file:t,key:r,line:i.getStartLineNumber()})}return n},To=(e,t)=>{const s=Po(e,t);if(s===void 0)return[];const n=[];for(const i of p(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...wo(r,x(t,i),s))}return n},Co=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=A(s,"key");if(!(!n||!R(n)||_(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Fo=(e,t)=>w(e,t,Co),Oo=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ro=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Oo}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Lo=new Set(["queue","send"]),wt=new Set(["bcc","cc","to"]),Do=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Lo.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},ko=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return wt.has(t.getName())&&R(n)&&!_(n)}if(!o.isPropertyAssignment(t)||!wt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&R(s)&&!_(s)}):!1,Mo=(e,t)=>{const s=Do(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!ko(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},Ko=(e,t)=>w(e,t,Mo),_o=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,zo=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?_o(e):!0,is=(e,t=!1)=>{for(const s of e.getProperties()){if(zo(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||is(n,!0))return!0}return!1},$o=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ht(n))for(const r of Le(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||is(a)))return!0}}return!1},Uo=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=oe(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=oe(a);c!==void 0&&s.push({column:c,strategy:jt(a),table:i})}}return s},qo=(e,t)=>{const s=new Map;for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Ht(i))for(const a of Le(r))for(const c of Uo(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Bo=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=oe(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=oe(u);if(d===void 0)continue;const h=jt(u);h!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:h,table:a})}}return i},Vo=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?k(s):void 0;return n?.receiver?Le(n.receiver).flatMap(i=>Bo(i,e.getName(),t)):[]},Wo=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Vo(c,r))}return s},jo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return D(s)},Ho=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},Go=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return wn(s.getExpression())?s:void 0},Yo=e=>{const t=Go(e),s=t===void 0?void 0:Ho(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>jo(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Qo=e=>e.getVariableDeclarations().flatMap(t=>Yo(t)),Xo=(e,t)=>{const s=E(t,In);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Qo(n)},Zo=new Set(["delete","get","patch"]),Jo=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),ea=new Set(["auth","identity","session","user"]),ta=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),sa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!D(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},na=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},ra=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),ia=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,oa=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>ra(s.getExpression(),t)&&ia(s.getThenStatement())),aa=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Zo.has(i))continue;const r=n.getExpression();if(!(D(r)||o.isPropertyAccessExpression(r)&&D(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},ca=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},la=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>ca(s)==="ctx")),ua=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>ta.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),da=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Jo.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&ea.has(t.getName()))return!0}return la(e)||ua(e)},fa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=k(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=es(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Wt(n.receiver,"use","rls"),a=da(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const h=sa(d);if(h===void 0)continue;const m=na(d);if(m===void 0||c.has(m)||!oa(i,m))continue;const P=aa(i,m);P!==void 0&&(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:P,table:h,usesRls:r,visibility:n.visibility}))}return u},ga=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...fa(c,r))}return s},pa=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ma=new Set(["insert","insertManyUnsafe","patch","replace"]),ha=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ma.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},xa=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},Tt=(e,t)=>{if(o.isPropertyAccessExpression(e)){const s=e.getExpression();return o.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(o.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return o.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&o.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},va=e=>{if(!o.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(o.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let i,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!o.isVariableDeclarationList(c)||c.getDeclarationKind()!==Fs.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(i=u,r=d)}return i},Ea=(e,t)=>{if(Tt(e,t))return!0;const s=va(e);return s!==void 0&&Tt(s,t)},Sa=(e,t,s,n,i)=>{const r=[];for(const a of e.getProperties()){let c,u;if(o.isPropertyAssignment(a)?(c=a.getName(),u=a.getInitializer()):o.isShorthandPropertyAssignment(a)&&(c=a.getName(),u=a.getNameNode()),!(c===void 0||u===void 0||!pa.has(c))&&R(u)&&!_(u)){const d=v(s),h=i(d)===c&&Ea(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...h&&{ownerScoped:!0}})}}return r},ya=(e,t,s)=>{const n=ha(e.getExpression());if(n===void 0)return[];const i=e.getArguments()[1];return i?xa(i,n).flatMap(r=>Sa(r,n,e,t,s)):[]},Aa=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of ya(i,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Na=(e,t,s=[],n=[])=>{const i=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);i.push(...Aa(c,u,d=>r.get(`${u}:${d}`)??{}))}return i},ba=["providerSubscriptionId","state"],Pa=["providerEventId","processedAt"],Ct=(e,t)=>t.every(s=>s in e.shape),Ia=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Ct(t,ba)&&Ct(s,Pa)},wa=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Ta=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ca=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Ta(t.getInitializer()):void 0},Fa=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!wa.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Ca(n):void 0;return{callee:s,exportName:v(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Oa=(e,t)=>w(e,t,Fa),Ra=new Set(["defineQueue","defineWorkflow"]),La=new Set(["run","runAction","runMutation","runQuery"]),Da=new Set(["api","internal"]),ka=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},Ma=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},os=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},as=(e,t)=>e===t||e.startsWith(`${t}.`),cs=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},Ft=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},ls=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Ft(s));return o.isIdentifier(e)&&Ft(e)&&t.push(e),t},Ka=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},_a=e=>{const t=os(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},za=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:_a(e),i=new Set,r=a=>cs(a).some(c=>n.some(u=>as(c.getText(),u)))?!0:ls(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of Ka(a))i.add(u)}return{names:i,prefixes:n}},$a=(e,t)=>cs(e).some(s=>t.prefixes.some(n=>as(s.getText(),n)))?!0:ls(e).some(s=>t.names.has(s.getText())),Ua=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!Da.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},qa=(e,t,s)=>{const n=os(e,0);if(n===void 0)return[];const i=za(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!La.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!$a(u,i))continue;const d=Ua(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:v(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},Ba=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=ka(n);if(i===void 0||!Ra.has(i))continue;const r=Ma(n);r!==void 0&&s.push(...qa(r,i==="defineQueue"?"queue":"workflow",t))}return s},Va=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ba(i,x(t,n)))}return s},Ot={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Rt=new Set(["account","credential","member","passkey","session","user"]),Wa=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ja=e=>{const s=Wa(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Rt.has(s)||Rt.has(n)},Ha=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Ga=(e,t)=>{const{objects:s,opaque:n}=ke(e,t);return qr(s).some(i=>Ha(i))?!0:n?void 0:!1},Ya=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Qa=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},ie={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Xa=e=>{const t=Qa(e),s=t?S(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Ya(t);return{...ie,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ot?{...ie,[Ot[s]]:!0}:ie},Za=e=>{const t={...ie};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=Xa(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Ja=new Set(["insert","insertMany","insertManyUnsafe","replace"]),ec=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Ja.has(t.getName()))return!1;const s=t.getExpression();if(!D(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:ja(i.getLiteralText())},tc=new Set(["create","runAfter","runAt","send","sendBatch"]),sc=new Set(["queues","scheduler","workflows"]),nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!tc.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&sc.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},rc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return D(s)},us=new Set(["generateObject","generateText","streamObject","streamText"]),ic=e=>{const t=S(e.getExpression());return t!==void 0&&us.has(t)},oc=e=>{const t=S(e.getExpression());if(t===void 0||!us.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},ac=new Set(["log","span","trace"]),cc=new Set(["ai"]),lc=new Set(["email","mail"]),uc=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),be=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),dc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),fc=new Set(["every","filter","flatMap","forEach","map","some"]),gc=new Set(["all","allSettled","race"]),pc=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(fc.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&gc.has(n))return t},mc=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(dc.has(t.getKind())){const s=pc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},hc=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},xc=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},vc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!uc.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=xc(n);r&&(t=!0,!mc(r)&&!hc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ec=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),Lt="lunora-advisor-exempt",Sc=/^[\s*/]+/u,yc=/[\w-]/u,Ac=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
6
|
`);for(const n of s.split(`
|
|
7
|
-
`)){const i=n.replace(yc,"");if(!i.startsWith(Lt))continue;const r=i.slice(Lt.length);if(Sc.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Nc=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},bc=(e,t)=>{const s=Nc(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},Pc=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(ec(u)&&(r=!0),nc(u)&&(t=!0),rc(u)&&(i=!0),ic(u)&&(s=!0),oc(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=vc(e);return{callsMail:be(e,lc),emitsEvent:be(e,ac),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||be(e,cc),throwsBareError:Ec(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},Ic=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=k(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Za(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=bc(e,s);return{...r?Pc(r):{},...Ac(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:Ga(s,n.receiver),kind:n.kind,visibility:n.visibility}},wc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Ic(i,t);r&&s.push(r)}return s},Tc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wc(i,x(t,n)))}return s},Cc=new Set(["dbRateLimit","rateLimit"]),Fc=e=>o.isArrowFunction(e)?e.getBody():e,Oc=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Cc.has(s))return;const n=e.getArguments()[2];if(!n)return;const i=A(n,"key");if(!i)return;const r=Fc(i);if(!(!R(r)||_(r)))return{callee:s,exportName:v(e),file:t,limitName:Bt(e),line:e.getStartLineNumber()}},Rc=(e,t)=>w(e,t,Oc),Lc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Dc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Lc.has(t.getName()))return;const s=t.getExpression();if(D(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&D(s.getExpression()))return s.getName()},kc=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&D(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Mc=e=>{let t=G(e)??e;for(;o.isAwaitExpression(t);)t=G(t.getExpression())??t.getExpression();return t},ds=(e,t=!1)=>{const s=Mc(e);if(o.isIdentifier(s)){if(t)return;const n=fe(s);return n===void 0?void 0:ds(n,!0)}if(o.isCallExpression(s))return Dc(s)??kc(s)},Kc=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},_c=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=k(s);if(n?.kind!=="query")return[];const i=es(s);if(i===void 0)return[];const r=n.receiver!==void 0&&an(n.receiver,"output"),a=n.receiver!==void 0&&Wt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Kc(i)){const h=ds(d);h===void 0||c.has(h)||(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:h,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},zc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(..._c(c,r))}return s},$c=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Uc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?k(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Vt(r);if(a===void 0)continue;const c=$c(A(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},qc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Uc(c,r))}return s},ce=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ce(e.getLeft()),s=ce(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Bc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ce(t)!==void 0},Vc=/(?:^|\/)__tests__\//u,Wc=/\.(?:spec|test)$/u,jc=e=>Vc.test(e)||Wc.test(e),Hc=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Gc=(e,t,s)=>Kn(e)?!jc(s)&&_n(Hc(t)):!0,Yc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(Bc(r))continue;const a=ce(r);if(a===void 0)continue;const c=kn(a);if(c===void 0||!Gc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Mn(a)}))}return s},Qc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Yc(i,x(t,n)))}return s},Xc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?k(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Vt(r);if(a===void 0)continue;const c=A(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&R(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Zc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Xc(c,r))}return s},Jc=new Set(["query","unsafe"]),el=e=>{if(!o.isPropertyAccessExpression(e)||!Jc.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},tl=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),sl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",nl=(e,t)=>{if(!el(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!tl(s)))return{exportName:sl(e),file:t,line:s.getStartLineNumber()}},rl=(e,t)=>w(e,t,nl),il=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],ol=e=>{for(const[t,s]of il)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},al=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=ol(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},cl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ll=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:cl,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},ul=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),dl=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,fl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),r==="expiresInSeconds"&&(s=dl(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},gl=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=ul.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},pl=(e,t)=>{const s=gl(e.getExpression());if(s!==void 0)return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...fl(e.getArguments()[s.optionsIndex])}},ml=(e,t)=>w(e,t,pl),hl=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),xl=(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"}),vl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!o.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return ke(e,t).opaque},El=(e,t)=>{const s=[],n=(i,r)=>{const a=i.getInitializer();if(a===void 0||!o.isCallExpression(a))return;const c=k(a);c!==void 0&&vl(a,c.receiver)&&s.push(xl(t,r,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations())n(r,r.getName());return s},yl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...El(i,x(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},Sl=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),me=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),fs=e=>!e.isAny(),Ke=e=>{const t=e.getType();if(!fs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Sl.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},gs=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},ps={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Al=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.`}),Nl={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},_e=(e,t,s,n,i)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,h=d===void 0?i:Al(d),m=c===void 0?h.remediation:`${c} ${h.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${h.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${m}`:m,title:"Procedure exists at runtime but is missing from the generated API"}},bl=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(me(s,t,a)||!gs(r))continue;const c=Ke(r);c!==void 0&&n.push(_e(t,a,c,r.getStartLineNumber(),ps))}return n},Pl=(e,t,s)=>{if(me(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ke(i.getExpression());r!==void 0&&n.push(_e(t,"default",r,i.getStartLineNumber(),ps))}return n},Il=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(me(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!gs(c))continue;const u=Ke(c);u!==void 0&&n.push(_e(t,a,u,r.getStartLineNumber(),Nl))}return n},wl=(e,t,s)=>[...bl(e,t,s),...Pl(e,t,s),...Il(e,t,s)],Tl=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>me(s,t,n.getName())).filter(n=>{const i=n.getInitializer();return i!==void 0&&o.isCallExpression(i)&&o.isPropertyAccessExpression(i.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Cl=({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"}),Fl=(e,t,s)=>{const n=[],i=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...wl(c,u,s)),i.push(...Tl(c,u,s))}const[r]=i;return r!==void 0&&i.every(({declaration:a})=>!fs(a.getType()))&&n.push(Cl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Ol=new Set(["when","where"]),Pe=new Set(["definePolicy","defineShape"]),Rl=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Pe.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return Pe.has(i)?i:void 0}const s=t.getText();return Pe.has(s)?s:void 0},Ll=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,ms=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Ll(e))return"empty-object";if(o.isParenthesizedExpression(e))return ms(e.getExpression())}},ze=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Dl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ze(t)===e),hs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ze(t)===e),kl=e=>{const t=Dl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||hs(e).length>0},Ml=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ze(t)===e),Fe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",Kl=(e,t)=>Fe(e)||Fe(t),_l=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Dt=e=>!Fe(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),zl=(e,t,s)=>{const n=_l.get(e);if(n!==void 0)return Kl(t,s)?n==="positive"?"negative":"positive":Dt(t)||Dt(s)?void 0:n},H=e=>{if(o.isParenthesizedExpression(e))return H(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=zl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=H(e.getLeft()),i=H(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},kt=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},$l=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Ul=e=>o.isReturnStatement(e)?e.getExpression()??e:e,ql=e=>{const t=[];for(const s of hs(e)){const n=H(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Ml(e)){const n=H(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?kt(s.getThenStatement()):kt(s.getElseStatement())??$l(s);i!==void 0&&t.push(Ul(i))}return t},Bl=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},Vl=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!Ol.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&kl(a))for(const c of ql(a)){const u=ms(c);u!==void 0&&i.push({exportName:Bl(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return i},Wl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=Rl(n);i!==void 0&&s.push(...Vl(n,i,t))}return s},jl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Wl(i,x(t,n)))}return s},Hl=new Set(["query","upsert","upsertMany"]),Gl=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(Hl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Yl=(e,t)=>{const s=Gl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=A(n,"namespace");if(!(!i||!R(i)||_(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},Ql=(e,t)=>w(e,t,Yl),Xl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},Zl=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Jl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Xl(a))continue;const c=tn(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Zl(a)})}}return s},eu=".lunora-schema.json",Oe=(e,t)=>{b(e)&&_t(e,"utf8")===t||ws(e,t,"utf8")},tu=(e,t)=>{if(t===""){Ts(e,{force:!0});return}Oe(e,t)},su=e=>{const t=E(e,"package.json");if(b(t))try{const s=JSON.parse(_t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},nu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},ru=e=>{let t=b(e)?e:ne(e);for(;t&&t!==ne(t);){const s=E(t,"tsconfig.json");if(b(s))return s;t=ne(t)}},Mt=e=>e.replaceAll("\\","/"),iu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},le=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Kt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,ou=8,au=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:h}=e;let m=lt(a,i),P=dt(a,i),M=ut(a,i);ft([...m,...P].map(g=>g.filePath)),ft(M.filter(g=>g.stream).map(g=>g.filePath),"http-stream");for(let g=1;;g+=1){const T=Gs({agents:t,functions:m,httpRoutes:M,mutators:P,useUmbrella:d,workflows:h}),F=Ys({agents:t,functions:m,migrations:r,mutators:P,shapes:c,useUmbrella:d,usesSandbox:u});if(g>=ou||Kt(a,s,T)&&Kt(a,n,F))return{apiContent:T,functions:m,functionsContent:F,httpRoutes:M,mutators:P};le(a,s,T),le(a,n,F),m=lt(a,i),P=dt(a,i),M=ut(a,i)}},cu=e=>{const t=ru(e);return t?new ct({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ct({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},nd=(e,t)=>{const s=p(t),n=E(t,"schema.ts");b(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>Mt(c))),r=Mt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},rd=e=>{const t=nu(),s=t?Ae.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=E(n,"schema.ts");if(!b(i))throw new L("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??cu(n);xn(Yi);const a=Dn(r,i,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:h,dependencies:m,entryCronTriggers:P,env:M,featureUsage:g,hasFlags:T,hasNotify:F,identity:U,platformGate:S,queues:O,serverContent:z,storageRulesMetadata:W,usesSandbox:X,useUmbrella:K,workflows:C}=mr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),N=E(n,"_generated"),xs=E(N,"dataModel.ts"),vs=E(N,"server.ts"),Es=E(N,"api.ts"),ys=E(N,"functions.ts");le(r,xs,h),le(r,vs,z);const Z=Pn(r,n),q=zn(r,n),{apiContent:$e,functions:B,functionsContent:Ue,httpRoutes:Ss,mutators:J}=au({agents:c,apiPath:Es,generatedFunctionsPath:ys,lunoraDirectory:n,migrations:Z,project:r,shapes:q,useUmbrella:K,usesSandbox:X,workflows:C}),ee=e.lint===!1?void 0:Rs({adminRoutes:Nr(r,n),aiRawRuns:Ir(r,n),aiToolSideEffects:Mr(r,n),argumentDerivedFetches:zr(r,n),argumentValidators:Yr(r,n),authApiCalls:vn(r,n),authConfigs:ii(r,n),browserUrlAccesses:ui(r,n),configCalls:vi(r,n),containerKeyAccesses:yi(r,n),containerOverrides:Ii(r,n),containers:u,exportSinks:Fi(r,n),staleMigrationImports:al(r,n),failOpenGuards:ki(r,n),flagReads:Vi(r,n),flagSecurityDefaults:Gi(r,n),geoIndexUsages:Zi(r,n),httpActionGuards:uo(r,n),httpHeaderWrites:So(r,n),hyperdriveCalls:An(r,n),identityClaimReads:To(r,n),imageDeliveryUrlAccesses:Fo(r,n),inserts:Nn(r,n),kvKeyAccesses:Ro(r,n,B),mailRecipientAccesses:Ko(r,n),maskProcedures:bn(r,n),maskStrategies:Wo(r,n),mutatorWrites:Xo(r,n),nondeterministicCalls:Tn(r,n),normalizeIdAuthorizations:ga(r,n),notifyCalls:Fn(r,n),notifyConfig:Cn(r,n),mutators:J,ownerFieldWrites:Na(r,n,B,J),unrestrictedWhereBranches:jl(r,n),paymentWebhooks:Oa(r,n),privilegedDispatches:Va(r,n),procedureProtections:Tc(r,n),queries:hn(r,n),queues:O,r2sqlCalls:On(r,n),ratelimitKeySelectors:Rc(r,n),rawRowReturns:zc(r,n),relationLoads:qc(r,n),rlsProcedures:Rn(r,n),schema:a,secretLiterals:Qc(r,n),shapes:q,softDeleteReads:Zc(r,n),sqlInterpolations:rl(r,n),storageKeyAccesses:ll(r,n,B),storageUploads:ml(r,n),vectorNamespaceAccesses:Ql(r,n),workflowCalls:Jl(r,n),workflows:C,wranglerVariables:e.wranglerVariables}),qe=ee===void 0?[]:[...Cs(ee,{source:"static"}),...Fl(r,n,{byName:new Set([...C,...O,...c,...u].map(f=>f.exportName)),byPath:new Set([...B,...J,...q,...Z].map(f=>`${f.filePath}:${f.exportName}`))}),...yl(r,n)],As=Ln(r,n),Be=qo(r,n);iu(q,Be,$o(r,n));const Ns=T?zi(r,n):[],he=S.signals.vectorStore!==!1,j=hl(g,{containerCount:u.length,cronCount:d.length,dependencies:m,hasPaymentTables:Ia(a.tables),queueCount:O.length,storageColumnCount:Object.keys(zt(a)).length,storageRuleCount:W.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:he,workflowCount:C.length}),Ve=t?Ae.now():0,xe=Wn(a,Z.map(f=>f.id)),We=Ms({advisories:qe.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:ee?.procedureProtections??[],agents:c,containers:u,env:M,flagKeys:Ns,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:T,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:F,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:he,hasX402:g.x402,maskMetadata:Be,mutators:J,queues:O,rlsMetadata:As,schema:a,schemaSnapshot:xe,shapes:q,storageRules:W,studioFeatures:j,useUmbrella:K,workflows:C}),je=Ks(q,m.has("@lunora/db"),K),He=_s(u,a.jurisdiction),Ge=zs(C),Ye=$s(c),Qe=Us(O),Xe=qs(d),bs=Bs(j.scheduler),Ze=Vs(a.vectorIndexes),te=Ws(a,K),Je=js(m.has("@lunora/seed")),se=e.apiSpec??"openapi",ve=se==="openapi"||se==="both",Ee=se==="openrpc"||se==="both",et=$n({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:m.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue"),hasGlobal:a.tables.some(f=>$t(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>Ut(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:j.kv,hasNotify:F,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:O.some(f=>f.mode==="push"),hasScheduler:j.scheduler,hasStorage:j.storage,hasVectors:he,hasWorkflow:C.length>0,hasX402:g.x402,identity:U,jurisdiction:a.jurisdiction,tableNames:a.tables.map(f=>f.name),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:ve,wantsOpenRpc:Ee}),tt=su(e.projectRoot),st=Un({functions:B,httpRoutes:Ss,version:tt}),nt=Bn({functions:B,version:tt}),rt=`${JSON.stringify(st,void 0,2)}
|
|
7
|
+
`)){const i=n.replace(Sc,"");if(!i.startsWith(Lt))continue;const r=i.slice(Lt.length);if(yc.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Nc=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},bc=(e,t)=>{const s=Nc(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},Pc=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(ec(u)&&(r=!0),nc(u)&&(t=!0),rc(u)&&(i=!0),ic(u)&&(s=!0),oc(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=vc(e);return{callsMail:be(e,lc),emitsEvent:be(e,ac),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||be(e,cc),throwsBareError:Ec(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},Ic=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=k(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?Za(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=bc(e,s);return{...r?Pc(r):{},...Ac(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:Ga(s,n.receiver),kind:n.kind,visibility:n.visibility}},wc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Ic(i,t);r&&s.push(r)}return s},Tc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wc(i,x(t,n)))}return s},Cc=new Set(["dbRateLimit","rateLimit"]),Fc=e=>o.isArrowFunction(e)?e.getBody():e,Oc=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!Cc.has(s))return;const n=e.getArguments()[2];if(!n)return;const i=A(n,"key");if(!i)return;const r=Fc(i);if(!(!R(r)||_(r)))return{callee:s,exportName:v(e),file:t,limitName:Bt(e),line:e.getStartLineNumber()}},Rc=(e,t)=>w(e,t,Oc),Lc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Dc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Lc.has(t.getName()))return;const s=t.getExpression();if(D(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&D(s.getExpression()))return s.getName()},kc=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&D(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Mc=e=>{let t=G(e)??e;for(;o.isAwaitExpression(t);)t=G(t.getExpression())??t.getExpression();return t},ds=(e,t=!1)=>{const s=Mc(e);if(o.isIdentifier(s)){if(t)return;const n=fe(s);return n===void 0?void 0:ds(n,!0)}if(o.isCallExpression(s))return Dc(s)??kc(s)},Kc=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},_c=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=k(s);if(n?.kind!=="query")return[];const i=es(s);if(i===void 0)return[];const r=n.receiver!==void 0&&an(n.receiver,"output"),a=n.receiver!==void 0&&Wt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Kc(i)){const h=ds(d);h===void 0||c.has(h)||(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:h,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},zc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(..._c(c,r))}return s},$c=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Uc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?k(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Vt(r);if(a===void 0)continue;const c=$c(A(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},qc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Uc(c,r))}return s},ce=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ce(e.getLeft()),s=ce(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Bc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ce(t)!==void 0},Vc=/(?:^|\/)__tests__\//u,Wc=/\.(?:spec|test)$/u,jc=e=>Vc.test(e)||Wc.test(e),Hc=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Gc=(e,t,s)=>Kn(e)?!jc(s)&&_n(Hc(t)):!0,Yc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(Bc(r))continue;const a=ce(r);if(a===void 0)continue;const c=kn(a);if(c===void 0||!Gc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Mn(a)}))}return s},Qc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Yc(i,x(t,n)))}return s},Xc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?k(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Vt(r);if(a===void 0)continue;const c=A(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&R(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},Zc=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Xc(c,r))}return s},Jc=new Set(["query","unsafe"]),el=e=>{if(!o.isPropertyAccessExpression(e)||!Jc.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},tl=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),sl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",nl=(e,t)=>{if(!el(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!tl(s)))return{exportName:sl(e),file:t,line:s.getStartLineNumber()}},rl=(e,t)=>w(e,t,nl),il=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],ol=e=>{for(const[t,s]of il)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},al=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=ol(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},cl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ll=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:cl,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},ul=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),dl=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,fl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),r==="expiresInSeconds"&&(s=dl(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},gl=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=ul.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},pl=(e,t)=>{const s=gl(e.getExpression());if(s!==void 0)return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...fl(e.getArguments()[s.optionsIndex])}},ml=(e,t)=>w(e,t,pl),hl=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),xl=(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"}),vl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!o.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return ke(e,t).opaque},El=(e,t)=>{const s=[],n=(i,r)=>{const a=i.getInitializer();if(a===void 0||!o.isCallExpression(a))return;const c=k(a);c!==void 0&&vl(a,c.receiver)&&s.push(xl(t,r,a.getStartLineNumber()))};for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations())n(r,r.getName());return s},Sl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n);i!==void 0&&s.push(...El(i,x(t,n)))}return s.toSorted((n,i)=>n.cacheKey.localeCompare(i.cacheKey))},yl=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),me=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),fs=e=>!e.isAny(),Ke=e=>{const t=e.getType();if(!fs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:yl.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},gs=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},ps={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},Al=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.`}),Nl={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},_e=(e,t,s,n,i)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,h=d===void 0?i:Al(d),m=c===void 0?h.remediation:`${c} ${h.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${h.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${m}`:m,title:"Procedure exists at runtime but is missing from the generated API"}},bl=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(me(s,t,a)||!gs(r))continue;const c=Ke(r);c!==void 0&&n.push(_e(t,a,c,r.getStartLineNumber(),ps))}return n},Pl=(e,t,s)=>{if(me(s,t,"default"))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ke(i.getExpression());r!==void 0&&n.push(_e(t,"default",r,i.getStartLineNumber(),ps))}return n},Il=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(me(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!gs(c))continue;const u=Ke(c);u!==void 0&&n.push(_e(t,a,u,r.getStartLineNumber(),Nl))}return n},wl=(e,t,s)=>[...bl(e,t,s),...Pl(e,t,s),...Il(e,t,s)],Tl=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>me(s,t,n.getName())).filter(n=>{const i=n.getInitializer();return i!==void 0&&o.isCallExpression(i)&&o.isPropertyAccessExpression(i.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Cl=({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"}),Fl=(e,t,s)=>{const n=[],i=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...wl(c,u,s)),i.push(...Tl(c,u,s))}const[r]=i;return r!==void 0&&i.every(({declaration:a})=>!fs(a.getType()))&&n.push(Cl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Ol=new Set(["when","where"]),Pe=new Set(["definePolicy","defineShape"]),Rl=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Pe.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return Pe.has(i)?i:void 0}const s=t.getText();return Pe.has(s)?s:void 0},Ll=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,ms=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Ll(e))return"empty-object";if(o.isParenthesizedExpression(e))return ms(e.getExpression())}},ze=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Dl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ze(t)===e),hs=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ze(t)===e),kl=e=>{const t=Dl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||hs(e).length>0},Ml=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ze(t)===e),Fe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",Kl=(e,t)=>Fe(e)||Fe(t),_l=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Dt=e=>!Fe(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),zl=(e,t,s)=>{const n=_l.get(e);if(n!==void 0)return Kl(t,s)?n==="positive"?"negative":"positive":Dt(t)||Dt(s)?void 0:n},H=e=>{if(o.isParenthesizedExpression(e))return H(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=zl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=H(e.getLeft()),i=H(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},kt=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},$l=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Ul=e=>o.isReturnStatement(e)?e.getExpression()??e:e,ql=e=>{const t=[];for(const s of hs(e)){const n=H(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Ml(e)){const n=H(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?kt(s.getThenStatement()):kt(s.getElseStatement())??$l(s);i!==void 0&&t.push(Ul(i))}return t},Bl=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},Vl=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!Ol.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&kl(a))for(const c of ql(a)){const u=ms(c);u!==void 0&&i.push({exportName:Bl(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return i},Wl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=Rl(n);i!==void 0&&s.push(...Vl(n,i,t))}return s},jl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Wl(i,x(t,n)))}return s},Hl=new Set(["query","upsert","upsertMany"]),Gl=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(Hl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Yl=(e,t)=>{const s=Gl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=A(n,"namespace");if(!(!i||!R(i)||_(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},Ql=(e,t)=>w(e,t,Yl),Xl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},Zl=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Jl=(e,t)=>{const s=[];for(const n of p(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Xl(a))continue;const c=tn(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Zl(a)})}}return s},eu=".lunora-schema.json",Oe=(e,t)=>{b(e)&&_t(e,"utf8")===t||ws(e,t,"utf8")},tu=(e,t)=>{if(t===""){Ts(e,{force:!0});return}Oe(e,t)},su=e=>{const t=E(e,"package.json");if(b(t))try{const s=JSON.parse(_t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},nu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},ru=e=>{let t=b(e)?e:ne(e);for(;t&&t!==ne(t);){const s=E(t,"tsconfig.json");if(b(s))return s;t=ne(t)}},Mt=e=>e.replaceAll("\\","/"),iu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},le=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Kt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,ou=8,au=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:h}=e;let m=lt(a,i),P=dt(a,i),M=ut(a,i);ft([...m,...P].map(g=>g.filePath)),ft(M.filter(g=>g.stream).map(g=>g.filePath),"http-stream");for(let g=1;;g+=1){const T=Gs({agents:t,functions:m,httpRoutes:M,mutators:P,useUmbrella:d,workflows:h}),F=Ys({agents:t,functions:m,migrations:r,mutators:P,shapes:c,useUmbrella:d,usesSandbox:u});if(g>=ou||Kt(a,s,T)&&Kt(a,n,F))return{apiContent:T,functions:m,functionsContent:F,httpRoutes:M,mutators:P};le(a,s,T),le(a,n,F),m=lt(a,i),P=dt(a,i),M=ut(a,i)}},cu=e=>{const t=ru(e);return t?new ct({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ct({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},nd=(e,t)=>{const s=p(t),n=E(t,"schema.ts");b(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>Mt(c))),r=Mt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},rd=e=>{const t=nu(),s=t?Ae.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),i=E(n,"schema.ts");if(!b(i))throw new L("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??cu(n);xn(Yi);const a=Dn(r,i,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:h,dependencies:m,entryCronTriggers:P,env:M,featureUsage:g,hasFlags:T,hasNotify:F,identity:U,platformGate:y,queues:O,serverContent:z,storageRulesMetadata:W,usesSandbox:X,useUmbrella:K,workflows:C}=mr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),N=E(n,"_generated"),xs=E(N,"dataModel.ts"),vs=E(N,"server.ts"),Es=E(N,"api.ts"),Ss=E(N,"functions.ts");le(r,xs,h),le(r,vs,z);const Z=Pn(r,n),q=zn(r,n),{apiContent:$e,functions:B,functionsContent:Ue,httpRoutes:ys,mutators:J}=au({agents:c,apiPath:Es,generatedFunctionsPath:Ss,lunoraDirectory:n,migrations:Z,project:r,shapes:q,useUmbrella:K,usesSandbox:X,workflows:C}),ee=e.lint===!1?void 0:Rs({adminRoutes:Nr(r,n),aiRawRuns:Ir(r,n),aiToolSideEffects:Mr(r,n),argumentDerivedFetches:zr(r,n),argumentValidators:Yr(r,n),authApiCalls:vn(r,n),authConfigs:ii(r,n),browserUrlAccesses:ui(r,n),configCalls:vi(r,n),containerKeyAccesses:Si(r,n),containerOverrides:Ii(r,n),containers:u,exportSinks:Fi(r,n),staleMigrationImports:al(r,n),failOpenGuards:ki(r,n),flagReads:Vi(r,n),flagSecurityDefaults:Gi(r,n),geoIndexUsages:Zi(r,n),httpActionGuards:uo(r,n),httpHeaderWrites:yo(r,n),hyperdriveCalls:An(r,n),identityClaimReads:To(r,n),imageDeliveryUrlAccesses:Fo(r,n),inserts:Nn(r,n),kvKeyAccesses:Ro(r,n,B),mailRecipientAccesses:Ko(r,n),maskProcedures:bn(r,n),maskStrategies:Wo(r,n),mutatorWrites:Xo(r,n),nondeterministicCalls:Tn(r,n),normalizeIdAuthorizations:ga(r,n),notifyCalls:Fn(r,n),notifyConfig:Cn(r,n),mutators:J,ownerFieldWrites:Na(r,n,B,J),unrestrictedWhereBranches:jl(r,n),paymentWebhooks:Oa(r,n),privilegedDispatches:Va(r,n),procedureProtections:Tc(r,n),queries:hn(r,n),queues:O,r2sqlCalls:On(r,n),ratelimitKeySelectors:Rc(r,n),rawRowReturns:zc(r,n),relationLoads:qc(r,n),rlsProcedures:Rn(r,n),schema:a,secretLiterals:Qc(r,n),shapes:q,softDeleteReads:Zc(r,n),sqlInterpolations:rl(r,n),storageKeyAccesses:ll(r,n,B),storageUploads:ml(r,n),vectorNamespaceAccesses:Ql(r,n),workflowCalls:Jl(r,n),workflows:C,wranglerVariables:e.wranglerVariables}),qe=ee===void 0?[]:[...Cs(ee,{source:"static"}),...Fl(r,n,{byName:new Set([...C,...O,...c,...u].map(f=>f.exportName)),byPath:new Set([...B,...J,...q,...Z].map(f=>`${f.filePath}:${f.exportName}`))}),...Sl(r,n)],As=Ln(r,n),Be=qo(r,n);iu(q,Be,$o(r,n));const Ns=T?zi(r,n):[],he=y.signals.vectorStore!==!1,j=hl(g,{containerCount:u.length,cronCount:d.length,dependencies:m,hasPaymentTables:Ia(a.tables),queueCount:O.length,storageColumnCount:Object.keys(zt(a)).length,storageRuleCount:W.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:he,workflowCount:C.length}),Ve=t?Ae.now():0,xe=Wn(a,Z.map(f=>f.id)),We=Ms({advisories:qe.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:ee?.procedureProtections??[],agents:c,containers:u,env:M,flagKeys:Ns,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:T,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:F,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:he,hasX402:g.x402,maskMetadata:Be,mutators:J,queues:O,rlsMetadata:As,schema:a,schemaSnapshot:xe,shapes:q,storageRules:W,studioFeatures:j,useUmbrella:K,workflows:C}),je=Ks(q,m.has("@lunora/db"),K),He=_s(u,a.jurisdiction),Ge=zs(C),Ye=$s(c),Qe=Us(O),Xe=qs(d),bs=Bs(j.scheduler),Ze=Vs(a.vectorIndexes),te=Ws(a,K),Je=js(m.has("@lunora/seed")),se=e.apiSpec??"openapi",ve=se==="openapi"||se==="both",Ee=se==="openrpc"||se==="both",et=$n({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:m.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue"),hasGlobal:a.tables.some(f=>$t(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>Ut(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:j.kv,hasNotify:F,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:O.some(f=>f.mode==="push"),hasScheduler:j.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:j.storage,hasVectors:he,hasWorkflow:C.length>0,hasX402:g.x402,identity:U,jurisdiction:a.jurisdiction,tableNames:a.tables.map(f=>f.name),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:ve,wantsOpenRpc:Ee}),tt=su(e.projectRoot),st=Un({functions:B,httpRoutes:ys,version:tt}),nt=Bn({functions:B,version:tt}),rt=`${JSON.stringify(st,void 0,2)}
|
|
8
8
|
`,it=`${JSON.stringify(nt,void 0,2)}
|
|
9
|
-
`,ot=qn(st),at=Vn(nt),
|
|
9
|
+
`,ot=qn(st),at=Vn(nt),Se=E(n,eu),Ps=b(Se),ye=[];if(!e.dryRun){b(N)||Is(N,{recursive:!0});const f=($,V)=>{Oe(E(N,$),V),ye.push($)},I=($,V)=>{tu(E(N,$),V),V!==""&&ye.push($)};f("app.ts",et),f("dataModel.ts",h),f("api.ts",$e),f("server.ts",z),f("functions.ts",Ue),f("shard.ts",We),f("crons.ts",Xe),f("vectors.ts",Ze),f("drizzle.global.ts",te.global),f("drizzle.shard.ts",te.shard),I("containers.ts",He),I("workflows.ts",Ge),I("agents.ts",Ye),I("queues.ts",Qe),I("scheduler.ts",bs),I("seed.ts",Je),I("collections.ts",je),I("openapi.json",ve?rt:""),I("openapi.ts",ve?ot:""),I("openrpc.json",Ee?it:""),I("openrpc.ts",Ee?at:""),(!Ps||e.updateSchemaBaseline===!0)&&Oe(Se,Os(xe))}if(t){const f=Ae.now(),I=Math.round(f-s),$=Math.round(Ve-s),V=Math.round(f-Ve);console.error(`@lunora/codegen: codegen took ${I.toString()}ms (discovery ${$.toString()}ms, emit ${V.toString()}ms)`)}return{advisories:qe,advisorContext:ee,agents:c,containers:u,cronTriggers:[...new Set([...Hs(d),...P])],generated:{agents:Ye,api:$e,app:et,collections:je,containers:He,crons:Xe,dataModel:h,drizzleGlobal:te.global,drizzleShard:te.shard,functions:Ue,openApi:rt,openApiModule:ot,openRpc:it,openRpcModule:at,queues:Qe,seed:Je,server:z,shard:We,vectors:Ze,workflows:Ge},migrations:Z,outputDirectory:N,platformDiagnostics:y.diagnostics,queues:O,schemaSnapshot:xe,schemaSnapshotPath:Se,workflows:C,writtenFiles:ye}};export{eu as SCHEMA_SNAPSHOT_FILENAME,cu as createCodegenProject,ru as findTsconfig,nd as refreshCodegenProject,rd as runCodegen};
|
package/dist/packem_shared/{buildOpenApiDocument-D_-3ZGH1.mjs → buildOpenApiDocument-DCGde3iO.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-BuaY_1hY.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
|
|
2
2
|
`,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
|
package/dist/packem_shared/{discoverFunctions-C9O2RBTz.mjs → discoverFunctions-DRf4ucil.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as x}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as P,lunoraRelativePath as E}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{b as f,c as b}from"./classify-procedure-call-BIlyTUBD.mjs";import{Node as s,SyntaxKind as A}from"ts-morph";import{p as N,r as m,a as v}from"./parse-validator-tdRHHDzh.mjs";import{u as y}from"./unwrap-handler-return-
|
|
1
|
+
import{s as x}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as P,lunoraRelativePath as E}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{b as f,c as b}from"./classify-procedure-call-BIlyTUBD.mjs";import{Node as s,SyntaxKind as A}from"ts-morph";import{p as N,r as m,a as v}from"./parse-validator-tdRHHDzh.mjs";import{u as y}from"./unwrap-handler-return-Da99uRXX.mjs";const F=i=>{const e=i.getArguments()[0];if(!e||!s.isObjectLiteralExpression(e))return"unknown";const t=e.getProperty("handler");if(!t||!s.isPropertyAssignment(t))return"unknown";const r=t.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":y(r)},z=i=>{const e=i.getArguments()[0];return!e||!(s.isArrowFunction(e)||s.isFunctionExpression(e))?"unknown":y(e)},C=i=>{let e={};for(const t of f(i)){if(t.name!=="input")continue;const r=t.call.getArguments()[0],n=r!==void 0&&s.isExpression(r)?m(r):void 0;n!==void 0&&(e={...v(n),...e})}return e},S=i=>{const e=f(i).find(r=>r.name==="output");if(!e)return;const t=e.call.getArguments()[0];return t&&s.isExpression(t)?N(t):void 0},u=(i,e)=>{const t=i.getProperty(e);if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},d=(i,e)=>{const t=i.getProperty(e);if(t===void 0||!s.isPropertyAssignment(t))return;const r=t.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},O=i=>{const e=i.getProperty("cache");if(e===void 0||!s.isPropertyAssignment(e))return;const t=e.getInitializer();if(t===void 0||!s.isObjectLiteralExpression(t))return;const r=u(t,"scope"),n=d(t,"maxAge"),o=d(t,"staleWhileRevalidate"),a=u(t,"tag"),c=u(t,"vary"),g={...n===void 0?{}:{maxAge:n},...r==="private"||r==="public"?{scope:r}:{},...o===void 0?{}:{staleWhileRevalidate:o},...a===void 0?{}:{tag:a},...c===void 0?{}:{vary:c}};return Object.keys(g).length===0?void 0:g},L=i=>{if(i===void 0||!s.isObjectLiteralExpression(i))return{};const e=O(i),t=i.getProperty("rest");return t!==void 0&&s.isPropertyAssignment(t)?{...e===void 0?{}:{cache:e},rest:t.getInitializer()?.getText()==="true"}:e===void 0?{}:{cache:e}},I=i=>{const e=f(i).find(t=>t.name==="expose");return e?L(e.call.getArguments()[0]):void 0},T=i=>{const e=i.getArguments()[0];if(!e||!s.isObjectLiteralExpression(e))return{};const t=e.getProperty("args");if(!t||!s.isPropertyAssignment(t))return{};const r=t.getInitializer(),n=r===void 0?void 0:m(r);return n===void 0?{}:v(n)},k=8,l=(i,e=0)=>{if(e>k)return;if(s.isCallExpression(i))return i;if(s.isParenthesizedExpression(i)||s.isAsExpression(i)||s.isSatisfiesExpression(i)||s.isNonNullExpression(i))return l(i.getExpression(),e+1);if(!s.isIdentifier(i)&&!s.isPropertyAccessExpression(i))return;const t=i.getSymbol()?.getValueDeclaration();return t?p(t,e+1):void 0},p=(i,e)=>{if(s.isVariableDeclaration(i)||s.isPropertyAssignment(i)){const t=i.getInitializer();return t?l(t,e):void 0}if(s.isShorthandPropertyAssignment(i)){const t=i.getValueSymbol()?.getValueDeclaration();return t?p(t,e+1):void 0}if(s.isBindingElement(i)){const t=i.getPropertyNameNode()?.getText()??i.getName(),o=i.getFirstAncestorByKind(A.VariableDeclaration)?.getInitializer()?.getType().getProperty(t)?.getValueDeclaration();return o?p(o,e+1):void 0}},V=i=>{const e=i.getNameNode();if(s.isObjectBindingPattern(e)){const n=[];for(const o of e.getElements()){const a=l(o.getNameNode());a&&n.push([o.getName(),a])}return n}const t=i.getInitializer(),r=t&&(s.isCallExpression(t)?t:l(t));return r?[[i.getName(),r]]:[]},w=i=>{const e=b(i);if(e){if(e.receiver){const t=I(e.receiver),r=S(e.receiver);return{args:C(e.receiver),...t?{expose:t}:{},kind:e.kind,...r?{output:r}:{},returnType:z(i),visibility:e.visibility}}return e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",visibility:e.visibility}:{args:T(i),kind:e.kind,returnType:F(i),visibility:e.visibility}}},h=(i,e,t)=>{const r=w(i);if(r)return{args:r.args,exportName:e,filePath:t,kind:r.kind,returnType:r.returnType,...r.output?{output:r.output}:{},visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},D=(i,e)=>{const t=[];for(const r of i.getExportAssignments()){if(r.isExportEquals())continue;const n=l(r.getExpression()),o=n?h(n,"default",e):void 0;o&&t.push(o)}return t},j=(i,e)=>{const t=[];for(const r of i.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations())for(const[o,a]of V(n)){const c=h(a,o,e);c&&t.push(c)}return t.push(...D(i,e)),t},R=i=>{const e=new Map;for(const t of i){const r=x(t.filePath),n=e.get(r);if(n&&n!==t.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${t.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[n,t.filePath],status:500});e.set(r,t.filePath)}},W=(i,e)=>{const t=P(e),r=[];for(const n of t){const o=i.getSourceFile(n)??i.addSourceFileAtPath(n),a=E(e,n);r.push(...j(o,a))}return r.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),R(r),r};export{W as default};
|
package/dist/packem_shared/{discoverHttpRoutes-S81Iv_iB.mjs → discoverHttpRoutes-_ME7hLcW.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{p as m,a as l}from"./parse-validator-tdRHHDzh.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{u as f}from"./unwrap-handler-return-
|
|
1
|
+
import{Node as i}from"ts-morph";import{p as m,a as l}from"./parse-validator-tdRHHDzh.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./listLunoraSourceFiles-D4xthUf-.mjs";import{u as f}from"./unwrap-handler-return-Da99uRXX.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),g=new Set(["body","params","searchParams"]),E=new Set(["handler","stream"]),v=r=>{const e=r.getArguments()[0];if(e&&i.isStringLiteral(e))return e.getLiteralValue()},x=r=>{const e=r.getArguments()[0];return e&&i.isObjectLiteralExpression(e)?l(e):{}},P=r=>{if(!i.isCallExpression(r))return;const e=r.getExpression();if(!i.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!i.isIdentifier(n)||n.getText()!=="httpRoute")return;const s=v(r);return s===void 0?void 0:{method:o.toUpperCase(),path:s}},S=(r,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},n=r.getExpression();if(!i.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;i.isCallExpression(s);){const a=s.getExpression();if(!i.isPropertyAccessExpression(a))break;const c=a.getName();if(u.has(c))break;if(g.has(c)){const p=x(s);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=s.getArguments()[0];p&&i.isExpression(p)&&(o.output=m(p))}s=a.getExpression()}const t=P(s);if(t)return o.method=t.method,o.path=t.path,o},A=r=>{const e=r.getArguments()[0];return!e||!(i.isArrowFunction(e)||i.isFunctionExpression(e))?"unknown":f(e)},T=(r,e,o,n)=>{const s=e.getName();if(!E.has(s))return;const t=S(r,s);if(!(t?.method===void 0||t.path===void 0))return{body:t.body,exportName:o,filePath:n,method:t.method,params:t.params,path:t.path,searchParams:t.searchParams,stream:t.stream,...t.stream?{chunkType:A(r)}:{},...t.output?{output:t.output}:{}}},b=(r,e)=>{const o=[];for(const n of r.getVariableStatements())if(n.isExported())for(const s of n.getDeclarations()){const t=s.getInitializer();if(!t||!i.isCallExpression(t))continue;const a=t.getExpression();if(!i.isPropertyAccessExpression(a))continue;const c=T(t,a,s.getName(),e);c&&o.push(c)}return o},F=(r,e)=>{const o=d(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),a=h(e,s);n.push(...b(t,a))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{F as default};
|
|
@@ -15,7 +15,7 @@ import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as
|
|
|
15
15
|
/**
|
|
16
16
|
* R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.
|
|
17
17
|
*/
|
|
18
|
-
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],In=mt,Cn=new Map(In.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),
|
|
18
|
+
readonly r2sql: import("@lunora/bindings/r2sql").R2SqlClient;`,tier:"action"}},{contextProperty:"scheduler",key:"scheduler",moduleSpecifier:"@lunora/scheduler"},{contextProperty:"storage",key:"storage",moduleSpecifier:"@lunora/storage"},{appMethod:{configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},contextProperty:"vectors",key:"vectors",moduleSpecifier:"@lunora/bindings/vectors"},{contextProperty:"workflows",key:"workflows",moduleSpecifier:"@lunora/workflow"}],In=mt,Cn=new Map(In.flatMap(e=>e.serverCtxField?[[e.key,e.serverCtxField]]:[])),da=mt.flatMap(e=>"appMethod"in e?[{appMethod:e.appMethod,key:e.key}]:[]),gt=/^(?:"(?:[^"\\]|\\(?:["\\/bfnrt]|u[0-9A-Fa-f]{4}))*"|'[^'\\]*'|-?\d+(?:\.\d+)?|true|false|null)$/u,Dn=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),ft=e=>e.column!==void 0,Ln=(e,t)=>{switch(e){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
|
|
19
19
|
`;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
|
|
20
20
|
`;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
|
|
21
21
|
`;case"null":return`if (${t} !== null) return DEFER;
|
|
@@ -49,7 +49,7 @@ ${yt("source")}${r.pre}return { ${r.entries} };
|
|
|
49
49
|
${t}
|
|
50
50
|
`:"";return`export interface Insert_${e.name} {
|
|
51
51
|
_id?: Id<"${e.name}">;
|
|
52
|
-
_creationTime?: number;${n}}`},Je="schema",
|
|
52
|
+
_creationTime?: number;${n}}`},Je="schema",ua=e=>{for(const u of e.tables)f(u.name,"table name");const t=e.tables.map(u=>`"${u.name}"`).join(" | ")||"never",n=e.tables.filter(u=>u.extensionKey===void 0).map(u=>`"${u.name}"`).join(" | ")||"never",r=e.tables.map(u=>{const l=Object.entries(u.shape).map(([x,v])=>{const $=q(x);if(v.kind==="optional"){const T=v.inner?N(v.inner):"unknown";return` ${$}?: ${T};`}return` ${$}: ${N(v)};`}).join(`
|
|
53
53
|
`),b=l?`
|
|
54
54
|
${l}
|
|
55
55
|
`:"",R=u.commitOrdered===!0?`
|
|
@@ -224,7 +224,7 @@ ${r}
|
|
|
224
224
|
export const httpStreams: HttpStreamsRef = {
|
|
225
225
|
${a}
|
|
226
226
|
};
|
|
227
|
-
`,body:r}},
|
|
227
|
+
`,body:r}},ha=e=>{const{agents:t=[],functions:n,httpRoutes:r=[],mutators:a=[],useUmbrella:o=!1,workflows:i=[]}=e,s=oe(o),c=[...n.filter(O=>O.visibility!=="internal"),...lr(t,n),...cr(a,n)],d=n.filter(O=>O.visibility==="internal"),h=ut(c),g=ut(d),y=dr(r),u=`${h}
|
|
228
228
|
${g}
|
|
229
229
|
${y.body}`,l=ze(u),b=l.length>0?`
|
|
230
230
|
import type { ${l.join(", ")} } from "./dataModel.js";
|
|
@@ -243,7 +243,7 @@ export const internal = anyApi as unknown as InternalApiTypes;
|
|
|
243
243
|
${v.block}${y.block}`,T=[...$.includes("FunctionReference<")?["FunctionReference"]:[],...y.block===""?[]:["HttpStreamRef"]],H=T.length>0?`import type { ${T.join(", ")} } from "${s.client}";
|
|
244
244
|
`:"";return Rt(`${S}import { anyApi } from "${s.client}";
|
|
245
245
|
${H}${v.importLine}${b}
|
|
246
|
-
${$}`,o)},
|
|
246
|
+
${$}`,o)},pa=e=>e?`${S}import { createSeedClient as createSeedClientBase } from "@lunora/seed";
|
|
247
247
|
import type { SeedClient, SeedClientOptions } from "@lunora/seed";
|
|
248
248
|
|
|
249
249
|
import schema from "../schema.js";
|
|
@@ -260,7 +260,7 @@ import type { InsertModel } from "./dataModel.js";
|
|
|
260
260
|
* const { posts } = await seed.posts((x) => x([10, 20]));
|
|
261
261
|
*/
|
|
262
262
|
export const createSeedClient = (options?: SeedClientOptions): SeedClient<InsertModel> => createSeedClientBase<InsertModel>(schema, options);
|
|
263
|
-
`:"",
|
|
263
|
+
`:"",ma=(e,t,n=!1)=>{if(e.length===0||!t)return"";const r=oe(n),a=c=>c.table===void 0?"Row":`Doc<${JSON.stringify(c.table)}> & Row`,o=e.map(c=>{f(c.exportName,"shape export name");const d=a(c),h=L(xe(c.args),c.filePath),g=Object.keys(c.args).length>0,y=g?` args: ${h};`:` args?: ${h};`,u=g?`(args: ${h}) => void`:`(args?: ${h}) => void`,l=`${c.exportName}CollectionOptions`;return`/** Options for the \`${c.exportName}\` shape binding. */
|
|
264
264
|
export interface ${Ve(l)} {
|
|
265
265
|
${y}
|
|
266
266
|
/**
|
|
@@ -366,7 +366,7 @@ ${i}
|
|
|
366
366
|
`);return` ${Y(i)}: {
|
|
367
367
|
${s}
|
|
368
368
|
},`}).join(`
|
|
369
|
-
`),types:n}},gr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=se(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},
|
|
369
|
+
`),types:n}},gr=(e,t=[])=>{const n=new Set;for(const r of e.tables)for(const a of Object.values(r.shape)){const o=se(a);o.kind==="storage"&&typeof o.bucket=="string"&&o.bucket!==""&&n.add(o.bucket)}for(const r of t)r!==""&&r!=="default"&&n.add(r);return["default",...[...n].toSorted((r,a)=>r.localeCompare(a))]},ga=({agents:e=[],containers:t=[],env:n,hasAccessFacade:r=!1,hasAi:a=!1,hasAnalytics:o=!1,hasBrowser:i=!1,hasVectors:s=!0,hasFlags:c=!1,hasHyperdrive:d=!1,hasImages:h=!1,hasKv:g=!1,hasNotify:y=!1,hasPayments:u=!1,hasPipelines:l=!1,hasR2sql:b=!1,hasX402:R=!1,identity:x,queues:v=[],schema:$,storageRuleBuckets:T=[],useUmbrella:H=!1,workflows:O=[]}={})=>{const C=oe(H),k=gr($??{tables:[]},T).map(p=>JSON.stringify(p)).join(" | "),P=a?`import type { LunoraAi } from "@lunora/ai";
|
|
370
370
|
`:"",M=a?`
|
|
371
371
|
readonly ai: LunoraAi;`:"",ie=u?`import type { LunoraPayment } from "@lunora/payment";
|
|
372
372
|
`:"",le=u?`
|
|
@@ -730,7 +730,7 @@ export const definePolicy = createPolicyDsl<DataModel, Relations${Be}>();
|
|
|
730
730
|
export const v = vBase as unknown as Omit<typeof vBase, "id"> & {
|
|
731
731
|
id: <T extends TableName>(table: T) => ColumnValidator<IdOfTable<T>, IdOfTable<T>>;
|
|
732
732
|
};
|
|
733
|
-
`},fr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${A(n.filePath)}:${n.exportName}`);return t},
|
|
733
|
+
`},fr=e=>{const t={connect:[],disconnect:[],init:[],reactor:[],whisper:[]};for(const n of e)n.lifecycle&&t[n.lifecycle].push(`${A(n.filePath)}:${n.exportName}`);return t},fa=e=>{const{agents:t=[],functions:n,migrations:r=[],mutators:a=[],shapes:o=[],useUmbrella:i=!1,usesSandbox:s=!1}=e,c=n.length>0,d=oe(i),{dispatchBody:h,importBlock:g,installBlock:y,migrationBody:u,mutatorPaths:l,shapeBody:b}=pr(n,r,a,o),R=sr(t,n),x=ir(s,n),v=[R.lines,x.lines].filter(w=>w.length>0).join(`
|
|
734
734
|
`);let $=h;v.length>0&&($=h.length>0?`${h.trimEnd()}
|
|
735
735
|
${v}
|
|
736
736
|
`:`
|
|
@@ -1068,7 +1068,7 @@ const LUNORA_FLAG_KEYS: ReadonlyArray<{ key: string; type: "boolean" | "number"
|
|
|
1068
1068
|
const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
|
|
1069
1069
|
const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
|
|
1070
1070
|
`,configField:`
|
|
1071
|
-
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,
|
|
1071
|
+
pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:I("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:E,ba=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(o=>(f(o.exportName,`container export "${o.exportName}"`),f(o.className,`container class "${o.className}"`),`/** Container DO for the \`${o.exportName}\` definition (binding \`${o.bindingName}\`). */
|
|
1072
1072
|
export class ${o.className} extends LunoraContainer {
|
|
1073
1073
|
public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
|
|
1074
1074
|
super(ctx, env, ${o.exportName}, "${o.exportName}"${n});
|
|
@@ -1102,7 +1102,7 @@ ${r}`},Fr=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[]
|
|
|
1102
1102
|
const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
|
|
1103
1103
|
${n}
|
|
1104
1104
|
];
|
|
1105
|
-
`}},
|
|
1105
|
+
`}},ya=e=>{if(e.length===0)return"";const t=e.map(r=>(f(r.exportName,`workflow export "${r.exportName}"`),f(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition (binding \`${r.bindingName}\`). */
|
|
1106
1106
|
export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
|
|
1107
1107
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1108
1108
|
super(ctx, env, ${r.exportName}, "${r.exportName}");
|
|
@@ -1130,7 +1130,7 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
|
|
|
1130
1130
|
/** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
|
|
1131
1131
|
type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
|
|
1132
1132
|
|
|
1133
|
-
${t}`},
|
|
1133
|
+
${t}`},wa=e=>{if(e.length===0)return"";const n=e.filter(s=>s.voice).length>0,r=e.map(s=>{f(s.exportName,`agent export "${s.exportName}"`),f(s.className,`agent class "${s.className}"`);const c=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent (binding \`${s.bindingName}\`). */
|
|
1134
1134
|
export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
|
|
1135
1135
|
public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
|
|
1136
1136
|
super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
|
|
@@ -1158,7 +1158,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
|
|
|
1158
1158
|
|
|
1159
1159
|
import { ${a} } from "../agents.js";
|
|
1160
1160
|
|
|
1161
|
-
${r}`},
|
|
1161
|
+
${r}`},ka=e=>{const t=e.filter(a=>a.mode==="push");if(t.length===0)return"";for(const a of t)f(a.exportName,`queue export "${a.exportName}"`);const n=t.map(a=>a.exportName).join(", "),r=t.map(a=>` ${JSON.stringify(a.name)}: { definition: ${a.exportName}, exportName: ${JSON.stringify(a.exportName)} },`).join(`
|
|
1162
1162
|
`);return`${S}/**
|
|
1163
1163
|
* Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
|
|
1164
1164
|
* composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
|
|
@@ -1218,7 +1218,7 @@ const ${e}: ${t} = ${JSON.stringify(r,void 0,4)};
|
|
|
1218
1218
|
? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
|
|
1219
1219
|
: x402Stub;
|
|
1220
1220
|
`,configField:`
|
|
1221
|
-
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Hr=(e,t,n,r,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],
|
|
1221
|
+
x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:I("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},Hr=(e,t,n,r,a)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...a?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]],xa=({advisories:e=[],advisorProcedures:t=[],agents:n=[],containers:r=[],env:a,flagKeys:o=[],hasAccessFacade:i=!1,hasAi:s=!1,hasAnalytics:c=!1,hasBrowser:d=!1,hasFlags:h=!1,hasHyperdrive:g=!1,hasImages:y=!1,hasKv:u=!1,hasNotify:l=!1,hasPayments:b=!1,hasPipelines:R=!1,hasR2sql:x=!1,hasVectors:v=!0,hasX402:$=!1,maskMetadata:T,mutators:H=[],queues:O=[],rlsMetadata:C,schema:k,schemaSnapshot:P,shapes:M=[],storageRules:ie,studioFeatures:le,useUmbrella:Z=!1,workflows:V=[]})=>{const D=oe(Z),ee=H.length>0,w=M.length>0,Ae=P===void 0?"":$n(P),F=P===void 0?"":`
|
|
1222
1222
|
/** Structural schema snapshot + its content hash, recorded in the shard's \`__lunora_schema_history\` ledger on cold start so the studio can show a schema-version timeline and diff any two versions. */
|
|
1223
1223
|
const LUNORA_SCHEMA_SNAPSHOT: { hash: string; json: string } = { hash: ${JSON.stringify(Tn(P))}, json: ${JSON.stringify(Ae)} };
|
|
1224
1224
|
`,ce=P===void 0?"":", schemaSnapshot: LUNORA_SCHEMA_SNAPSHOT",{build:de,configField:Oe,contextField:Ie,stub:Ce}=$r(s),ue=Ir(i),G=Tr(u),_=Nr(h,D.flags),J=Cr(o,h,D.flags),te=Ar(l),he=Or(a),z=Dr(c),j=Lr(y),W=Er(g),U=_r(d),B=Pr(x),ne=Mr(R),{build:De,contextField:ve,importLines:Se,specs:pe}=qr(O),{build:Le,contextField:Ee,importLines:Re,specs:me}=Fr(r,k.jurisdiction),{build:_e,contextField:Pe,importLines:$e,specs:Me}=Br(V),{build:Fe,contextField:ge,importLines:fe,specs:Be}=jr(n),{build:qe,configField:je,contextField:be,imports:ye,stub:Ze}=Kr(b),{build:p,configField:We,imports:Te,stub:re}=Qr($),Ot=e,It=t,et=C??{policies:[],roles:[]},Ct=T??{columns:[]},Dt=ie??{rules:[]},Lt=le??{analytics:!1,auth:!1,containers:!1,flags:!1,kv:!1,mail:!1,notifications:!1,payments:!1,queues:!1,scheduler:!1,storage:!1,vectors:!1,workflows:!1},{constant:Et,override:_t}=Wr(V),{constant:Pt,override:Mt}=Ur(O),K=v&&k.vectorIndexes.length>0,tt=new Set(k.tables.filter(m=>typeof m.shardMode=="object"&&m.shardMode.kind==="shardBy").map(m=>m.name)),Ne=K&&k.vectorIndexes.some(m=>tt.has(m.table)),we=k.tables.some(m=>m.shardMode==="global"),Ue=k.tables.some(m=>Nn(m)),nt=k.tables.some(m=>An(m)),ae=k.tables.some(m=>m.externalSource!==void 0),rt=k.tables.some(m=>m.memory===!0),Ke=k.tables.some(m=>m.shardMode!=="global"&&m.searchIndexes.length>0);if(nt&&Ue)throw new X("INTERNAL",'lunora codegen: mixing `.global()` (D1) and `.global({ backend: "hyperdrive" })` tables in one app is not supported yet — use a single global backend.');const Qe=k.tables.length>0,Ft=br(k),Bt=wr(k),qt=Sr(k),jt=yr(k),at=kr(k),ot=Hr(K,V.length>0,O.length>0,h,Ke);w&&ot.push("WhereInput");const st=Rr(we),Wt=w?`
|
|
@@ -1298,7 +1298,7 @@ assertShapesDeclareReadPolicies(LUNORA_SHAPES, ${JSON.stringify(it)}, (schema as
|
|
|
1298
1298
|
hyperdriveGlobal?: (env: Record<string, unknown>, request?: { cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; userId?: string }) => DatabaseWriterLike | undefined;`:"",Jt=ae?`
|
|
1299
1299
|
sourceClient?: (env: Record<string, unknown>, binding: string) => { query: <Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) => Promise<Row[]> } | undefined;`:"",zt='throw new Error("ctx.db.<globalTable>: no global backend configured. Pass `d1` or `hyperdriveGlobal` to createShardDO().");',Yt='throw new Error("ctx.vectors: no vectors configured. Pass `vectors` to createShardDO().");',Xt='throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO().");',Zt='throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO().");',en=we?I("globalDbStub: DatabaseWriterLike",zt,["aggregate","count","delete","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","normalizeId","patch","query","rank","rankPage","replace"],{sync:["normalizeId","query"]}):"",tn=K?I("vectorsStub: VectorSearchLike",Yt,["deleteByIds","getByIds","query","upsert","upsertNow"]):"",nn=Ne?`
|
|
1300
1300
|
const vectorShardKey = this.currentShardKey();
|
|
1301
|
-
`:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",an
|
|
1301
|
+
`:"",rn=Ne?"namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey, ":"",an=`, { ${["deferAfterCommit: (work) => this.deferAfterCommit(work)",...Ne?["namespace: vectorShardKey === ROOT_SHARD_NAME ? undefined : vectorShardKey",`shardedIndexNames: [${k.vectorIndexes.filter(m=>tt.has(m.table)).map(m=>JSON.stringify(m.name)).join(", ")}]`]:[]].join(", ")} }`,on=K?`
|
|
1302
1302
|
let vectors: VectorSearchLike;
|
|
1303
1303
|
let onWrite: WriteHook | undefined;
|
|
1304
1304
|
|
|
@@ -1454,7 +1454,14 @@ ${nn}
|
|
|
1454
1454
|
// never what changed in them, so it costs one small read per poll tick
|
|
1455
1455
|
// for the whole shard — and a tick whose answer omits a shape's table
|
|
1456
1456
|
// skips that shape's membership drain entirely.
|
|
1457
|
-
|
|
1457
|
+
// Named local, not an inline object literal — same reason as the
|
|
1458
|
+
// dispatch path and \`readGlobalShapeRows\`: \`bookmark\` is not declared
|
|
1459
|
+
// on the narrower Hyperdrive thunk's \`request\` type, and an inline
|
|
1460
|
+
// literal trips an excess-property error (TS2353) that makes the
|
|
1461
|
+
// emitted \`shard.ts\` uncompilable for every Hyperdrive-global app with
|
|
1462
|
+
// a \`defineShape\`. The Hyperdrive factory simply never reads it.
|
|
1463
|
+
const globalRequest = { ...this.globalCdcOptions(config.cdc ?? false), bookmark: this.getInboundBookmark() };
|
|
1464
|
+
const globalDb: DatabaseWriterLike = ${He}?.(env, globalRequest) ?? globalDbStub;
|
|
1458
1465
|
|
|
1459
1466
|
return globalDb.cdcChangedTables?.(sinceSeq, { cursorOnly });
|
|
1460
1467
|
}
|
|
@@ -2207,8 +2214,12 @@ ${Q("headroom ?? this.transactionHeadroom()")}
|
|
|
2207
2214
|
// an absent row falling through to the \`.global()\` D1 twin, though that
|
|
2208
2215
|
// branch is already unreachable here: \`adminWriter\` is built without a
|
|
2209
2216
|
// \`globalDb\`, so a miss throws \`NOT_FOUND\` either way.
|
|
2217
|
+
// \`hard\` is set only by the BULK delete arm, which needs the row gone
|
|
2218
|
+
// from the physical table for its next batch's scan to make progress.
|
|
2219
|
+
// A single-row \`writeRow\` delete never carries it, so it keeps the
|
|
2220
|
+
// table's declared \`.softDelete()\` behaviour.
|
|
2210
2221
|
if (args.op === "delete") {
|
|
2211
|
-
await writer.delete(args.id ?? "", args.table);
|
|
2222
|
+
await writer.delete(args.id ?? "", args.table, { hard: args.hard === true });
|
|
2212
2223
|
|
|
2213
2224
|
return { id: args.id ?? null, op: "delete" };
|
|
2214
2225
|
}
|
|
@@ -2577,7 +2588,7 @@ ${n}
|
|
|
2577
2588
|
`:""].join("");return`${S}import { ${c.join(", ")} } from "${n.serverDrizzle}";
|
|
2578
2589
|
${h}
|
|
2579
2590
|
${d}
|
|
2580
|
-
`},
|
|
2591
|
+
`},va=(e,t=!1)=>{const n=e.tables.filter(a=>a.shardMode==="global"),r=e.tables.filter(a=>a.shardMode!=="global");return{global:L(ht(n,t),Je),shard:L(ht(r,t),Je)}},Sa=e=>e?`${S}/**
|
|
2581
2592
|
* The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
|
|
2582
2593
|
* forward it — wrangler binds only what the entry exports:
|
|
2583
2594
|
*
|
|
@@ -2587,7 +2598,7 @@ ${d}
|
|
|
2587
2598
|
* forwards this module for you whenever it exists.
|
|
2588
2599
|
*/
|
|
2589
2600
|
export { SchedulerDO } from "@lunora/scheduler";
|
|
2590
|
-
`:"",
|
|
2601
|
+
`:"",Ra=e=>{const t=new Map;for(const i of e){const s=t.get(i.cron);s?s.push(i):t.set(i.cron,[i])}const n=[...t.keys()].map(i=>` ${JSON.stringify(i)},`).join(`
|
|
2591
2602
|
`),r=n.length>0?`
|
|
2592
2603
|
${n}
|
|
2593
2604
|
`:"",a=[...t.entries()].map(([i,s])=>{const c=s.map(d=>{const h=d.workflow?`workflow: ${JSON.stringify(d.workflow.binding)}`:`functionPath: ${JSON.stringify(d.functionPath)}`;return` { name: ${JSON.stringify(d.name)}, ${h}, args: ${JSON.stringify(d.args)} },`}).join(`
|
|
@@ -2621,7 +2632,7 @@ export const LUNORA_CRON_TRIGGERS: ReadonlyArray<string> = [${r}];
|
|
|
2621
2632
|
* looks up \`event.cron\` here and dispatches every job in the list.
|
|
2622
2633
|
*/
|
|
2623
2634
|
export const LUNORA_CRONS: Record<string, ReadonlyArray<LunoraCronJob>> = {${o}};
|
|
2624
|
-
`}
|
|
2635
|
+
`},$a=e=>{const t=[...e].toSorted((r,a)=>r.name.localeCompare(a.name)).map(r=>{const a=[`name: ${JSON.stringify(r.name)}`,`table: ${JSON.stringify(r.table)}`];return r.field!==void 0&&a.push(`field: ${JSON.stringify(r.field)}`),r.dimensions!==void 0&&a.push(`dimensions: ${JSON.stringify(r.dimensions)}`),r.metric!==void 0&&a.push(`metric: ${JSON.stringify(r.metric)}`),r.metadata!==void 0&&a.push(`metadata: ${JSON.stringify(r.metadata)}`),` { ${a.join(", ")} },`}).join(`
|
|
2625
2636
|
`),n=t.length>0?`
|
|
2626
2637
|
${t}
|
|
2627
2638
|
`:"";return`${S}/**
|
|
@@ -2645,4 +2656,4 @@ export interface LunoraVectorIndex {
|
|
|
2645
2656
|
* \`createWorker({ vectorIntrospector })\` to back the studio's vector browser.
|
|
2646
2657
|
*/
|
|
2647
2658
|
export const LUNORA_VECTOR_INDEXES: ReadonlyArray<LunoraVectorIndex> = [${n}];
|
|
2648
|
-
`}
|
|
2659
|
+
`},Ta=e=>[...new Set(e.map(t=>t.cron))];export{da as A,In as C,S as G,er as U,ha as a,ma as b,ba as c,Ra as d,wa as e,ua as f,va as g,fa as h,Sa as i,ga as j,xa as k,$a as l,ya as m,Ta as n,yr as o,ka as p,pa as q};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as w,G as
|
|
1
|
+
import{A as w,G as y}from"./emit-BuaY_1hY.mjs";const k=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[k(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},N=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],L=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasSourcedTables?[' private sourceClientFactory?: NonNullable<ShardConfig["sourceClient"]>;']:[],...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${a}"]>>): this {
|
|
3
3
|
this.shardExtras.${a} = factory as NonNullable<ShardConfig["${a}"]>;
|
|
4
4
|
|
|
@@ -52,7 +52,12 @@ import{A as w,G as k}from"./emit-CTDEkEXh.mjs";const y=e=>`has${e.charAt(0).toUp
|
|
|
52
52
|
this.shardSelector = selector;
|
|
53
53
|
|
|
54
54
|
return this;
|
|
55
|
-
}`,...e.
|
|
55
|
+
}`,...e.hasSourcedTables?[` /** Resolve the SQL client a \`.source(...)\` table's ingest poll reads from, given the wrangler Hyperdrive binding it named. Build it with \`@lunora/hyperdrive\`'s \`createHyperdrive\` plus your driver adapter. REQUIRED for a sourced table: without it every poll tick records "no sourceClient resolved for binding" and the table stays empty. */
|
|
56
|
+
public sourceClient(factory: (env: Env, binding: string) => ReturnType<NonNullable<ShardConfig["sourceClient"]>>): this {
|
|
57
|
+
this.sourceClientFactory = factory as NonNullable<ShardConfig["sourceClient"]>;
|
|
58
|
+
|
|
59
|
+
return this;
|
|
60
|
+
}`]:[],...e.hasStorage?[` /** Wire R2 storage — backs \`ctx.storage\` (incl. multi-bucket) and the studio file browser, from one declaration. */
|
|
56
61
|
public storage(declaration: StorageDeclaration<Env>): this {
|
|
57
62
|
this.storageDeclaration = declaration;
|
|
58
63
|
|
|
@@ -129,7 +134,7 @@ import{A as w,G as k}from"./emit-CTDEkEXh.mjs";const y=e=>`has${e.charAt(0).toUp
|
|
|
129
134
|
? {
|
|
130
135
|
scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
|
|
131
136
|
}
|
|
132
|
-
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
137
|
+
: {}),`]:[],...e.hasSourcedTables?[" ...(this.sourceClientFactory === undefined ? {} : { sourceClient: this.sourceClientFactory }),"]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
133
138
|
${a.join(`
|
|
134
139
|
`)}
|
|
135
140
|
`:""},B=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
@@ -384,7 +389,7 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
|
|
|
384
389
|
storageUpload: (key: string, body: ArrayBuffer, opts?: { bucket?: string; contentType?: string; sha256?: string }) => pick(opts?.bucket).upload(key, body, opts),
|
|
385
390
|
};
|
|
386
391
|
}
|
|
387
|
-
`:""
|
|
392
|
+
`:"",H=e=>e?`
|
|
388
393
|
/**
|
|
389
394
|
* Adapt the raw D1 binding to \`@lunora/d1\`'s \`D1Exec\` (reads via \`all\`, writes via \`run\`, and — when the binding exposes it — several writes in one round trip via \`batch\`).
|
|
390
395
|
*
|
|
@@ -619,7 +624,7 @@ const buildGlobalCdcApplier =
|
|
|
619
624
|
|
|
620
625
|
return request.changes.length;
|
|
621
626
|
};
|
|
622
|
-
`:""
|
|
627
|
+
`:"",$=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],"LunoraConfig",...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),F=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=N(t),n=B(t),i=a?` let auth: LunoraAuth | null = null;
|
|
623
628
|
let authInit: Promise<void> | null = null;
|
|
624
629
|
`:"",o=a?`
|
|
625
630
|
const initAuth = async (env: Env): Promise<void> => {
|
|
@@ -680,7 +685,7 @@ ${u.map(p=>` { agent: lunoraAgentDefinitions.${p.exportName}, binding
|
|
|
680
685
|
`:"",f=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
681
686
|
public build(): ComposedApp {
|
|
682
687
|
return this.assemble();
|
|
683
|
-
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${
|
|
688
|
+
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${y}${I(t).join(`
|
|
684
689
|
`)}
|
|
685
690
|
|
|
686
691
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
@@ -708,7 +713,7 @@ interface ComposedApp extends LunoraWorker {
|
|
|
708
713
|
* first request so per-isolate singletons are built once.
|
|
709
714
|
*/
|
|
710
715
|
class AppBuilder<Env extends object> {
|
|
711
|
-
${
|
|
716
|
+
${L(t).join(`
|
|
712
717
|
`)}
|
|
713
718
|
|
|
714
719
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
@@ -798,7 +803,7 @@ ${n.join(`
|
|
|
798
803
|
return options;
|
|
799
804
|
}
|
|
800
805
|
}
|
|
801
|
-
${
|
|
806
|
+
${H(t.hasGlobal)}
|
|
802
807
|
/**
|
|
803
808
|
* Shape of the project's root \`lunora.config.*\`.
|
|
804
809
|
*
|
|
@@ -829,5 +834,5 @@ interface LunoraConfig<Env extends object = object> {
|
|
|
829
834
|
const defineApp = <Env extends object>(): AppBuilder<Env> => new AppBuilder<Env>();
|
|
830
835
|
|
|
831
836
|
export { AppBuilder, defineApp };
|
|
832
|
-
export type { ${
|
|
837
|
+
export type { ${$(t)} };
|
|
833
838
|
`};export{F as emitApp};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Node as u,SyntaxKind as f}from"ts-morph";import{posix as y}from"node:path";const j=/\bany\b(?!\s*(?:\?\s*)?:)/u,R=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,k=e=>j.test(e.replaceAll(R,"")),w="/_generated/",U=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},C=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,E=e=>{for(const t of e.getAncestors())if(u.isModuleDeclaration(t)){const n=C.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},D=new WeakMap,L=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=D.get(n.compilerSymbol);return r===void 0&&(r=new Map,D.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},x=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),O=(e,t,n)=>e.getModuleSpecifierValue()===t&&x(e,n)?n:void 0,$=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},P=(e,t,n)=>{if(!x(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:L(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},h=/^\.\.?(?:$|\/)/u,q=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),B=(e,t)=>{const n=t.getModuleSpecifierValue();if(!h.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:q.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${y.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=y.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},F=(e,t,n)=>{const r=E(t);for(const s of e.getImportDeclarations()){const i=r===void 0?$(s,t)??P(s,t,n):O(s,r,n);if(i!==void 0)return{exportName:i,specifier:B(e,s)??s.getModuleSpecifierValue()}}},K=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),g={kind:"verbatim"},m={kind:"expand"},V=new Set([f.ClassDeclaration,f.EnumDeclaration,f.EnumMember,f.InterfaceDeclaration,f.TypeAliasDeclaration]),W=e=>E(e)!==void 0||u.isExportable(e)&&e.isExported(),I=(e,t,n)=>{const r=e.getSourceFile();if(r.getSymbol()===void 0&&E(e)===void 0||!V.has(e.getKind()))return g;const s=r.getFilePath();if(s.includes(w))return g;if(s===n)return m;const i=u.isEnumMember(e)?e.getParent():e;if(!u.hasName(i))return m;const o=F(t.getSourceFile(),i,i.getName());return o===void 0?W(i)?g:m:K(o.specifier,t)?m:{kind:"qualify",qualified:o}},N=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1;for(const a of[s,r].flatMap(c=>c?.getDeclarations()??[])){const c=I(a,t,n);if(c.kind==="qualify"&&i.has(a))return c;o||=c.kind!=="verbatim"}return o?m:g},G=(e,t,n)=>{const r=u.isPropertySignature(e)||u.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return g;let s=!1;for(const i of[r,...r.getDescendantsOfKind(f.TypeReference)].filter(o=>u.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const a of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const c=I(a,t,n);if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?m:g},X=/^[A-Za-z_$][\w$]*$/u,H=e=>X.test(e)?e:JSON.stringify(e),M=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},p=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,b=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),N(e,t,n).kind!=="verbatim"||M(e).some(s=>b(s,t,n,r))?!0:p(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>G(i,t,n).kind!=="verbatim")?!0:b(s.getTypeAtLocation(t),t,n,r)):!1),Y=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(u.isPropertySignature(n)||u.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},J=32,z=8,Q=(e,t,n,r,s,i)=>{const o=e.getArrayElementType(),a=o?i(o,t,n,r,s):void 0;if(a!==void 0)return o?.isUnion()?`(${a})[]`:`${a}[]`},Z=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getUnionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(c)}return o.join(" | ")},ee=(e,t,n,r,s,i)=>{if(!p(e))return;const o=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),l=Y(a,c),_=l&&c.isUnion()?c.getUnionTypes().filter(v=>!v.isUndefined()):[c],T=[];for(const v of _){const A=i(v,t,n,r+1,s);if(A===void 0)return;T.push(A)}o.push(`${H(a.getName())}${l?"?":""}: ${T.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},te=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},ne=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>u.isClassDeclaration(t)||u.isClassExpression(t)),S=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>J)return!0;const i=new Set(r).add(e);if(M(e).some(l=>S(l,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return S(o,t,n+1,i,s);if(U(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(l=>l?.getDeclarations()??[]).some(l=>u.isClassDeclaration(l)||u.isClassExpression(l)))return!0;const c=p(e)&&e.getProperties().some(l=>S(l.getTypeAtLocation(t),t,n+1,i,s));return c||s.add(e),c},re=(e,t,n,r,s,i,o)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const l=o(c,n,r,s+1,i);if(l===void 0)return;a.push(l)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},se=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>u.isEnumDeclaration(t)||u.isEnumMember(t)),d=(e,t,n,r,s)=>{if(r>z||s.has(e))return;const i=N(e,t,n);if(i.kind==="verbatim"&&!b(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!ne(e)){if(e.isEnumLiteral())return te(e);if(i.kind==="qualify"&&!se(e)){const a=re(i.qualified,e,t,n,r,o,d);if(a!==void 0)return a}return e.isArray()?Q(e,t,n,r,o,d):e.isUnion()?Z(e,t,n,r,o,d):ee(e,t,n,r,o,d)}},ae=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let n=t.getReturnType();const s=(n.getSymbol()??n.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=n.getTypeArguments()[0];a&&(n=a)}const i=n.getText(e);if(!i||i==="any"||i==="never"||k(i)||S(n,e,0,new Set))return"unknown";const o=e.getSourceFile().getFilePath();return b(n,e,o)?d(n,e,o,0,new Set)??"unknown":i};export{d as e,k as i,b as r,ae as u};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.199",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,8 +46,8 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.144",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.124",
|
|
51
51
|
"@lunora/container": "1.0.0-alpha.52",
|
|
52
52
|
"@lunora/errors": "1.0.0-alpha.39",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.32",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Node as l,SyntaxKind as f}from"ts-morph";import{posix as A}from"node:path";const j=/\bany\b(?!\s*(?:\?\s*)?:)/u,R=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,k=e=>j.test(e.replaceAll(R,"")),w="/_generated/",U=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},C=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,D=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=C.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},y=new WeakMap,L=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=y.get(n.compilerSymbol);return r===void 0&&(r=new Map,y.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},N=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),O=(e,t,n)=>e.getModuleSpecifierValue()===t&&N(e,n)?n:void 0,$=(e,t)=>{const n=e.getDefaultImport();if(n===void 0)return;const r=n.getSymbol();return(r?.getAliasedSymbol()??r)?.getDeclarations().includes(t)===!0?"default":void 0},P=(e,t,n)=>{if(!N(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:L(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},h=/^\.\.?(?:$|\/)/u,q=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),B=(e,t)=>{const n=t.getModuleSpecifierValue();if(!h.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:q.get(r.getExtension());if(r===void 0||s===void 0)return;const o=`${A.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,i=A.relative(e.getDirectoryPath(),o);return i.startsWith(".")?i:`./${i}`},K=(e,t,n)=>{const r=D(t);for(const s of e.getImportDeclarations()){const o=r===void 0?$(s,t)??P(s,t,n):O(s,r,n);if(o!==void 0)return{exportName:o,specifier:B(e,s)??s.getModuleSpecifierValue()}}},V=(e,t)=>Object.keys(t.getProject().getCompilerOptions().paths??{}).some(n=>{const r=n.indexOf("*");return r===-1?e===n:e.startsWith(n.slice(0,r))&&e.endsWith(n.slice(r+1))}),g={kind:"verbatim"},d={kind:"expand"},F=new Set([f.ClassDeclaration,f.EnumDeclaration,f.EnumMember,f.InterfaceDeclaration,f.TypeAliasDeclaration]),x=(e,t,n)=>{const r=e.getSourceFile();if(r.getSymbol()===void 0&&D(e)===void 0||!F.has(e.getKind()))return g;const s=r.getFilePath();if(s.includes(w))return g;if(s===n)return d;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return d;const i=K(t.getSourceFile(),o,o.getName());return i===void 0?g:V(i.specifier,t)?d:{kind:"qualify",qualified:i}},I=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),o=new Set((r??s)?.getDeclarations());let i=!1;for(const a of[s,r].flatMap(c=>c?.getDeclarations()??[])){const c=x(a,t,n);if(c.kind==="qualify"&&o.has(a))return c;i||=c.kind!=="verbatim"}return i?d:g},W=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return g;let s=!1;for(const o of[r,...r.getDescendantsOfKind(f.TypeReference)].filter(i=>l.isTypeReference(i))){const i=o.getTypeName().getSymbol();for(const a of(i?.getAliasedSymbol()??i)?.getDeclarations()??[]){const c=x(a,t,n);if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?d:g},G=/^[A-Za-z_$][\w$]*$/u,X=e=>G.test(e)?e:JSON.stringify(e),M=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},E=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,b=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),I(e,t,n).kind!=="verbatim"||M(e).some(s=>b(s,t,n,r))?!0:E(e)?e.getProperties().some(s=>s.getDeclarations().some(o=>W(o,t,n).kind!=="verbatim")?!0:b(s.getTypeAtLocation(t),t,n,r)):!1),H=(e,t)=>{const n=e.getValueDeclaration()??e.getDeclarations()[0];return n&&(l.isPropertySignature(n)||l.isPropertyDeclaration(n))&&n.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},Y=32,J=8,z=(e,t,n,r,s,o)=>{const i=e.getArrayElementType(),a=i?o(i,t,n,r,s):void 0;if(a!==void 0)return i?.isUnion()?`(${a})[]`:`${a}[]`},Q=(e,t,n,r,s,o)=>{const i=[];for(const a of e.getUnionTypes()){const c=o(a,t,n,r,s);if(c===void 0)return;i.push(c)}return i.join(" | ")},Z=(e,t,n,r,s,o)=>{if(!E(e))return;const i=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=H(a,c),_=u&&c.isUnion()?c.getUnionTypes().filter(v=>!v.isUndefined()):[c],T=[];for(const v of _){const p=o(v,t,n,r+1,s);if(p===void 0)return;T.push(p)}i.push(`${X(a.getName())}${u?"?":""}: ${T.join(" | ")}`)}return i.length>0?`{ ${i.join("; ")} }`:"{}"},ee=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},te=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),S=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>Y)return!0;const o=new Set(r).add(e);if(M(e).some(u=>S(u,t,n+1,o,s)))return!0;const i=e.getArrayElementType();if(i!==void 0)return S(i,t,n+1,o,s);if(U(e))return s.add(e),!1;if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0||[e.getSymbol(),e.getAliasSymbol()].flatMap(u=>u?.getDeclarations()??[]).some(u=>l.isClassDeclaration(u)||l.isClassExpression(u)))return!0;const c=E(e)&&e.getProperties().some(u=>S(u.getTypeAtLocation(t),t,n+1,o,s));return c||s.add(e),c},ne=(e,t,n,r,s,o,i)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=i(c,n,r,s+1,o);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},re=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),m=(e,t,n,r,s)=>{if(r>J||s.has(e))return;const o=I(e,t,n);if(o.kind==="verbatim"&&!b(e,t,n))return e.getText(t);const i=new Set(s).add(e);if(!te(e)){if(e.isEnumLiteral())return ee(e);if(o.kind==="qualify"&&!re(e)){const a=ne(o.qualified,e,t,n,r,i,m);if(a!==void 0)return a}return e.isArray()?z(e,t,n,r,i,m):e.isUnion()?Q(e,t,n,r,i,m):Z(e,t,n,r,i,m)}},oe=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let n=t.getReturnType();const s=(n.getSymbol()??n.getAliasSymbol())?.getName();if(s==="Promise"||s==="AsyncIterable"||s==="AsyncIterableIterator"||s==="AsyncGenerator"){const a=n.getTypeArguments()[0];a&&(n=a)}const o=n.getText(e);if(!o||o==="any"||o==="never"||k(o)||S(n,e,0,new Set))return"unknown";const i=e.getSourceFile().getFilePath();return b(n,e,i)?m(n,e,i,0,new Set)??"unknown":o};export{m as e,k as i,b as r,oe as u};
|