@lunora/codegen 1.0.0-alpha.207 → 1.0.0-alpha.209

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.
@@ -1,4 +1,4 @@
1
- import{A as w,G as y}from"./emit-Ba1jzhVh.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} */
1
+ import{A as w,G as y}from"./emit-CE9-QEca.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
 
@@ -0,0 +1 @@
1
+ import{Node as l,SyntaxKind as g}from"ts-morph";import{lunoraRelativePath as L}from"./listLunoraSourceFiles-DsxeRYvh.mjs";import{posix as D}from"node:path";let S,v;const Ae=e=>{const t=S,n=[];S=n;try{return{erased:n,value:e()}}finally{S=t}},Te=e=>{S?.push(...e)},j=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},w=(e,t)=>{S?.push({exportName:j(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},Ne=e=>{v!==void 0&&w(v,e)},xe=(e,t)=>{const n=v;v=e;try{return t()}finally{v=n}},k=(e,t)=>{const n=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${n}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${n}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},De=(e,t)=>{const n=new Map;for(const r of e){const s=k(r,L(t,r.filePath));n.set(s.cacheKey,s)}return[...n.values()].toSorted((r,s)=>r.cacheKey.localeCompare(s.cacheKey))},P=/\bany\b(?!\s*(?:\?\s*)?:)/u,U=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,O=e=>P.test(e.replaceAll(U,"")),K="/_generated/",B=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},F=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,T=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=F.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},h=new WeakMap,V=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=h.get(n.compilerSymbol);return r===void 0&&(r=new Map,h.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},_=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),W=(e,t,n)=>e.getModuleSpecifierValue()===t&&_(e,n)?n:void 0,q=(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},G=(e,t,n)=>{if(!_(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:V(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},X=/^\.\.?(?:$|\/)/u,H=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),Y=(e,t)=>{const n=t.getModuleSpecifierValue();if(!X.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:H.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${D.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=D.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},J=(e,t,n)=>{const r=T(t);for(const s of e.getImportDeclarations()){const i=r===void 0?q(s,t)??G(s,t,n):W(s,r,n);if(i!==void 0)return{exportName:i,specifier:Y(e,s)??s.getModuleSpecifierValue()}}},z=(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))}),m={kind:"verbatim"},p={kind:"expand"},Q=new Set([g.ClassDeclaration,g.EnumDeclaration,g.EnumMember,g.InterfaceDeclaration,g.TypeAliasDeclaration]),Z=e=>T(e)!==void 0||l.isExportable(e)&&e.isExported(),ee=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),M=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&T(e)===void 0||!Q.has(e.getKind()))return m;const i=s.getFilePath();if(i.includes(K))return m;if(i===n)return p;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return p;const a=J(t.getSourceFile(),o,o.getName());return a===void 0?Z(o)||!ee(r(),o.getName())?m:p:z(a.specifier,t)?p:{kind:"qualify",qualified:a}},te=new Set([g.ClassDeclaration,g.EnumDeclaration,g.FunctionDeclaration,g.ModuleDeclaration]),I=e=>{const t=e?.getDeclarations()??[];return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},ne=e=>{for(const t of e.getDeclarations()){const n=t.getFirstChildByKind(g.ComputedPropertyName);if(n!==void 0){let r=n.getExpression();for(;l.isPropertyAccessExpression(r);)r=r.getExpression();return r}}},re=(e,t)=>{if(e.getProperties().some(s=>{if(!s.getName().startsWith("__@"))return!1;const i=ne(s);return i===void 0||!I(i.getSymbol())}))return!0;const r=e.getSymbol();return r!==void 0&&r.getDeclarations().some(s=>te.has(s.getKind()))&&!I(r)&&t().startsWith("typeof ")},R=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,a;const c=()=>(a??=e.getText(t),a);for(const u of[s,r].flatMap(d=>d?.getDeclarations()??[])){const d=M(u,t,n,c);if(d.kind==="qualify"&&i.has(u))return d;o||=d.kind!=="verbatim"}return o||re(e,c)?p:m},se=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return m;let s=!1;for(const i of[r,...r.getDescendantsOfKind(g.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const a of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const c=M(a,t,n,()=>i.getText());if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?p:m},oe=/^[A-Za-z_$][\w$]*$/u,ie=e=>oe.test(e)?e:JSON.stringify(e),$=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},y=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0&&!e.getProperties().some(t=>t.getName().startsWith("__@")),E=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),R(e,t,n).kind!=="verbatim"||$(e).some(s=>E(s,t,n,r))?!0:y(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>se(i,t,n).kind!=="verbatim")?!0:E(s.getTypeAtLocation(t),t,n,r)):!1),ae=(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())},C=(e,t)=>e!==void 0&&(y(e)||e.isString()||e.isNumber()||e.isBigInt()||e.isBoolean()||e.isLiteral()||e.isBooleanLiteral()||e.isEnumLiteral()||e.isTemplateLiteral()||e.isNull()||e.isUndefined()||e.isAny()||e.isUnknown()||e.isNever()||e.isVoid())?t:`(${t})`,ce=32,ue=8,le=(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`${C(o,a)}[]`},ge=(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(" | ")},de=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getIntersectionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(C(a,c))}return o.join(" & ")},me=(e,t,n,r,s,i)=>{if(!y(e))return;const o=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=ae(a,c),d=u&&c.isUnion()?c.getUnionTypes().filter(A=>!A.isUndefined()):[c],N=[];for(const A of d){const x=i(A,t,n,r+1,s);if(x===void 0)return;N.push(x)}o.push(`${ie(a.getName())}${u?"?":""}: ${N.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},fe=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},pe=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),b=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>ce)return!0;const i=new Set(r).add(e);if($(e).some(u=>b(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return b(o,t,n+1,i,s);if(B(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=y(e)&&e.getProperties().some(u=>b(u.getTypeAtLocation(t),t,n+1,i,s));return c||s.add(e),c},Se=(e,t,n,r,s,i,o)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(c,n,r,s+1,i);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},ve=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),f=(e,t,n,r,s)=>{if(r>ue||s.has(e))return;const i=R(e,t,n);if(i.kind==="verbatim"&&!E(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!pe(e)){if(e.isEnumLiteral())return fe(e);if(i.kind==="qualify"&&!ve(e)){const a=Se(i.qualified,e,t,n,r,o,f);if(a!==void 0)return a}return e.isArray()?le(e,t,n,r,o,f):e.isUnion()?ge(e,t,n,r,o,f):e.isIntersection()?de(e,t,n,r,o,f):me(e,t,n,r,o,f)}},he=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"||O(i)||b(n,e,0,new Set))return"unknown";const o=e.getSourceFile().getFilePath();if(E(n,e,o)){const a=f(n,e,o,0,new Set);return a===void 0&&w(e,i),a??"unknown"}return i};export{E as a,Ne as b,Ae as c,De as d,f as e,O as i,xe as p,Te as r,he as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.207",
3
+ "version": "1.0.0-alpha.209",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.150",
50
- "@lunora/agent": "1.0.0-alpha.131",
49
+ "@lunora/advisor": "1.0.0-alpha.152",
50
+ "@lunora/agent": "1.0.0-alpha.133",
51
51
  "@lunora/container": "1.0.0-alpha.56",
52
52
  "@lunora/errors": "1.0.0-alpha.41",
53
- "@lunora/platform": "1.0.0-alpha.33",
54
- "@lunora/queue": "1.0.0-alpha.62",
55
- "@lunora/scheduler": "1.0.0-alpha.81",
53
+ "@lunora/platform": "1.0.0-alpha.35",
54
+ "@lunora/queue": "1.0.0-alpha.64",
55
+ "@lunora/scheduler": "1.0.0-alpha.83",
56
56
  "@lunora/values": "1.0.0-alpha.51",
57
- "@lunora/workflow": "1.0.0-alpha.60",
57
+ "@lunora/workflow": "1.0.0-alpha.61",
58
58
  "jiti": "^2.7.0",
59
59
  "quicktype-core": "^26.0.0",
60
60
  "ts-morph": "^28.0.0"
@@ -1 +0,0 @@
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-Ba1jzhVh.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};
@@ -1,9 +0,0 @@
1
- import{existsSync as P,mkdirSync as Fs,readFileSync as _t,writeFileSync as Os,rmSync as Rs}from"node:fs";import{join as E,dirname as ne}from"node:path";import{performance as Ae}from"node:perf_hooks";import{runAdvisor as Ls}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as Ds,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as ks}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Ms}from"./formatAdvisories-DwmUKYuc.mjs";import{s as Ks}from"./paths-C-9fwEgQ.mjs";import{C as re,o as zt,j as _s,f as zs,k as $s,b as Us,c as qs,m as Bs,e as Vs,p as Ws,d as js,i as Hs,l as Gs,g as Ys,q as Qs,n as Xs,a as Zs,h as Js}from"./emit-Ba1jzhVh.mjs";import{isD1GlobalTable as $t,isHyperdriveGlobalTable as Ut}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as en}from"./AGENTS_FILENAME-DPIMTD_h.mjs";import{discoverContainers as tn}from"./CONTAINERS_FILENAME-wDZs0S4p.mjs";import sn from"./discoverCrons-B2GXsB-m.mjs";import{diagnosticAt as ue}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as de}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,unwrapExpression as G,listSecurityScanFiles as Re,objectLiteralFromCallbackBody as qt,propertyInitializer as A,lunoraRelativePath as x,collectCallRows as T,collectSecurityCallRows as nn,limitNameOf as Bt,optionsObjectLiteral as Vt,isContextIdentifier as we,handlerOf as rn,isDatabaseAccessor as M,readTargetOf as Wt,enclosingExportName as on}from"./listLunoraSourceFiles-DsxeRYvh.mjs";import an from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as cn}from"./QUEUES_FILENAME-Dd781zOQ.mjs";import{discoverSandboxUsage as ln}from"./discoverSandboxUsage-pJ42YuvL.mjs";import un from"./discoverStorageRulesMetadata-BFiKUo5m.mjs";import{a as y,c as K,d as jt,e as dn}from"./classify-procedure-call-RjsZg8AH.mjs";import{discoverWorkflows as fn}from"./WORKFLOWS_FILENAME-v3AJcUjy.mjs";import{gatePlatformFeatures as gn,resolveCodegenTarget as pn,readTargetDiagnostics as mn}from"./DEFAULT_TARGET-DtzlGawL.mjs";import{i as L,a as z,e as v,r as hn,b as xn,s as fe,c as vn,f as En,d as yn}from"./queries-TZaLWhWq.mjs";import{r as ge,s as Sn}from"./parse-validator-DW5RNi_6.mjs";import An from"./discoverAuthApiCalls-EHm1O8uG.mjs";import{t as Ht,i as Nn,r as bn,e as Pn,a as wn,c as In}from"./unwrap-handler-return-FZxbgxxx.mjs";import lt from"./discoverFunctions-azmV60kc.mjs";import ut from"./discoverHttpRoutes-BrDDCDdD.mjs";import Tn from"./discoverHyperdriveCalls-CzRlqv_N.mjs";import Cn from"./discoverInserts-BP0Gl37o.mjs";import{m as Le,a as ie,s as Gt,d as Fn}from"./index-D6xfnMEE.mjs";import{e as Yt}from"./exported-procedure-chains-CjlBrFjo.mjs";import On from"./discoverMigrations-BX86Fv9G.mjs";import{MUTATORS_FILENAME as Rn,isDefineMutatorCallee as Ln,discoverMutators as dt}from"./MUTATORS_FILENAME-Dv8PMtzE.mjs";import Dn from"./discoverNondeterministicCalls-CJYIXWPw.mjs";import{discoverNotifyConfig as kn,discoverNotifyCalls as Mn}from"./NOTIFY_FILENAME-DbuOgja2.mjs";import Kn from"./discoverR2sqlCalls-emIgm3TF.mjs";import _n from"./discoverRlsProcedures-CU7YMR3P.mjs";import zn from"./discoverRlsMetadata-3Gs8U3ng.mjs";import $n from"./discoverSchema-B0GCa2PI.mjs";import{secretKindOf as Un,redact as qn,isHeuristicSecretKind as Bn,isSecretishName as Vn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Wn}from"./SHAPES_FILENAME-BtuI2r7-.mjs";import{emitApp as jn}from"./emitApp-DSSyAMLC.mjs";import{buildOpenApiDocument as Hn,emitOpenApiModule as Gn}from"./buildOpenApiDocument-Ckg1Yc6n.mjs";import{buildOpenRpcDocument as Yn,emitOpenRpcModule as Qn}from"./OPENRPC_VERSION--vy88dC-.mjs";import{buildSchemaSnapshot as Xn}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const ft=(e,t="api")=>{const s=new Map;for(const n of e){const o=Ks(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new k("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Zn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!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`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:re)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Jn=(e,t,s={})=>{if(t===void 0)return;const n=Zn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
2
- `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
- ${o}
4
-
5
- Install them with your package manager, then re-run codegen.`)},er="env.ts",tr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},sr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},nr=e=>{if(i.isIdentifier(e))return tr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.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(!i.isIdentifier(r))throw ue(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},or=(e,t)=>{const s=E(t,er);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=rr(n);if(o.length!==0){if(o.length>1)throw ue(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},gt="ctx",Qt=e=>{const t=new Set,s=new Set([gt]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==gt)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},ir=(e,t)=>{const s=Object.fromEntries(re.map(n=>[n.key,!1]));for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Qt(o);for(const c of re)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(re.every(c=>s[c.key]))break}return s},Xt="identity.ts",ar=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return de(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},cr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&de(n.getModuleSpecifierValue())}return!1},lr=e=>{if(i.isIdentifier(e))return ar(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&cr(t)}return!1},ur=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!lr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ue(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},dr=(e,t)=>{const s=E(t,Xt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=ur(n);if(o.length!==0){if(o.length>1)throw ue(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},fr=(e,t)=>{const s=G(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return G(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},gr=e=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!i.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||G(s)?.getText()!=="false"}),pr=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Qt(o).has("secrets")),s.durableStreams||(s.durableStreams=o.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(i.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>gr(fr(o,u)))})),s.durableStreams&&s.secrets)break}return s},mr="createWorker",hr="extend",pt=e=>e!==void 0&&(i.isStringLiteral(e)||i.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||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=pt(o.getNameNode());r!==void 0&&t.push(r)}return t},xr=e=>{const t=y(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===mr)return i.isObjectLiteralExpression(s)?mt(s):[];if(t!==hr||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=qt(s.getBody());return n===void 0?[]:mt(n)},vr=(e,t)=>{const s=[];for(const{filePath:n}of Re(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...xr(r))}return[...new Set(s)]},Zt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Zt(e.inner)},Er=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=Zt(n);return o!==void 0&&t.has(o)}))},yr=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(r.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Sr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=dr(s,t),a=or(s,t),c=fn(s,t),u=cn(s,t),d=en(s,t);yr(c,d);const m=tn(s,t),h=un(s,t),w=sn(s,t,c,d),D=vr(s,t),g=pr(s,t),b=ln(s,t),F=ir(s,t);F.browser=F.browser||b.usesSandboxBrowser;const O=gn(F,pn(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(N=>N.commitOrdered===!0),cronTriggers:w.length>0,crossShardFanout:o.tables.some(N=>typeof N.shardMode=="object"),durableStreams:g.durableStreams,globalTables:o.tables.some(N=>N.shardMode==="global"),queues:u.length>0,relationGraph:Er(o),secrets:g.secrets,vectorStore:o.vectorIndexes.length>0}),S=O.usage,R=O.signals.vectorStore!==!1,$=an(n),W=$??new Set,X=W.has("lunorash");Jn(o,$,{hasVectors:R,scheduler:S.scheduler||w.length>0,storage:S.storage||h.rules.length>0||Object.keys(zt(o)).length>0,usage:S});const _=P(E(t,"flags.ts")),C=P(E(t,"notify.ts"));return{agents:d,containers:m,crons:w,dataModelContent:zs(o),declaredDependencies:$,dependencies:W,entryCronTriggers:D,env:a,featureUsage:S,hasFlags:_,hasNotify:C,identity:r,platformGate:{...O,diagnostics:[...mn(n,e.target),...O.diagnostics]},queues:u,serverContent:_s({agents:d,containers:m,env:a,hasAccessFacade:S.access,hasAi:S.ai,hasAnalytics:S.analytics,hasBrowser:S.browser,hasVectors:R,hasFlags:_,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:o,storageRuleBuckets:h.rules.map(N=>N.bucket),useUmbrella:X,workflows:c}),storageRulesMetadata:h,usesSandbox:b.usesSandboxBrowser||b.usesSandboxContainer||b.usesSandboxFs,useUmbrella:X,workflows:c}},Jt=new Set(["delete","get","head","options","patch","post","put"]),Ar=new Set(["handler","stream"]),Nr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ht=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),br=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Jt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Pr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||Jt.has(n.getName()))break;s=n.getExpression()}return br(s)},wr=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(i.isIdentifier(s)&&ht.has(s.getText()))return!0}return!1},Ir=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Ar.has(n.getName()))return;const o=Pr(s);if(!o||!Nr.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&wr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Tr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Ir(o,t);r&&s.push(r)}return s},Cr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Tr(o,x(t,n)))}return s},Fr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Or=(e,t)=>{if(!Fr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)||z(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Rr=(e,t)=>T(e,t,Or),Lr=new Set(["generateText","streamText"]),Dr=new Set(["messages","prompt","system"]),kr=[{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"]}],Mr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of kr)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Kr=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Mr(t);if(s!==void 0)return s}},_r=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},zr=e=>{if(hn(e))return!0;const t=_r(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},$r=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Dr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&zr(s))return!0}return!1},Ur=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());if(o===void 0||!Lr.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=Kr(c),a!==void 0))break;a!==void 0&&s.push({exportName:v(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:$r(r)})}return s},qr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ur(o,x(t,n)))}return s},Br=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Vr=(e,t)=>{if(!Br(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Wr=(e,t)=>T(e,t,Vr),De=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=ge(s.getExpression());return n===void 0||De(n,t)})}finally{t.delete(e)}},jr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:ge(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:De(o)}},Hr=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?ge(r):void 0;a===void 0?s=!0:(t.push(a),s||=De(a))}n=o.getExpression()}return{objects:t,opaque:s}},ke=(e,t)=>t?Hr(t):jr(e),es=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=ge(s.getExpression());return n===void 0?[]:es(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},Gr=e=>e.flatMap(t=>es(t,new Set)),Yr=new Set(["check","length","max"]),Ie=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Qr=e=>[e,...e.getDescendants()].filter(t=>Ie(t)!==void 0),Xr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(Yr.has(s.getName()))return!0;t=n}},Zr=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=Qr(r),c=o.getName();a.some(u=>Ie(u)==="any")?t.push(c):a.some(u=>Ie(u)==="string"&&!Xr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Jr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=K(s);if(n?.visibility!=="public")return;const{objects:o}=ke(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=Zr(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},eo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Jr(o,t);r&&s.push(r)}return s},to=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...eo(o,x(t,n)))}return s},Ne=e=>e?.getKind()===l.TrueKeyword,so=e=>e?.getKind()===l.FalseKeyword,no=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,ro=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),oo=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&y(t.getExpression())==="scim"),io=e=>e!==void 0&&i.isCallExpression(e)&&ro.has(y(e.getExpression())??""),ao=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),co=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:oo(A(e,"plugins"))&&io(A(e,"database")),secureCookiesDisabled:so(A(t,"useSecureCookies")),sessionFreshAgeZero:no(A(n,"freshAge")),trustedOriginsWildcard:ao(A(e,"trustedOrigins"))}},lo=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),uo=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?co(s):lo();return{exportName:v(e),file:t,line:e.getStartLineNumber(),...o}},fo=(e,t)=>nn(e,t,uo),go=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},po=(e,t,s)=>{const n=go(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!L(o)||z(o))&&!(s.requireUnmodifiedReach===!0&&!xn(o)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:n}},mo=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=po(o,t,s);r&&n.push(r)}return n},pe=(e,t,s)=>{const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...mo(r,x(t,o),s))}return n},ho=new Set(["content","pdf","scrape","screenshot"]),xo=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ho}),vo=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Eo=new Set(["RateLimiter"]),yo=new Set(["extend"]),xt="lunora",So=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ts=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Te=e=>e&&i.isObjectLiteralExpression(e)?ts(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Ao=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&qt(t.getBody());return s?ts(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},No=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());o!==void 0&&(vo.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])}):yo.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ao(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=y(n.getExpression());o===void 0||!Eo.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Te(n.getArguments()[0])})}return s},bo=(e,t)=>{for(const s of So){const n=E(t,s);if(!P(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===xt&&r.push({callee:xt,file:s,line:a.getStartLineNumber(),...Te(a.getArguments()[0])});return r}return[]},Po=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Re(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...No(r,n))}return s.push(...bo(e,ne(t))),s},vt="ctx.containers.",wo=e=>{if(!e.startsWith(vt))return!1;const t=e.slice(vt.length);return t.length>0&&!t.includes(".")},Io=(e,t)=>pe(e,t,{argIndex:0,matchReceiver:wo,methods:new Set(["get"])}),To=new Set(["allow","deny","setAllowed"]),Co=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Fo=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Co(e)))return{detail:"enableInternet: true",exportName:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Oo=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!To.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Ro=(e,t)=>Fo(e,t)??Oo(e,t),Lo=(e,t)=>T(e,t,Ro),Do=(e,t)=>{const s=e.exportName??`line ${e.line.toString()}`;return{cacheKey:`procedure_return_type_erased:${t}:${s}`,categories:["SCHEMA"],description:"Codegen renders a procedure's return type into `_generated/`, where only names that resolve from that directory may appear. A type it can neither name nor reproduce structurally — a class instance, a call or index signature, a recursive or very deeply nested shape — is emitted as `unknown` instead, so callers lose the shape while the runtime still returns it.",detail:`\`${s}\` in \`${t}\` (line ${e.line.toString()}) returns \`${e.rendered}\`, which codegen could not reproduce — its generated type is \`unknown\`.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e.exportName,filePath:t,line:e.line,rendered:e.rendered},name:"procedure_return_type_erased",remediation:"Declare the shape explicitly with `.output(...)`, or export the type from the module that declares it so codegen can name it. A class instance cannot cross the wire at all — return a plain object.",title:"Procedure return type is missing from the generated type"}},ko=e=>{const t=new Map;for(const s of Ht()){const n=Do(s,x(e,s.filePath));t.set(n.cacheKey,n)}return[...t.values()].toSorted((s,n)=>s.cacheKey.localeCompare(n.cacheKey))},Mo=()=>{Ht()},Ko=new Set(["defineExportSink","r2Sink","webhookExportSink"]),_o=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Ko.has(s)?s:void 0},zo=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},$o=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Re(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=_o(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?zo(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},Uo=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),qo=new Set(["dbRateLimit","rateLimit"]),Bo=e=>{const t=Vt(e);if(!t)return!1;const s=t.getProperty("failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},Vo=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=Uo.get(s);if(n!==void 0)return{callee:s,exportName:v(e),failOpen:Bo(e.getArguments()[n]),file:t,limitName:qo.has(s)?Bt(e):"",line:e.getStartLineNumber()}},Wo=(e,t)=>T(e,t,Vo),jo=new Set(["boolean","number","object","string"]),Ho=e=>{const t=e.getName();if(!jo.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&we(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&we(n.getExpression()))return t},Go=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=Ho(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},Yo=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=Go(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},Qo=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=K(t);if(s?.kind!=="query")return;const n=rn(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},Et=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Xo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.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()}`},Zo=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=Xo(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},Jo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Qo(o);r&&s.push(...Zo(r,t))}return s},ei=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Jo(o,x(t,n)))}return s},ti=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&we(t.getExpression())},si=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},ni=(e,t)=>{if(!ti(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=si(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:v(e),file:t,key:o,line:e.getStartLineNumber()}},ri=(e,t)=>T(e,t,ni),oi=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||Nn(r))return;const a=e.getSourceFile().getFilePath();if(bn(o,e,a)){const c=Pn(o,e,a,0,new Set);return c===void 0&&wn(r),c}return r},ii=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},ai=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},ci=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))ii(a)&&s.push({file:r,indexName:ai(a),line:a.getStartLineNumber()})}return s},Y=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,ss=e=>{const t=e.getArguments()[0],s=Y(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&i.isPropertyAssignment(n)?Y(n.getInitializer()):void 0},li=new Set(["delete","get","head","options","patch","post","put"]),ui=new Set(["handler","stream"]),di=new Set(["runAction","runMutation"]),fi=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,ns=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if((s.getPropertyNameNode()?.getText()??s.getNameNode().getText())===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},yt=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:ns(s,"ctx")},St=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:ns(s,"request")},At=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(di.has(a)&&Q(c,t))return a;if(fi.has(a)&&i.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 o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Q(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},gi=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,pi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Q(n.getExpression(),t)},mi=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],rs=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:mi(s)},hi=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?rs(t,a.getText()):[]}return[]},xi=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=rs(s,t.getText());return n.length>0?n:hi(t,s)},bt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>pi(o,t)&&xi(o).some(r=>gi.test(r)))},vi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ui.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(li.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},Ei=(e,t)=>{const s=e.getExpression();if(i.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=vi(e);if(n===void 0)return;const o=Y(e.getArguments()[0]),r=o&&yt(o,!1);if(!o||r===void 0||bt(o,St(o,!1)))return;const a=At(o,r);return a===void 0?void 0:{exportName:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Nt(o,r),sideEffect:a}},yi=(e,t)=>T(e,t,Ei),Si=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Ai=new Set(["append","set"]),os=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Pt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Si.has(y(n.getExpression())??"")&&En(n,t)),Ni=(e,t)=>{if(Pt(e,t))return!0;const s=fe(e);return s!==void 0&&Pt(s,t)},Ce=(e,t)=>vn(e,t)&&!Ni(e,t),bi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=fe(e);return t!==void 0&&i.isNewExpression(t)&&y(t.getExpression())==="Headers"},ae=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=fe(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Me=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Ce(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:os(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Ce(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=ae(n.getExpression());o!==void 0&&Me(o,t,s)}},is=(e,t)=>{const s=ae(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=ae(n.getInitializer());o!==void 0&&Me(o,"response-init",t)},Pi=(e,t)=>{const s=y(e.getExpression());if(s==="Response")is(e.getArguments()[1],t);else if(s==="Headers"){const n=ae(e.getArguments()[0]);n!==void 0&&Me(n,"headers-ctor",t)}},wi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){is(e.getArguments()[1],t);return}if(Ai.has(n)&&bi(o)){const r=e.getArguments()[1];r!==void 0&&Ce(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:os(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Ii=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Pi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))wi(s,t)},Ti=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Y(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return Ii(n,{exportName:v(e),relativePath:t,requestName:r.getText(),rows:a}),a},Ci=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Ti(n,t));return s},Fi=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ci(o,x(t,n)))}return s},Oi=new Set(["auth","context.auth","ctx.auth"]),Ri="userId",Li=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Di=(e,t)=>{const s=E(t,Xt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(y(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Li(r):void 0}},wt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Oi.has(e.getExpression().getText())?e:void 0},ki=e=>{if(i.isPropertyAccessExpression(e)&&wt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&wt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Mi=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=ki(o);r!==void 0&&n.push({declared:r===Ri||s.has(r),exportName:v(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Ki=(e,t)=>{const s=Di(e,t);if(s===void 0)return[];const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Mi(r,x(t,o),s))}return n},_i=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=A(s,"key");if(!(!n||!L(n)||z(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},zi=(e,t)=>T(e,t,_i),$i=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ui=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return pe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:$i}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},qi=new Set(["queue","send"]),It=new Set(["bcc","cc","to"]),Bi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!qi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Vi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return It.has(t.getName())&&L(n)&&!z(n)}if(!i.isPropertyAssignment(t)||!It.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&L(s)&&!z(s)}):!1,Wi=(e,t)=>{const s=Bi(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Vi(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},ji=(e,t)=>T(e,t,Wi),Hi=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,Gi=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Hi(e):!0,as=(e,t=!1)=>{for(const s of e.getProperties()){if(Gi(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||as(n,!0))return!0}return!1},Yi=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Yt(n))for(const r of Le(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||as(a)))return!0}}return!1},Qi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=ie(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=ie(a);c!==void 0&&s.push({column:c,strategy:Gt(a),table:o})}}return s},Xi=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Yt(o))for(const a of Le(r))for(const c of Qi(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Zi=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=ie(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=ie(u);if(d===void 0)continue;const m=Gt(u);m!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:m,table:a})}}return o},Ji=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?K(s):void 0;return n?.receiver?Le(n.receiver).flatMap(o=>Zi(o,e.getName(),t)):[]},ea=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ji(c,r))}return s},ta=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return M(s)},sa=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},na=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Ln(s.getExpression())?s:void 0},ra=e=>{const t=na(e),s=t===void 0?void 0:sa(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>ta(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},oa=e=>e.getVariableDeclarations().flatMap(t=>ra(t)),ia=(e,t)=>{const s=E(t,Rn);if(!P(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return oa(n)},aa=new Set(["delete","get","patch"]),ca=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),la=new Set(["auth","identity","session","user"]),ua=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),da=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!M(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},fa=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},ga=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),pa=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,ma=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>ga(s.getExpression(),t)&&pa(s.getThenStatement())),ha=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!aa.has(o))continue;const r=n.getExpression();if(!(M(r)||i.isPropertyAccessExpression(r)&&M(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},xa=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},va=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>xa(s)==="ctx")),Ea=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>ua.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),ya=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(ca.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&la.has(t.getName()))return!0}return va(e)||Ea(e)},Sa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=K(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=ss(s);if(o===void 0)return[];const r=n.receiver!==void 0&&jt(n.receiver,"use","rls"),a=ya(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const m=da(d);if(m===void 0)continue;const h=fa(d);if(h===void 0||c.has(h)||!ma(o,h))continue;const w=ha(o,h);w!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:w,table:m,usesRls:r,visibility:n.visibility}))}return u},Aa=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sa(c,r))}return s},Na=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ba=new Set(["insert","insertManyUnsafe","patch","replace"]),Pa=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ba.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},wa=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},Tt=(e,t)=>{if(i.isPropertyAccessExpression(e)){const s=e.getExpression();return i.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(i.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return i.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&i.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Ia=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(i.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!i.isVariableDeclarationList(c)||c.getDeclarationKind()!==Ds.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(o=u,r=d)}return o},Ta=(e,t)=>{if(Tt(e,t))return!0;const s=Ia(e);return s!==void 0&&Tt(s,t)},Ca=(e,t,s,n,o)=>{const r=[];for(const a of e.getProperties()){let c,u;if(i.isPropertyAssignment(a)?(c=a.getName(),u=a.getInitializer()):i.isShorthandPropertyAssignment(a)&&(c=a.getName(),u=a.getNameNode()),!(c===void 0||u===void 0||!Na.has(c))&&L(u)&&!z(u)){const d=v(s),m=o(d)===c&&Ta(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...m&&{ownerScoped:!0}})}}return r},Fa=(e,t,s)=>{const n=Pa(e.getExpression());if(n===void 0)return[];const o=e.getArguments()[1];return o?wa(o,n).flatMap(r=>Ca(r,n,e,t,s)):[]},Oa=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of Fa(o,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Ra=(e,t,s=[],n=[])=>{const o=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);o.push(...Oa(c,u,d=>r.get(`${u}:${d}`)??{}))}return o},La=["providerSubscriptionId","state"],Da=["providerEventId","processedAt"],Ct=(e,t)=>t.every(s=>s in e.shape),ka=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Ct(t,La)&&Ct(s,Da)},Ma=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Ka=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,_a=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Ka(t.getInitializer()):void 0},za=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Ma.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?_a(n):void 0;return{callee:s,exportName:v(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},$a=(e,t)=>T(e,t,za),Ua=new Set(["defineQueue","defineWorkflow"]),qa=new Set(["run","runAction","runMutation","runQuery"]),Ba=new Set(["api","internal"]),Va=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Wa=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},cs=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},ls=(e,t)=>e===t||e.startsWith(`${t}.`),us=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Ft=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},ds=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Ft(s));return i.isIdentifier(e)&&Ft(e)&&t.push(e),t},ja=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Ha=e=>{const t=cs(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},Ga=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Ha(e),o=new Set,r=a=>us(a).some(c=>n.some(u=>ls(c.getText(),u)))?!0:ds(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of ja(a))o.add(u)}return{names:o,prefixes:n}},Ya=(e,t)=>us(e).some(s=>t.prefixes.some(n=>ls(s.getText(),n)))?!0:ds(e).some(s=>t.names.has(s.getText())),Qa=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!Ba.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Xa=(e,t,s)=>{const n=cs(e,0);if(n===void 0)return[];const o=Ga(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!qa.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!Ya(u,o))continue;const d=Qa(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},Za=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Va(n);if(o===void 0||!Ua.has(o))continue;const r=Wa(n);r!==void 0&&s.push(...Xa(r,o==="defineQueue"?"queue":"workflow",t))}return s},Ja=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Za(o,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"]),ec=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),tc=e=>{const s=ec(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Rt.has(s)||Rt.has(n)},sc=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},nc=(e,t)=>{const{objects:s,opaque:n}=ke(e,t);return Gr(s).some(o=>sc(o))?!0:n?void 0:!1},rc=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},oc=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},oe={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},ic=e=>{const t=oc(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=rc(t);return{...oe,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ot?{...oe,[Ot[s]]:!0}:oe},ac=e=>{const t={...oe};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=ic(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},cc=new Set(["insert","insertMany","insertManyUnsafe","replace"]),lc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!cc.has(t.getName()))return!1;const s=t.getExpression();if(!M(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:tc(o.getLiteralText())},uc=new Set(["create","runAfter","runAt","send","sendBatch"]),dc=new Set(["queues","scheduler","workflows"]),fc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!uc.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&dc.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},gc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return M(s)},fs=new Set(["generateObject","generateText","streamObject","streamText"]),pc=e=>{const t=y(e.getExpression());return t!==void 0&&fs.has(t)},mc=e=>{const t=y(e.getExpression());if(t===void 0||!fs.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},hc=new Set(["log","span","trace"]),xc=new Set(["ai"]),vc=new Set(["email","mail"]),Ec=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),be=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),yc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Sc=new Set(["every","filter","flatMap","forEach","map","some"]),Ac=new Set(["all","allSettled","race"]),Nc=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(Sc.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&Ac.has(n))return t},bc=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(yc.has(t.getKind())){const s=Nc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Pc=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},wc=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ic=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Ec.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=wc(n);r&&(t=!0,!bc(r)&&!Pc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Tc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Lt="lunora-advisor-exempt",Cc=/^[\s*/]+/u,Fc=/[\w-]/u,Oc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
6
- `);for(const n of s.split(`
7
- `)){const o=n.replace(Cc,"");if(!o.startsWith(Lt))continue;const r=o.slice(Lt.length);if(Fc.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:""}},Rc=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Lc=(e,t)=>{const s=Rc(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},Dc=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(lc(u)&&(r=!0),fc(u)&&(t=!0),gc(u)&&(o=!0),pc(u)&&(s=!0),mc(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ic(e);return{callsMail:be(e,vc),emitsEvent:be(e,hc),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||be(e,xc),throwsBareError:Tc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},kc=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=K(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?ac(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Lc(e,s);return{...r?Dc(r):{},...Oc(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:nc(s,n.receiver),kind:n.kind,visibility:n.visibility}},Mc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=kc(o,t);r&&s.push(r)}return s},Kc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Mc(o,x(t,n)))}return s},_c=new Set(["dbRateLimit","rateLimit"]),zc=e=>i.isArrowFunction(e)?e.getBody():e,$c=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},gs=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},ps=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const o=n.getParent();return!(i.isPropertyAccessExpression(o)&&o.getNameNode()===n)})},Uc=(e,t)=>L(e)||t!==void 0&&ps(e,t).some(s=>gs(s)),qc=(e,t)=>t===void 0?z(e):ps(e,t).some(s=>!gs(s)),Bc=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!_c.has(s))return;const n=A(Vt(e.getArguments()[2]),"key");if(!n)return;const o=zc(n),r=$c(n);if(!(!Uc(o,r)||qc(o,r)))return{callee:s,exportName:v(e),file:t,limitName:Bt(e),line:e.getStartLineNumber()}},Vc=(e,t)=>T(e,t,Bc),Wc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),jc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Wc.has(t.getName()))return;const s=t.getExpression();if(M(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&M(s.getExpression()))return s.getName()},Hc=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&M(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Gc=e=>{let t=G(e)??e;for(;i.isAwaitExpression(t);)t=G(t.getExpression())??t.getExpression();return t},ms=(e,t=!1)=>{const s=Gc(e);if(i.isIdentifier(s)){if(t)return;const n=fe(s);return n===void 0?void 0:ms(n,!0)}if(i.isCallExpression(s))return jc(s)??Hc(s)},Yc=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Qc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=K(s);if(n?.kind!=="query")return[];const o=ss(s);if(o===void 0)return[];const r=n.receiver!==void 0&&dn(n.receiver,"output"),a=n.receiver!==void 0&&jt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Yc(o)){const m=ms(d);m===void 0||c.has(m)||(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:m,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},Xc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Qc(c,r))}return s},Zc=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Jc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?K(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Wt(r);if(a===void 0)continue;const c=Zc(A(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},el=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Jc(c,r))}return s},ce=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ce(e.getLeft()),s=ce(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},tl=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ce(t)!==void 0},sl=/(?:^|\/)__tests__\//u,nl=/\.(?:spec|test)$/u,rl=e=>sl.test(e)||nl.test(e),ol=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},il=(e,t,s)=>Bn(e)?!rl(s)&&Vn(ol(t)):!0,al=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(tl(r))continue;const a=ce(r);if(a===void 0)continue;const c=Un(a);if(c===void 0||!il(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:qn(a)}))}return s},cl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...al(o,x(t,n)))}return s},ll=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?K(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Wt(r);if(a===void 0)continue;const c=A(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&L(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},ul=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ll(c,r))}return s},dl=new Set(["query","unsafe"]),fl=e=>{if(!i.isPropertyAccessExpression(e)||!dl.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},gl=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),pl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",ml=(e,t)=>{if(!fl(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!gl(s)))return{exportName:pl(e),file:t,line:s.getStartLineNumber()}},hl=(e,t)=>T(e,t,ml),xl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],vl=e=>{for(const[t,s]of xl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},El=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=vl(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},yl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Sl=(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:yl,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Al=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Nl=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,bl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=Nl(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Pl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Al.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},wl=(e,t)=>{const s=Pl(e.getExpression());if(s!==void 0)return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...bl(e.getArguments()[s.optionsIndex])}},Il=(e,t)=>T(e,t,wl),Tl=(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")}),Cl=(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"}),Fl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return ke(e,t).opaque},Ol=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=K(a);c!==void 0&&Fl(a,c.receiver)&&s.push(Cl(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},Rl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...Ol(o,x(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},Ll=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),hs=e=>!e.isAny(),Ke=e=>{const t=e.getType();if(!hs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:Ll.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},xs=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},vs={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."},Dl=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),kl={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},_e=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,m=d===void 0?o:Dl(d),h=c===void 0?m.remediation:`${c} ${m.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${m.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},Ml=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(me(s,t,a)||!xs(r))continue;const c=Ke(r);c!==void 0&&n.push(_e(t,a,c,r.getStartLineNumber(),vs))}return n},Kl=(e,t,s)=>{if(me(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ke(o.getExpression());r!==void 0&&n.push(_e(t,"default",r,o.getStartLineNumber(),vs))}return n},_l=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(me(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!xs(c))continue;const u=Ke(c);u!==void 0&&n.push(_e(t,a,u,r.getStartLineNumber(),kl))}return n},zl=(e,t,s)=>[...Ml(e,t,s),...Kl(e,t,s),..._l(e,t,s)],$l=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>me(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Ul=({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"}),ql=(e,t,s)=>{const n=[],o=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...zl(c,u,s)),o.push(...$l(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!hs(a.getType()))&&n.push(Ul(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},Bl=new Set(["when","where"]),Pe=new Set(["definePolicy","defineShape"]),Vl=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return Pe.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return Pe.has(o)?o:void 0}const s=t.getText();return Pe.has(s)?s:void 0},Wl=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Es=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Wl(e))return"empty-object";if(i.isParenthesizedExpression(e))return Es(e.getExpression())}},ze=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),jl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ze(t)===e),ys=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ze(t)===e),Hl=e=>{const t=jl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||ys(e).length>0},Gl=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ze(t)===e),Fe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",Yl=(e,t)=>Fe(e)||Fe(t),Ql=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Dt=e=>!Fe(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Xl=(e,t,s)=>{const n=Ql.get(e);if(n!==void 0)return Yl(t,s)?n==="positive"?"negative":"positive":Dt(t)||Dt(s)?void 0:n},H=e=>{if(i.isParenthesizedExpression(e))return H(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Xl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=H(e.getLeft()),o=H(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},kt=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Zl=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Jl=e=>i.isReturnStatement(e)?e.getExpression()??e:e,eu=e=>{const t=[];for(const s of ys(e)){const n=H(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Gl(e)){const n=H(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?kt(s.getThenStatement()):kt(s.getElseStatement())??Zl(s);o!==void 0&&t.push(Jl(o))}return t},tu=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},su=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!Bl.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Hl(a))for(const c of eu(a)){const u=Es(c);u!==void 0&&o.push({exportName:tu(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},nu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Vl(n);o!==void 0&&s.push(...su(n,o,t))}return s},ru=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...nu(o,x(t,n)))}return s},ou=new Set(["query","upsert","upsertMany"]),iu=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(ou.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},au=(e,t)=>{const s=iu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=A(n,"namespace");if(!(!o||!L(o)||z(o)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},cu=(e,t)=>T(e,t,au),lu=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},uu=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},du=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!lu(a))continue;const c=on(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:uu(a)})}}return s},fu=".lunora-schema.json",Oe=(e,t)=>{P(e)&&_t(e,"utf8")===t||Os(e,t,"utf8")},gu=(e,t)=>{if(t===""){Rs(e,{force:!0});return}Oe(e,t)},pu=e=>{const t=E(e,"package.json");if(P(t))try{const s=JSON.parse(_t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},mu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},hu=e=>{let t=P(e)?e:ne(e);for(;t&&t!==ne(t);){const s=E(t,"tsconfig.json");if(P(s))return s;t=ne(t)}},Mt=e=>e.replaceAll("\\","/"),xu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},le=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Kt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,vu=8,Eu=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:m}=e,h=In();let w=lt(a,o),D=dt(a,o),g=ut(a,o);ft([...w,...D].map(b=>b.filePath)),ft(g.filter(b=>b.stream).map(b=>b.filePath),"http-stream");for(let b=1;;b+=1){const F=Zs({agents:t,functions:w,httpRoutes:g,mutators:D,useUmbrella:d,workflows:m}),O=Js({agents:t,functions:w,migrations:r,mutators:D,shapes:c,useUmbrella:d,usesSandbox:u});if(b>=vu||Kt(a,s,F)&&Kt(a,n,O))return{apiContent:F,functions:w,functionsContent:O,httpRoutes:g,mutators:D};le(a,s,F),le(a,n,O),h(),w=lt(a,o),D=dt(a,o),g=ut(a,o)}},yu=e=>{const t=hu(e);return t?new ct({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ct({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},md=(e,t)=>{const s=p(t),n=E(t,"schema.ts");P(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>Mt(c))),r=Mt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},hd=e=>{const t=mu(),s=t?Ae.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),o=E(n,"schema.ts");if(!P(o))throw new k("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??yu(n);Sn(oi),Mo();const a=$n(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:m,dependencies:h,entryCronTriggers:w,env:D,featureUsage:g,hasFlags:b,hasNotify:F,identity:O,platformGate:S,queues:R,serverContent:$,storageRulesMetadata:W,usesSandbox:X,useUmbrella:_,workflows:C}=Sr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),N=E(n,"_generated"),Ss=E(N,"dataModel.ts"),As=E(N,"server.ts"),Ns=E(N,"api.ts"),bs=E(N,"functions.ts");le(r,Ss,m),le(r,As,$);const Z=On(r,n),q=Wn(r,n),{apiContent:$e,functions:B,functionsContent:Ue,httpRoutes:Ps,mutators:J}=Eu({agents:c,apiPath:Ns,generatedFunctionsPath:bs,lunoraDirectory:n,migrations:Z,project:r,shapes:q,useUmbrella:_,usesSandbox:X,workflows:C}),ee=e.lint===!1?void 0:Ms({adminRoutes:Cr(r,n),aiRawRuns:Rr(r,n),aiToolSideEffects:qr(r,n),argumentDerivedFetches:Wr(r,n),argumentValidators:to(r,n),authApiCalls:An(r,n),authConfigs:fo(r,n),browserUrlAccesses:xo(r,n),configCalls:Po(r,n),containerKeyAccesses:Io(r,n),containerOverrides:Lo(r,n),containers:u,exportSinks:$o(r,n),staleMigrationImports:El(r,n),failOpenGuards:Wo(r,n),flagReads:ei(r,n),flagSecurityDefaults:ri(r,n),geoIndexUsages:ci(r,n),httpActionGuards:yi(r,n),httpHeaderWrites:Fi(r,n),hyperdriveCalls:Tn(r,n),identityClaimReads:Ki(r,n),imageDeliveryUrlAccesses:zi(r,n),inserts:Cn(r,n),kvKeyAccesses:Ui(r,n,B),mailRecipientAccesses:ji(r,n),maskProcedures:Fn(r,n),maskStrategies:ea(r,n),mutatorWrites:ia(r,n),nondeterministicCalls:Dn(r,n),normalizeIdAuthorizations:Aa(r,n),notifyCalls:Mn(r,n),notifyConfig:kn(r,n),mutators:J,ownerFieldWrites:Ra(r,n,B,J),unrestrictedWhereBranches:ru(r,n),paymentWebhooks:$a(r,n),privilegedDispatches:Ja(r,n),procedureProtections:Kc(r,n),queries:yn(r,n),queues:R,r2sqlCalls:Kn(r,n),ratelimitKeySelectors:Vc(r,n),rawRowReturns:Xc(r,n),relationLoads:el(r,n),rlsProcedures:_n(r,n),schema:a,secretLiterals:cl(r,n),shapes:q,softDeleteReads:ul(r,n),sqlInterpolations:hl(r,n),storageKeyAccesses:Sl(r,n,B),storageUploads:Il(r,n),vectorNamespaceAccesses:cu(r,n),workflowCalls:du(r,n),workflows:C,wranglerVariables:e.wranglerVariables}),qe=ee===void 0?[]:[...Ls(ee,{source:"static"}),...ql(r,n,{byName:new Set([...C,...R,...c,...u].map(f=>f.exportName)),byPath:new Set([...B,...J,...q,...Z].map(f=>`${f.filePath}:${f.exportName}`))}),...Rl(r,n),...ko(n)],ws=zn(r,n),Be=Xi(r,n);xu(q,Be,Yi(r,n));const Is=b?Yo(r,n):[],he=S.signals.vectorStore!==!1,j=Tl(g,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:ka(a.tables),queueCount:R.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=Xn(a,Z.map(f=>f.id)),We=$s({advisories:qe.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:ee?.procedureProtections??[],agents:c,containers:u,env:D,flagKeys:Is,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:b,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:R,rlsMetadata:ws,schema:a,schemaSnapshot:xe,shapes:q,storageRules:W,studioFeatures:j,useUmbrella:_,workflows:C}),je=Us(q,h.has("@lunora/db"),_),He=qs(u,a.jurisdiction),Ge=Bs(C),Ye=Vs(c),Qe=Ws(R),Xe=js(d),Ts=Hs(j.scheduler),Ze=Gs(a.vectorIndexes),te=Ys(a,_),Je=Qs(h.has("@lunora/seed")),se=e.apiSpec??"openapi",ve=se==="openapi"||se==="both",Ee=se==="openrpc"||se==="both",et=jn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue"),hasGlobal:a.tables.some(f=>$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:R.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:O,jurisdiction:a.jurisdiction,tableNames:a.tables.map(f=>f.name),useUmbrella:_,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:ve,wantsOpenRpc:Ee}),tt=pu(e.projectRoot),st=Hn({functions:B,httpRoutes:Ps,version:tt}),nt=Yn({functions:B,version:tt}),rt=`${JSON.stringify(st,void 0,2)}
8
- `,ot=`${JSON.stringify(nt,void 0,2)}
9
- `,it=Gn(st),at=Qn(nt),ye=E(n,fu),Cs=P(ye),Se=[];if(!e.dryRun){P(N)||Fs(N,{recursive:!0});const f=(U,V)=>{Oe(E(N,U),V),Se.push(U)},I=(U,V)=>{gu(E(N,U),V),V!==""&&Se.push(U)};f("app.ts",et),f("dataModel.ts",m),f("api.ts",$e),f("server.ts",$),f("functions.ts",Ue),f("shard.ts",We),f("crons.ts",Xe),f("vectors.ts",Ze),f("drizzle.global.ts",te.global),f("drizzle.shard.ts",te.shard),I("containers.ts",He),I("workflows.ts",Ge),I("agents.ts",Ye),I("queues.ts",Qe),I("scheduler.ts",Ts),I("seed.ts",Je),I("collections.ts",je),I("openapi.json",ve?rt:""),I("openapi.ts",ve?it:""),I("openrpc.json",Ee?ot:""),I("openrpc.ts",Ee?at:""),(!Cs||e.updateSchemaBaseline===!0)&&Oe(ye,ks(xe))}if(t){const f=Ae.now(),I=Math.round(f-s),U=Math.round(Ve-s),V=Math.round(f-Ve);console.error(`@lunora/codegen: codegen took ${I.toString()}ms (discovery ${U.toString()}ms, emit ${V.toString()}ms)`)}return{advisories:qe,advisorContext:ee,agents:c,containers:u,cronTriggers:[...new Set([...Xs(d),...w])],generated:{agents:Ye,api:$e,app:et,collections:je,containers:He,crons:Xe,dataModel:m,drizzleGlobal:te.global,drizzleShard:te.shard,functions:Ue,openApi:rt,openApiModule:it,openRpc:ot,openRpcModule:at,queues:Qe,seed:Je,server:$,shard:We,vectors:Ze,workflows:Ge},migrations:Z,outputDirectory:N,platformDiagnostics:S.diagnostics,queues:R,schemaSnapshot:xe,schemaSnapshotPath:ye,workflows:C,writtenFiles:Se}};export{fu as SCHEMA_SNAPSHOT_FILENAME,yu as createCodegenProject,hu as findTsconfig,md as refreshCodegenProject,hd as runCodegen};
@@ -1 +0,0 @@
1
- import{s as x}from"./paths-C-9fwEgQ.mjs";import{listLunoraSourceFiles as P,lunoraRelativePath as E}from"./listLunoraSourceFiles-DsxeRYvh.mjs";import{b as f,c as b}from"./classify-procedure-call-RjsZg8AH.mjs";import{Node as s,SyntaxKind as A}from"ts-morph";import{r as m,p as v,a as N}from"./parse-validator-DW5RNi_6.mjs";import{p as F,u as y}from"./unwrap-handler-return-FZxbgxxx.mjs";const z=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)},C=i=>{const e=i.getArguments()[0];return!e||!(s.isArrowFunction(e)||s.isFunctionExpression(e))?"unknown":y(e)},O=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)?F(e.call,()=>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},L=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},I=i=>{if(i===void 0||!s.isObjectLiteralExpression(i))return{};const e=L(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}},T=i=>{const e=f(i).find(t=>t.name==="expose");return e?I(e.call.getArguments()[0]):void 0},k=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)},V=8,l=(i,e=0)=>{if(e>V)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}},w=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]]:[]},D=i=>{const e=b(i);if(e){if(e.receiver){const t=T(e.receiver),r=S(e.receiver);return{args:O(e.receiver),...t?{expose:t}:{},kind:e.kind,...r?{output:r}:{},returnType:C(i),visibility:e.visibility}}return e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",visibility:e.visibility}:{args:k(i),kind:e.kind,returnType:z(i),visibility:e.visibility}}},h=(i,e,t)=>{const r=D(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}:{}}},j=(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},R=(i,e)=>{const t=[];for(const r of i.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations())for(const[o,a]of w(n)){const c=h(a,o,e);c&&t.push(c)}return t.push(...j(i,e)),t},B=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)}},q=(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(...R(o,a))}return r.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),B(r),r};export{q as default};
@@ -1 +0,0 @@
1
- import{Node as a}from"ts-morph";import{p as m,a as l}from"./parse-validator-DW5RNi_6.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./listLunoraSourceFiles-DsxeRYvh.mjs";import{p as f,u as g}from"./unwrap-handler-return-FZxbgxxx.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),E=new Set(["body","params","searchParams"]),v=new Set(["handler","stream"]),x=r=>{const e=r.getArguments()[0];if(e&&a.isStringLiteral(e))return e.getLiteralValue()},P=r=>{const e=r.getArguments()[0];return e&&a.isObjectLiteralExpression(e)?m(e):{}},S=r=>{if(!a.isCallExpression(r))return;const e=r.getExpression();if(!a.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const n=e.getExpression();if(!a.isIdentifier(n)||n.getText()!=="httpRoute")return;const s=x(r);return s===void 0?void 0:{method:o.toUpperCase(),path:s}},A=(r,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},n=r.getExpression();if(!a.isPropertyAccessExpression(n))return;let s=n.getExpression();for(;a.isCallExpression(s);){const i=s.getExpression();if(!a.isPropertyAccessExpression(i))break;const c=i.getName();if(u.has(c))break;if(E.has(c)){const p=P(s);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=s.getArguments()[0];p&&a.isExpression(p)&&(o.output=f(s,()=>l(p)))}s=i.getExpression()}const t=S(s);if(t)return o.method=t.method,o.path=t.path,o},T=r=>{const e=r.getArguments()[0];return!e||!(a.isArrowFunction(e)||a.isFunctionExpression(e))?"unknown":g(e)},b=(r,e,o,n)=>{const s=e.getName();if(!v.has(s))return;const t=A(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:T(r)}:{},...t.output?{output:t.output}:{}}},y=(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||!a.isCallExpression(t))continue;const i=t.getExpression();if(!a.isPropertyAccessExpression(i))continue;const c=b(t,i,s.getName(),e);c&&o.push(c)}return o},k=(r,e)=>{const o=d(e),n=[];for(const s of o){const t=r.getSourceFile(s)??r.addSourceFileAtPath(s),i=h(e,s);n.push(...y(t,i))}return n.sort((s,t)=>`${s.method} ${s.path}`.localeCompare(`${t.method} ${t.path}`)||s.filePath.localeCompare(t.filePath)),n};export{k as default};
@@ -1 +0,0 @@
1
- import{Node as l,SyntaxKind as m}from"ts-morph";import{posix as D}from"node:path";const _=/\bany\b(?!\s*(?:\?\s*)?:)/u,$=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,U=e=>_.test(e.replaceAll($,""));let b=[],p;const O=e=>{for(const t of e.getAncestors())if(l.isVariableDeclaration(t))return t.getName()},M=(e,t)=>{b.push({exportName:O(e),filePath:e.getSourceFile().getFilePath(),line:e.getStartLineNumber(),rendered:t})},me=e=>{p!==void 0&&M(p,e)},de=(e,t)=>{const n=p;p=e;try{return t()}finally{p=n}},Se=()=>{const e=b.length;return()=>{b.splice(e)}},pe=()=>{const e=b;return b=[],e},C="/_generated/",L=e=>{const t=[e.getSymbol(),e.getAliasSymbol()].flatMap(n=>n?.getDeclarations()??[]);return t.length>0&&t.every(n=>n.getSourceFile().getSymbol()===void 0)},P=/^(?<quote>["'])(?<specifier>.*)\k<quote>$/su,A=e=>{for(const t of e.getAncestors())if(l.isModuleDeclaration(t)){const n=P.exec(t.getName());if(n?.groups?.specifier!==void 0)return n.groups.specifier}},I=new WeakMap,h=(e,t)=>{const n=e.getSymbol();if(n===void 0)return;let r=I.get(n.compilerSymbol);return r===void 0&&(r=new Map,I.set(n.compilerSymbol,r)),r.has(t)||r.set(t,n.getExport(t)??e.getExportSymbols().find(s=>s.getName()===t)),r.get(t)},R=(e,t)=>e.getNamespaceImport()!==void 0||e.getNamedImports().some(n=>n.getName()===t),q=(e,t,n)=>e.getModuleSpecifierValue()===t&&R(e,n)?n:void 0,B=(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},F=(e,t,n)=>{if(!R(e,n))return;const r=e.getModuleSpecifierSourceFile(),s=r===void 0?void 0:h(r,n);return(s?.getAliasedSymbol()??s)?.getDeclarations().includes(t)===!0?n:void 0},V=/^\.\.?(?:$|\/)/u,K=new Map([[".cjs",".cjs"],[".cts",".cjs"],[".d.ts",".js"],[".js",".js"],[".jsx",".jsx"],[".mjs",".mjs"],[".mts",".mjs"],[".ts",".js"],[".tsx",".js"]]),W=(e,t)=>{const n=t.getModuleSpecifierValue();if(!V.test(n))return;const r=t.getModuleSpecifierSourceFile(),s=r===void 0?void 0:K.get(r.getExtension());if(r===void 0||s===void 0)return;const i=`${D.join(r.getDirectoryPath(),r.getBaseNameWithoutExtension())}${s}`,o=D.relative(e.getDirectoryPath(),i);return o.startsWith(".")?o:`./${o}`},G=(e,t,n)=>{const r=A(t);for(const s of e.getImportDeclarations()){const i=r===void 0?B(s,t)??F(s,t,n):q(s,r,n);if(i!==void 0)return{exportName:i,specifier:W(e,s)??s.getModuleSpecifierValue()}}},X=(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))}),f={kind:"verbatim"},S={kind:"expand"},H=new Set([m.ClassDeclaration,m.EnumDeclaration,m.EnumMember,m.InterfaceDeclaration,m.TypeAliasDeclaration]),Y=e=>A(e)!==void 0||l.isExportable(e)&&e.isExported(),J=(e,t)=>new RegExp(String.raw`(?<![$\w])${t.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`)}(?![$\w])`,"u").test(e),w=(e,t,n,r)=>{const s=e.getSourceFile();if(s.getSymbol()===void 0&&A(e)===void 0||!H.has(e.getKind()))return f;const i=s.getFilePath();if(i.includes(C))return f;if(i===n)return S;const o=l.isEnumMember(e)?e.getParent():e;if(!l.hasName(o))return S;const a=G(t.getSourceFile(),o,o.getName());return a===void 0?Y(o)||!J(r(),o.getName())?f:S:X(a.specifier,t)?S:{kind:"qualify",qualified:a}},j=(e,t,n)=>{const r=e.getAliasSymbol(),s=e.getSymbol(),i=new Set((r??s)?.getDeclarations());let o=!1,a;const c=()=>(a??=e.getText(t),a);for(const u of[s,r].flatMap(g=>g?.getDeclarations()??[])){const g=w(u,t,n,c);if(g.kind==="qualify"&&i.has(u))return g;o||=g.kind!=="verbatim"}return o?S:f},z=(e,t,n)=>{const r=l.isPropertySignature(e)||l.isPropertyDeclaration(e)?e.getTypeNode():void 0;if(r===void 0)return f;let s=!1;for(const i of[r,...r.getDescendantsOfKind(m.TypeReference)].filter(o=>l.isTypeReference(o))){const o=i.getTypeName().getSymbol();for(const a of(o?.getAliasedSymbol()??o)?.getDeclarations()??[]){const c=w(a,t,n,()=>i.getText());if(c.kind==="qualify")return c;s||=c.kind!=="verbatim"}}return s?S:f},Q=/^[A-Za-z_$][\w$]*$/u,Z=e=>Q.test(e)?e:JSON.stringify(e),k=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},y=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,E=(e,t,n,r=new Set)=>r.has(e)?!1:(r.add(e),j(e,t,n).kind!=="verbatim"||k(e).some(s=>E(s,t,n,r))?!0:y(e)?e.getProperties().some(s=>s.getDeclarations().some(i=>z(i,t,n).kind!=="verbatim")?!0:E(s.getTypeAtLocation(t),t,n,r)):!1),ee=(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())},te=32,ne=8,re=(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()===!0||o?.isIntersection()===!0?`(${a})[]`:`${a}[]`},se=(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(" | ")},oe=(e,t,n,r,s,i)=>{const o=[];for(const a of e.getIntersectionTypes()){const c=i(a,t,n,r,s);if(c===void 0)return;o.push(a.isUnion()?`(${c})`:c)}return o.join(" & ")},ie=(e,t,n,r,s,i)=>{if(!y(e))return;const o=[];for(const a of e.getProperties()){const c=a.getTypeAtLocation(t),u=ee(a,c),g=u&&c.isUnion()?c.getUnionTypes().filter(T=>!T.isUndefined()):[c],x=[];for(const T of g){const N=i(T,t,n,r+1,s);if(N===void 0)return;x.push(N)}o.push(`${Z(a.getName())}${u?"?":""}: ${x.join(" | ")}`)}return o.length>0?`{ ${o.join("; ")} }`:"{}"},ae=e=>{const t=e.getLiteralValue();return typeof t=="string"?JSON.stringify(t):typeof t=="number"?String(t):void 0},ce=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isClassDeclaration(t)||l.isClassExpression(t)),v=(e,t,n,r,s=new Set)=>{if(r.has(e)||s.has(e))return!1;if(n>te)return!0;const i=new Set(r).add(e);if(k(e).some(u=>v(u,t,n+1,i,s)))return!0;const o=e.getArrayElementType();if(o!==void 0)return v(o,t,n+1,i,s);if(L(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=y(e)&&e.getProperties().some(u=>v(u.getTypeAtLocation(t),t,n+1,i,s));return c||s.add(e),c},ue=(e,t,n,r,s,i,o)=>{const a=[];for(const c of t.getAliasSymbol()===void 0?t.getTypeArguments():t.getAliasTypeArguments()){const u=o(c,n,r,s+1,i);if(u===void 0)return;a.push(u)}return`import("${e.specifier}").${e.exportName}${a.length>0?`<${a.join(", ")}>`:""}`},le=e=>[e.getSymbol(),e.getAliasSymbol()].flatMap(t=>t?.getDeclarations()??[]).some(t=>l.isEnumDeclaration(t)||l.isEnumMember(t)),d=(e,t,n,r,s)=>{if(r>ne||s.has(e))return;const i=j(e,t,n);if(i.kind==="verbatim"&&!E(e,t,n))return e.getText(t);const o=new Set(s).add(e);if(!ce(e)){if(e.isEnumLiteral())return ae(e);if(i.kind==="qualify"&&!le(e)){const a=ue(i.qualified,e,t,n,r,o,d);if(a!==void 0)return a}return e.isArray()?re(e,t,n,r,o,d):e.isUnion()?se(e,t,n,r,o,d):e.isIntersection()?oe(e,t,n,r,o,d):ie(e,t,n,r,o,d)}},be=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"||U(i)||v(n,e,0,new Set))return"unknown";const o=e.getSourceFile().getFilePath();if(E(n,e,o)){const a=d(n,e,o,0,new Set);return a===void 0&&M(e,i),a??"unknown"}return i};export{me as a,Se as c,d as e,U as i,de as p,E as r,pe as t,be as u};