@lunora/codegen 1.0.0-alpha.62 → 1.0.0-alpha.64

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.
Files changed (35) hide show
  1. package/dist/index.d.mts +20 -3
  2. package/dist/index.d.ts +20 -3
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{FLAGS_FILENAME-DW5oGq1q.mjs → FLAGS_FILENAME-C1GWerCB.mjs} +1 -1
  5. package/dist/packem_shared/GENERATED_HEADER-Sl8NoQFl.mjs +1 -0
  6. package/dist/packem_shared/MUTATORS_FILENAME-BWPAtQ2T.mjs +1 -0
  7. package/dist/packem_shared/{NOTIFY_FILENAME-C-c7Lg-U.mjs → NOTIFY_FILENAME-DP6qvFBX.mjs} +1 -1
  8. package/dist/packem_shared/{OPENRPC_VERSION-B_EyUGlr.mjs → OPENRPC_VERSION-BcivFYIX.mjs} +1 -1
  9. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CthmqJlJ.mjs +3 -0
  10. package/dist/packem_shared/SHAPES_FILENAME-maut3z1K.mjs +1 -0
  11. package/dist/packem_shared/{buildOpenApiDocument-f291wyY3.mjs → buildOpenApiDocument-BJudKDP_.mjs} +1 -1
  12. package/dist/packem_shared/{discoverAuthApiCalls-DOfSQqVK.mjs → discoverAuthApiCalls-Ba6W92HB.mjs} +1 -1
  13. package/dist/packem_shared/discoverCrons-2nUpw6do.mjs +1 -0
  14. package/dist/packem_shared/discoverFunctions-zrIQk7J8.mjs +1 -0
  15. package/dist/packem_shared/{discoverHttpRoutes-BOWz6y_n.mjs → discoverHttpRoutes-Bf_T_03b.mjs} +1 -1
  16. package/dist/packem_shared/{discoverInserts-BtteTyNy.mjs → discoverInserts-DveVeP5h.mjs} +1 -1
  17. package/dist/packem_shared/{discoverMaskProcedures-COPmwMBm.mjs → discoverMaskProcedures-BkBquCFR.mjs} +1 -1
  18. package/dist/packem_shared/discoverMigrations-T2xb-1rn.mjs +1 -0
  19. package/dist/packem_shared/{discoverNondeterministicCalls-Dmgc4QBx.mjs → discoverNondeterministicCalls-BymnOR9k.mjs} +1 -1
  20. package/dist/packem_shared/{discoverQueries-CcfuGKHh.mjs → discoverQueries-DNRA-G2a.mjs} +1 -1
  21. package/dist/packem_shared/{discoverR2sqlCalls-CjZKvg-N.mjs → discoverR2sqlCalls-YEjvGcEq.mjs} +1 -1
  22. package/dist/packem_shared/{discoverRlsMetadata-BXmNOgry.mjs → discoverRlsMetadata-DO3qlLXX.mjs} +1 -1
  23. package/dist/packem_shared/{discoverSandboxUsage-CDdBqWcM.mjs → discoverSandboxUsage-JwrmSN9l.mjs} +1 -1
  24. package/dist/packem_shared/{discoverStorageRulesMetadata-b71cJJHz.mjs → discoverStorageRulesMetadata-CCztRKjw.mjs} +1 -1
  25. package/dist/packem_shared/{emit-Cz-5gRp0.mjs → emit-Bp0nOR_O.mjs} +201 -180
  26. package/dist/packem_shared/{emitApp-DbpB1vA1.mjs → emitApp-BzO6O7Lx.mjs} +7 -7
  27. package/dist/packem_shared/module-specifiers-8FEEiUcv.mjs +1 -0
  28. package/package.json +3 -3
  29. package/dist/packem_shared/GENERATED_HEADER-4TxGhJDQ.mjs +0 -1
  30. package/dist/packem_shared/MUTATORS_FILENAME-BKKPROzu.mjs +0 -1
  31. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-B-b-ZgwS.mjs +0 -3
  32. package/dist/packem_shared/SHAPES_FILENAME-DTkSJSsg.mjs +0 -1
  33. package/dist/packem_shared/discoverCrons-B09_uEuL.mjs +0 -1
  34. package/dist/packem_shared/discoverFunctions-BdibLQmc.mjs +0 -1
  35. package/dist/packem_shared/discoverMigrations-iGMlp9YJ.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{c as w,w as E}from"./emit-Cz-5gRp0.mjs";const D=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,m=w.map(({appMethod:e,key:t})=>[D(t),e.method,e.configKey,e.doc]),g=e=>m.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],x=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],R=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:a,hasGlobal:n,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:u,hasStorage:d,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:v}=e,i=c?"lunorash/runtime":"@lunora/runtime",b=["ExecutionContextLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&b.push("GlobalIntrospector"),a&&b.push("FrameworkHostHandler");const f=[...n||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...a?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...x(t,r),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(l),...u?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...d?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...b].toSorted((S,y)=>S.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...n||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...v?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},$=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. */
1
+ import{d as w,w as E}from"./emit-Bp0nOR_O.mjs";const D=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,m=w.map(({appMethod:e,key:t})=>[D(t),e.method,e.configKey,e.doc]),g=e=>m.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],x=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],R=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],O=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,C=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],L=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasAccess:t,hasAuth:r,hasFramework:n,hasGlobal:a,hasHyperdriveGlobal:o,hasKv:l,hasQueue:s,hasScheduler:u,hasStorage:d,hasWorkflow:h,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:v}=e,i=c?"lunorash/runtime":"@lunora/runtime",b=["ExecutionContextLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];a&&b.push("GlobalIntrospector"),n&&b.push("FrameworkHostHandler");const f=[...a||o?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...n?["withFrameworkWorker"]:[]].join(", ");return[...r?['import type { LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...x(t,r),...a?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { createD1CtxDb, facetGlobalColumn, listGlobalTables, readGlobalTablePage } from "@lunora/d1";']:[],...o?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(l),...u?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...d?['import type { R2BucketLike, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...h?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),`import type { ${[...b].toSorted((S,y)=>S.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...L(e),...a||o?['import schema from "../schema.js";']:[],...O(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...s?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...v?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},$=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. */
2
2
  interface StorageDeclaration<Env> {
3
3
  /** The default R2 bucket binding (the bare \`ctx.storage\`). */
4
4
  bucket: Selector<Env, R2BucketLike>;
@@ -8,7 +8,7 @@ interface StorageDeclaration<Env> {
8
8
  publicBaseUrl?: Selector<Env, string>;
9
9
  /** HMAC secret for signed URLs. */
10
10
  signingSecret?: Selector<Env, string>;
11
- }`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\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 D1 binding its SQL adapter reads. 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`). */\n d1: Selector<Env, unknown>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}"]:[]],q=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...g(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],j=e=>m.filter(([t])=>e[t]).map(([,t,r,a])=>` /** ${a} */
11
+ }`]:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\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 D1 binding its SQL adapter reads. 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`). */\n d1: Selector<Env, unknown>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}"]:[]],q=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...g(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],j=e=>m.filter(([t])=>e[t]).map(([,t,r,n])=>` /** ${n} */
12
12
  public ${t}(factory: NonNullable<ShardConfig["${r}"]>): this {
13
13
  this.shardExtras.${r} = factory;
14
14
 
@@ -137,7 +137,7 @@ ${t.join(`
137
137
  }
138
138
  }`]:[],...e.hasStorage?[` if (this.storageDeclaration) {
139
139
  Object.assign(options, this.buildStorageAdmin(env));
140
- }`]:[],...e.hasKv?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasNotify?[" options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env) : undefined;"]:[]," options.logArchive = resolveLogArchiveFromEnv(env);",...e.hasAuth?[` if (this.authDeclaration) {
140
+ }`]:[],...e.hasKv?[" options.kvIntrospector = createKvIntrospectorFromEnv(env);"]:[],...e.hasNotify?[" options.notifySubscriptionStore = notifyConfig.store ? notifyConfig.store(env as Record<string, unknown>) : undefined;"]:[]," options.logArchive = resolveLogArchiveFromEnv(env);",...e.hasAuth?[` if (this.authDeclaration) {
141
141
  options.authHandler = (request) => {
142
142
  const auth = getAuth();
143
143
 
@@ -270,7 +270,7 @@ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector =
270
270
  readTablePage: (options) => readGlobalTablePage(exec, schema as never, options),
271
271
  };
272
272
  };
273
- `:"",U=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),F=e=>{const{hasAuth:t}=e,r=$(e),a=N(e),n=t?` let auth: LunoraAuth | null = null;
273
+ `:"",U=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,r)=>t.localeCompare(r)).join(", "),F=e=>{const{hasAuth:t}=e,r=$(e),n=N(e),a=t?` let auth: LunoraAuth | null = null;
274
274
  `:"",o=t?`
275
275
  const ensureAuth = async (env: Env): Promise<void> => {
276
276
  if (!this.authDeclaration || auth) {
@@ -336,7 +336,7 @@ ${v}
336
336
  // build, so the first request constructs them and every later request on
337
337
  // the same isolate reuses them.
338
338
  let worker: LunoraWorker | null = null;
339
- ${n}${o}
339
+ ${a}${o}
340
340
  ${d}
341
341
 
342
342
  const composed: ComposedApp = {
@@ -384,9 +384,9 @@ ${G(e).join(`
384
384
  options.adminToken = this.adminToken(env);
385
385
  }
386
386
 
387
- ${a.join(`
387
+ ${n.join(`
388
388
 
389
- `)}${a.length>0?`
389
+ `)}${n.length>0?`
390
390
 
391
391
  `:""} for (const fn of this.extendFns) {
392
392
  Object.assign(options, fn(env, { ...options }));
@@ -0,0 +1 @@
1
+ const s=/(?:^|\/)_generated\/server(?:\.js)?$/u,r=new Set(["@lunora/server","lunorash/server"]),n=e=>r.has(e),t=e=>s.test(e),o=e=>n(e)||t(e),a=new Set(["@lunora/scheduler",...r]),u=e=>a.has(e);export{u as E,n as o,o as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.62",
3
+ "version": "1.0.0-alpha.64",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,8 +46,8 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.41",
50
- "@lunora/agent": "1.0.0-alpha.17",
49
+ "@lunora/advisor": "1.0.0-alpha.43",
50
+ "@lunora/agent": "1.0.0-alpha.19",
51
51
  "@lunora/container": "1.0.0-alpha.16",
52
52
  "@lunora/errors": "1.0.0-alpha.8",
53
53
  "@lunora/queue": "1.0.0-alpha.10",
@@ -1 +0,0 @@
1
- import"@lunora/agent/component";import"@lunora/errors";import{w as m,a as r,E as o,n,o as l,L as g,X as u,G as E,z as p,g as C,_ as D,b as S,u as c,K as d,Y as A,D as z,Z as b}from"./emit-Cz-5gRp0.mjs";import"./paths-BmX5O1sG.mjs";export{m as GENERATED_HEADER,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,g as emitContainers,u as emitCrons,E as emitDataModel,p as emitDrizzleSchema,C as emitFunctions,D as emitQueues,S as emitSeed,c as emitServer,d as emitShard,A as emitVectors,z as emitWorkflows,b as emitWranglerCronTriggers};
@@ -1 +0,0 @@
1
- import{existsSync as u}from"node:fs";import{join as l}from"node:path";import{Node as i,SyntaxKind as a}from"ts-morph";import{diagnosticAt as p}from"./CodegenDiagnosticError-DPezpZTz.mjs";const m="mutators.ts",f=new Set(["@lunora/server","lunorash/server"]),d=e=>{const r=e.getSymbol();if(!r)return e.getText()==="defineMutator";for(const t of r.getDeclarations())if(i.isImportSpecifier(t))return f.has(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMutator":!1;return!1},g=e=>{const r=e.getSymbol();if(!r)return!1;for(const t of r.getDeclarations()){if(!i.isNamespaceImport(t))continue;const o=t.getFirstAncestorByKind(a.ImportDeclaration);return o!==void 0&&f.has(o.getModuleSpecifierValue())}return!1},x=e=>{if(i.isIdentifier(e))return d(e);if(i.isPropertyAccessExpression(e)){const r=e.getExpression();return e.getName()==="defineMutator"&&i.isIdentifier(r)&&g(r)}return!1},M=e=>{const r=[];for(const t of e.getVariableDeclarations()){if(!t.isExported())continue;const o=t.getInitializer();if(o?.getKind()!==a.CallExpression)continue;const s=o.getExpression();if(!x(s))continue;const n=t.getNameNode();if(!i.isIdentifier(n))throw p(n,"defineMutator exports must be plain named exports (no destructuring)");r.push({exportName:n.getText(),filePath:"mutators"})}return r},E=(e,r)=>{const t=l(r,m);if(!u(t))return[];const o=e.getSourceFile(t)??e.addSourceFileAtPath(t),s=M(o);return s.sort((n,c)=>n.exportName.localeCompare(c.exportName)),s};export{m as MUTATORS_FILENAME,E as discoverMutators,x as isDefineMutatorCallee};
@@ -1,3 +0,0 @@
1
- import{existsSync as E,readFileSync as ye,mkdirSync as qt,writeFileSync as Bt,rmSync as Vt}from"node:fs";import{join as g,dirname as de}from"node:path";import{performance as ge}from"node:perf_hooks";import{LunoraError as q}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as Xe}from"ts-morph";import{lintSchema as Ut}from"./formatAdvisories-DZvv-0MG.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as f,classifyProcedureCall as K,inlineHandler as Wt,procedureHandler as pt,chainUsesWrappedCall as mt,isDatabaseAccessor as k,chainHasStep as Gt,discoverFunctions as _t}from"./discoverFunctions-BdibLQmc.mjs";import{discoverAgents as Ht}from"./AGENTS_FILENAME-BesaDYkL.mjs";import Qt from"./discoverAuthApiCalls-DOfSQqVK.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import Jt from"./discoverCrons-B09_uEuL.mjs";import{diagnosticAt as _}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{r as fe,a as Zt,G as Yt,n as es,u as ts,g as ss,K as rs,o as ns,L as is,D as os,E as as,_ as cs,X as us,Y as ls,z as ds,b as gs,Z as fs}from"./emit-Cz-5gRp0.mjs";import{discoverFlagKeys as ps}from"./FLAGS_FILENAME-DW5oGq1q.mjs";import ms from"./discoverHttpRoutes-BOWz6y_n.mjs";import xs from"./discoverInserts-BtteTyNy.mjs";import hs,{discoverMaskStrategies as Es,discoverMaskMetadata as ys}from"./discoverMaskProcedures-COPmwMBm.mjs";import As from"./discoverMigrations-iGMlp9YJ.mjs";import{MUTATORS_FILENAME as $s,isDefineMutatorCallee as Ss,discoverMutators as Ns}from"./MUTATORS_FILENAME-BKKPROzu.mjs";import vs from"./discoverNondeterministicCalls-Dmgc4QBx.mjs";import{discoverNotifyConfig as bs,discoverNotifyCalls as Ps}from"./NOTIFY_FILENAME-C-c7Lg-U.mjs";import ws from"./discoverQueries-CcfuGKHh.mjs";import{discoverQueues as Is}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Ls from"./discoverR2sqlCalls-CjZKvg-N.mjs";import Os,{discoverRlsMetadata as Fs}from"./discoverRlsMetadata-BXmNOgry.mjs";import{discoverSandboxUsage as Ds}from"./discoverSandboxUsage-CDdBqWcM.mjs";import Ts from"./discoverSchema-m2voTncu.mjs";import{secretKindOf as Cs,redact as ks}from"./redact-CQ8-to6l.mjs";import{discoverShapes as Ks}from"./SHAPES_FILENAME-DTkSJSsg.mjs";import Rs from"./discoverStorageRulesMetadata-b71cJJHz.mjs";import{e as Ms}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as zs}from"./WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{emitApp as js}from"./emitApp-DbpB1vA1.mjs";import{buildOpenApiDocument as qs,emitOpenApiModule as Bs}from"./buildOpenApiDocument-f291wyY3.mjs";import{buildOpenRpcDocument as Vs,emitOpenRpcModule as Us}from"./OPENRPC_VERSION-B_EyUGlr.mjs";import{buildSchemaSnapshot as Ws,serializeSchemaSnapshot as Gs}from"./SCHEMA_SNAPSHOT_VERSION-Bpf1FGMG.mjs";const xt=new Set(["delete","get","head","options","patch","post","put"]),_s=new Set(["handler","stream"]),Hs=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Je=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Qs=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},Xs=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return Qs(s)},Js=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(Je.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Je.has(s.getText()))return!0}return!1},Zs=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!_s.has(r.getName()))return;const n=Xs(s);if(!n||!Hs.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&Js(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},Ys=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Zs(n,t);o&&s.push(o)}return s},er=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ys(n,f(t,r)))}return s},Ze=e=>{if(e.getText()!=="args")return!1;const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(i.isPropertyAssignment(t)&&t.getNameNode()===e)},Ye=e=>{if(e.getText()!=="ctx")return!1;const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(i.isPropertyAssignment(t)&&t.getNameNode()===e)},pe=e=>i.isIdentifier(e)?Ye(e):e.getDescendantsOfKind(u.Identifier).some(t=>Ye(t)),et=(e,t)=>{if(e.getText()!==t)return!1;const s=e.getParent();return i.isPropertyAccessExpression(s)&&s.getNameNode()===e?!1:!(i.isPropertyAssignment(s)&&s.getNameNode()===e)},tr=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},b=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e))return e.getName()},he=e=>i.isIdentifier(e)?Ze(e):e.getDescendantsOfKind(u.Identifier).some(t=>Ze(t)),L=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;const r=e.getStart();let n,o=-1;for(const a of s.getDescendantsOfKind(u.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<r&&l>o&&(n=c,o=l)}return n},P=e=>{if(he(e))return!0;const t=L(e);return t!==void 0&&he(t)},D=e=>{if(pe(e))return!0;const t=L(e);if(t!==void 0&&pe(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(u.Identifier)).some(r=>{const n=L(r);return n!==void 0&&pe(n)})},B=(e,t)=>i.isIdentifier(e)?et(e,t):e.getDescendantsOfKind(u.Identifier).some(s=>et(s,t)),sr=(e,t)=>{if(B(e,t))return!0;const s=L(e);if(s!==void 0&&B(s,t))return!0;const r=tr(e);if(r!==void 0){const n=L(r);return n!==void 0&&B(n,t)}return!1},h=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},rr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",nr=(e,t)=>{if(!rr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!P(s)||D(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},ir=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=nr(r,t);n&&s.push(n)}return s},or=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ir(n,f(t,r)))}return s},ar=new Set(["generateText","streamText"]),cr=new Set(["messages","prompt","system"]),ur=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],lr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of ur)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},dr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=lr(t);if(s!==void 0)return s}},gr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},fr=e=>{if(he(e))return!0;const t=gr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},pr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!cr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&fr(s))return!0}return!1},mr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=b(r.getExpression());if(n===void 0||!ar.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(b(c.getExpression())==="tool"&&(a=dr(c),a!==void 0))break;a!==void 0&&s.push({exportName:h(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:pr(o)})}return s},xr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...mr(n,f(t,r)))}return s},hr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Er=(e,t)=>{if(!hr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!P(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},yr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Er(r,t);n&&s.push(n)}return s},Ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yr(n,f(t,r)))}return s},$r=/\.check\(|\.meta\(|length|max/iu,Sr=/\bv\.any\s*\(/u,Nr=/\bv\.string\s*\(/u,vr=e=>Sr.test(e),br=e=>Nr.test(e)&&!$r.test(e),Pr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("args");if(!s||!i.isPropertyAssignment(s))return;const r=s.getInitializer();return r&&i.isObjectLiteralExpression(r)?r:void 0},wr=e=>{const t=[];let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const n=s.getArguments()[0];n&&i.isObjectLiteralExpression(n)&&t.push(n)}s=r.getExpression()}return t},Ir=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();vr(a)?t.push(c):br(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Lr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const n=r.receiver?wr(r.receiver):[Pr(s)].filter(c=>c!==void 0),{anyArgs:o,unboundedStringArgs:a}=Ir(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Or=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Lr(n,t);o&&s.push(o)}return s},Fr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Or(n,f(t,r)))}return s},I=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},me=e=>e?.getKind()===u.TrueKeyword,Dr=e=>e?.getKind()===u.FalseKeyword,Tr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Cr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),kr=e=>{const t=I(e,"advanced"),s=I(e,"emailAndPassword"),r=I(e,"session");return{analyzable:!0,disableCsrfCheck:me(I(t,"disableCSRFCheck")),emailPasswordEnabled:me(I(s,"enabled")),requireEmailVerification:me(I(s,"requireEmailVerification")),secureCookiesDisabled:Dr(I(t,"useSecureCookies")),sessionFreshAgeZero:Tr(I(r,"freshAge")),trustedOriginsWildcard:Cr(I(e,"trustedOrigins"))}},Kr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Rr=(e,t)=>{if(b(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?kr(s):Kr();return{exportName:h(e),file:t,line:e.getStartLineNumber(),...n}},Mr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Rr(r,t);n&&s.push(n)}return s},zr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Mr(n,f(t,r)))}return s},jr=(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},qr=(e,t,s)=>{const r=jr(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!P(n)||D(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:r}},Br=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=qr(n,t,s);o&&r.push(o)}return r},H=(e,t,s)=>{const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...Br(o,f(t,n),s))}return r},Vr=new Set(["content","pdf","scrape","screenshot"]),Ur=(e,t)=>H(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Vr}),Wr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Gr=new Set(["RateLimiter"]),_r=new Set(["extend"]),ht=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},tt=e=>e&&i.isObjectLiteralExpression(e)?ht(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Hr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},Qr=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?Hr(e):void 0},Xr=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Qr(t.getBody());return s?ht(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Jr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=b(r.getExpression());n!==void 0&&(Wr.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...tt(r.getArguments()[0])}):_r.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...Xr(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=b(r.getExpression());n===void 0||!Gr.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...tt(r.getArguments()[0])})}return s},Zr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Jr(n,f(t,r)))}return s},st="ctx.containers.",Yr=e=>{if(!e.startsWith(st))return!1;const t=e.slice(st.length);return t.length>0&&!t.includes(".")},en=(e,t)=>H(e,t,{argIndex:0,matchReceiver:Yr,methods:new Set(["get"])}),tn=new Set(["allow","deny","setAllowed"]),sn=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())},rn=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!sn(e)))return{detail:"enableInternet: true",exportName:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},nn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!tn.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},on=(e,t)=>rn(e,t)??nn(e,t),an=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=on(r,t);n&&s.push(n)}return s},cn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...an(n,f(t,r)))}return s},un="env.ts",Et=new Set(["@lunora/server","lunorash/server"]),ln=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Et.has(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Et.has(r.getModuleSpecifierValue())}return!1},gn=e=>{if(i.isIdentifier(e))return ln(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&dn(t)}return!1},fn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!gn(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},pn=(e,t)=>{const s=g(t,un);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=fn(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},mn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),xn=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return mn.has(s)?s:void 0},hn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},En=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=xn(a);if(c===void 0)continue;const l=a.getArguments()[0],p=l&&i.isObjectLiteralExpression(l)?hn(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:p.analyzable,emptyKeys:p.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:p.presentKeys})}}return s},yn=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),An=new Set(["dbRateLimit","rateLimit"]),$n=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},Sn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Nn=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const r=yn.get(s);if(r!==void 0)return{callee:s,exportName:h(e),failOpen:$n(e.getArguments()[r]),file:t,limitName:An.has(s)?Sn(e):"",line:e.getStartLineNumber()}},vn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Nn(r,t);n&&s.push(n)}return s},bn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...vn(n,f(t,r)))}return s},Pn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},wn=(e,t)=>{const s=Object.fromEntries(fe.map(r=>[r.key,!1]));for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Pn(n);for(const c of fe)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(fe.every(c=>s[c.key]))break}return s},In=["providerSubscriptionId","state"],Ln=["providerEventId","processedAt"],rt=(e,t)=>t.every(s=>s in e.shape),On=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&rt(t,In)&&rt(s,Ln)},Fn=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),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/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),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:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Dn=e=>i.isIdentifier(e)&&e.getText()==="ctx",Tn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Dn(t.getExpression())},Cn=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},kn=(e,t)=>{if(!Tn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=Cn(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:h(e),file:t,key:n,line:e.getStartLineNumber()}},Kn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=kn(r,t);n&&s.push(n)}return s},Rn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Kn(n,f(t,r)))}return s},Mn=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},zn=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},jn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))Mn(a)&&s.push({file:o,indexName:zn(a),line:a.getStartLineNumber()})}return s},qn=new Set(["delete","get","head","options","patch","post","put"]),Bn=new Set(["handler","stream"]),Vn=new Set(["runAction","runMutation"]),Un=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),U=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,nt=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,it=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},ot=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Vn.has(a)&&U(c,t))return a;if(Un.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&U(c.getExpression(),t))return`db.${a}`}},at=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&U(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!U(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},Wn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Bn.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(qn.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},Gn=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=nt(e.getArguments()[0]),l=c&&it(c,!0);if(!c||l===void 0)return;const p=ot(c,l);return p===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:at(c,l),sideEffect:p}}const r=Wn(e);if(r===void 0)return;const n=nt(e.getArguments()[0]),o=n&&it(n,!1);if(!n||o===void 0)return;const a=ot(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:at(n,o),sideEffect:a}},_n=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Gn(r,t);n&&s.push(n)}return s},Hn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(..._n(n,f(t,r)))}return s},Qn=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Xn=new Set(["append","set"]),Ae=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",yt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ct=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>Qn.has(Ae(s.getExpression()))&&B(s,t)),Jn=(e,t)=>{if(ct(e,t))return!0;const s=L(e);return s!==void 0&&ct(s,t)},Ee=(e,t)=>sr(e,t)&&!Jn(e,t),Zn=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=L(e);return t!==void 0&&i.isNewExpression(t)&&Ae(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=L(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},$e=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&Ee(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:yt(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();Ee(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=W(r.getExpression());n!==void 0&&$e(n,t,s)}},At=(e,t)=>{const s=W(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=W(r.getInitializer());n!==void 0&&$e(n,"response-init",t)},Yn=(e,t)=>{const s=Ae(e.getExpression());if(s==="Response")At(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&$e(r,"headers-ctor",t)}},ei=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){At(e.getArguments()[1],t);return}if(Xn.has(r)&&Zn(n)){const o=e.getArguments()[1];o!==void 0&&Ee(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:yt(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},ti=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))Yn(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))ei(s,t)},si=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=Wt(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return ti(r,{exportName:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},ri=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...si(r,t));return s},ni=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ri(n,f(t,r)))}return s},$t="identity.ts",St=new Set(["@lunora/server","lunorash/server"]),ii=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return St.has(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},oi=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&St.has(r.getModuleSpecifierValue())}return!1},ai=e=>{if(i.isIdentifier(e))return ii(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&oi(t)}return!1},ci=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!ai(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},ui=(e,t)=>{const s=g(t,$t);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=ci(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},li=new Set(["auth","context.auth","ctx.auth"]),di="userId",gi=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},fi=(e,t)=>{const s=g(t,$t);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(b(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?gi(o):void 0}},ut=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return li.has(e.getExpression().getText())?e:void 0},pi=e=>{if(i.isPropertyAccessExpression(e)&&ut(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&ut(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},mi=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=pi(n);o!==void 0&&r.push({declared:o===di||s.has(o),exportName:h(n),file:t,key:o,line:n.getStartLineNumber()})}return r},xi=(e,t)=>{const s=fi(e,t);if(s===void 0)return[];const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...mi(o,f(t,n),s))}return r},hi=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Ei=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=hi(s);if(!(!r||!P(r)||D(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ei(r,t);n&&s.push(n)}return s},Ai=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(n,f(t,r)))}return s},$i=new Set(["delete","get","getRaw","getWithMetadata","put"]),Si=(e,t)=>H(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:$i}),Ni=new Set(["queue","send"]),lt=new Set(["bcc","cc","to"]),vi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ni.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},bi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return lt.has(t.getName())&&P(r)&&!D(r)}if(!i.isPropertyAssignment(t)||!lt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&P(s)&&!D(s)}):!1,Pi=(e,t)=>{const s=vi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!bi(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},wi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Pi(r,t);n&&s.push(n)}return s},Ii=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...wi(n,f(t,r)))}return s},Li=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Oi=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},Fi=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return Ss(s.getExpression())?s:void 0},Di=e=>{const t=Fi(e),s=t===void 0?void 0:Oi(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>Li(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Ti=e=>e.getVariableDeclarations().flatMap(t=>Di(t)),Ci=(e,t)=>{const s=g(t,$s);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ti(r)},ki=new Set(["delete","get","patch"]),Ki=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Ri=new Set(["auth","identity","session","user"]),Mi=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),zi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!k(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},ji=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 r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},qi=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),Bi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,Vi=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>qi(s.getExpression(),t)&&Bi(s.getThenStatement())),Ui=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!ki.has(n))continue;const o=r.getExpression();if(!(k(o)||i.isPropertyAccessExpression(o)&&k(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},Wi=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},Gi=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>Wi(s)==="ctx")),_i=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Mi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Hi=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(Ki.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Ri.has(t.getName()))return!0}return Gi(e)||_i(e)},Qi=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=pt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=Hi(n),c=new Set,l=[];for(const p of n.getDescendantsOfKind(u.CallExpression)){const y=zi(p);if(y===void 0)continue;const O=ji(p);if(O===void 0||c.has(O)||!Vi(n,O))continue;const R=Ui(n,O);R!==void 0&&(c.add(O),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:y,usesRls:o,visibility:r.visibility}))}return l},Xi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Qi(c,o))}return s},Ji=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Zi=new Set(["insert","insertManyUnsafe","patch","replace"]),Yi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Zi.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},eo=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},to=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!Ji.has(a))&&P(c)&&!D(c)&&n.push({exportName:h(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},so=(e,t)=>{const s=Yi(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?eo(r,s).flatMap(n=>to(n,s,e,t)):[]},ro=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...so(r,t));return s},no=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ro(n,f(t,r)))}return s},io=e=>{const t=g(e,"package.json");if(!E(t))return new Set;try{const s=JSON.parse(ye(t,"utf8")),r=new Set;for(const n of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const o=s[n];if(o!==null&&typeof o=="object")for(const a of Object.keys(o))r.add(a)}return r}catch{return new Set}},oo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ao=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,co=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ao(t.getInitializer()):void 0},uo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=b(r.getExpression());if(n===void 0||!oo.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?co(o):void 0;s.push({callee:n,exportName:h(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},lo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...uo(n,f(t,r)))}return s},go=new Set(["defineQueue","defineWorkflow"]),fo=new Set(["run","runAction","runMutation","runQuery"]),po=new Set(["api","internal"]),mo=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},xo=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 r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},vt=(e,t)=>e===t||e.startsWith(`${t}.`),bt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},dt=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)},Pt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>dt(s));return i.isIdentifier(e)&&dt(e)&&t.push(e),t},ho=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},Eo=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},yo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:Eo(e),n=new Set,o=a=>bt(a).some(c=>r.some(l=>vt(c.getText(),l)))?!0:Pt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of ho(a))n.add(l)}return{names:n,prefixes:r}},Ao=(e,t)=>bt(e).some(s=>t.prefixes.some(r=>vt(s.getText(),r)))?!0:Pt(e).some(s=>t.names.has(s.getText())),$o=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 r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!po.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},So=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const n=yo(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!fo.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!Ao(l,n))continue;const p=$o(a.getArguments()[0]);p!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:h(a),line:a.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return o},No=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=mo(r);if(n===void 0||!go.has(n))continue;const o=xo(r);o!==void 0&&s.push(...So(o,n==="defineQueue"?"queue":"workflow",t))}return s},vo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...No(n,f(t,r)))}return s},gt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},bo=/account|credential|member|passkey|session|user/iu,wt=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Po=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},wo=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},V={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Io=e=>{const t=wo(e),s=t?wt(t):void 0;if(t&&s==="protectPublic"){const r=Po(t);return{...V,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in gt?{...V,[gt[s]]:!0}:V},Lo=e=>{const t={...V};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=Io(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},Oo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insert")return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!!(r&&i.isStringLiteral(r)&&bo.test(r.getLiteralText()))},Fo=new Set(["create","runAfter","runAt","send","sendBatch"]),Do=new Set(["queues","scheduler","workflows"]),To=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Fo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Do.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Co=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},ko=new Set(["generateObject","generateText","streamObject","streamText"]),Ko=e=>{const t=wt(e);if(t===void 0||!ko.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Ro=e=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(t=>{const s=t.getName();if(s!=="mail"&&s!=="email")return!1;const r=t.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),Mo=e=>{let t=!1,s=!1,r=!1,n=!1;for(const o of e.getDescendantsOfKind(u.CallExpression))if(Oo(o)&&(n=!0),To(o)&&(t=!0),Co(o)&&(r=!0),Ko(o)&&(s=!0),n&&t&&r&&s)break;return{callsMail:Ro(e),fanOut:t,unboundedAiGeneration:s,usesInsertManyUnsafe:r,writesUserTable:n}},zo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?Lo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},{callsMail:o,fanOut:a,unboundedAiGeneration:c,usesInsertManyUnsafe:l,writesUserTable:p}=Mo(e);return{callsMail:o,exportName:e.getName(),fanOut:a,file:t,kind:r.kind,unboundedAiGeneration:c,usesCaptcha:n.usesCaptcha,usesEmailGate:n.usesEmailGate,usesInsertManyUnsafe:l,usesMask:n.usesMask,usesRateLimit:n.usesRateLimit,usesRls:n.usesRls,visibility:r.visibility,writesUserTable:p}},jo=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=zo(n,t);o&&s.push(o)}return s},qo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...jo(n,f(t,r)))}return s},Bo=new Set(["dbRateLimit","rateLimit"]),Vo=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Uo=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Wo=e=>i.isArrowFunction(e)?e.getBody():e,Go=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Bo.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=Vo(r);if(!n)return;const o=Wo(n);if(!(!P(o)||D(o)))return{callee:s,exportName:h(e),file:t,limitName:Uo(e),line:e.getStartLineNumber()}},_o=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Go(r,t);n&&s.push(n)}return s},Ho=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(..._o(n,f(t,r)))}return s},Qo=new Set(["findFirst","findFirstOrThrow","findMany","get"]),Xo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Qo.has(t.getName()))return;const s=t.getExpression();if(k(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&k(s.getExpression()))return s.getName()},Jo=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&k(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Zo=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=Zo(e);if(i.isIdentifier(s)){if(t)return;const r=L(s);return r===void 0?void 0:It(r,!0)}if(i.isCallExpression(s))return Xo(s)??Jo(s)},Yo=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},ea=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=pt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Gt(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,l=[];for(const p of Yo(n)){const y=It(p);y===void 0||c.has(y)||(c.add(y),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),table:y,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},ta=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ea(c,o))}return s},sa=new Set(["findFirst","findFirstOrThrow","findMany"]),ra=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!sa.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},na=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},ia=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},oa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=ra(o);if(a===void 0)continue;const c=na(ia(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},aa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...oa(c,o))}return s},G=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=G(e.getLeft()),s=G(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},ca=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&G(t)!==void 0},ua=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(ca(o))continue;const a=G(o);if(a===void 0)continue;const c=Cs(a);if(c===void 0)continue;const l=o.getStartLineNumber(),p=`${String(l)}:${c}`;n.has(p)||(n.add(p),s.push({file:t,kind:c,line:l,preview:ks(a)}))}return s},la=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ua(n,f(t,r)))}return s},da=new Set(["findFirst","findFirstOrThrow","findMany"]),ga=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!da.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},fa=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},pa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=ga(o);if(a===void 0)continue;const c=fa(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),p=!l&&P(c);!l&&!p||n.push({exportName:e.getName(),file:t,fromArgs:p,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},ma=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...pa(c,o))}return s},xa=new Set(["query","unsafe"]),ha=e=>{if(!i.isPropertyAccessExpression(e)||!xa.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"},Ea=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),ya=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",Aa=(e,t)=>{if(!ha(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ea(s)))return{exportName:ya(e),file:t,line:s.getStartLineNumber()}},$a=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Aa(r,t);n&&s.push(n)}return s},Sa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...$a(n,f(t,r)))}return s},Na=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),va=(e,t)=>H(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:Na}),ba=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Pa=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,wa=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=Pa(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Ia=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=ba.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},La=(e,t)=>{const s=Ia(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...wa(e.getArguments()[s.optionsIndex])}},Oa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=La(r,t);n&&s.push(n)}return s},Fa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Oa(n,f(t,r)))}return s},Da=new Set(["when","where"]),xe=new Set(["definePolicy","defineShape"]),Ta=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return xe.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return xe.has(n)?n:void 0}const s=t.getText();return xe.has(s)?s:void 0},Ca=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Lt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Ca(e))return"empty-object";if(i.isParenthesizedExpression(e))return Lt(e.getExpression())}},Ot=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Ft=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>Ot(t)===e),Dt=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>Ot(t)===e),ka=e=>{const t=Ft(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Dt(e).length>0},Ka=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Ft(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Dt(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},Ra=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Ma=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!Da.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&ka(a))for(const c of Ka(a)){const l=Lt(c);l!==void 0&&n.push({exportName:Ra(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},za=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ta(r);n!==void 0&&s.push(...Ma(r,n,t))}return s},ja=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...za(n,f(t,r)))}return s},qa=new Set(["query","upsert","upsertMany"]),Ba=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(qa.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Va=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Ua=(e,t)=>{const s=Ba(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=Va(r);if(!(!n||!P(n)||D(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},Wa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ua(r,t);n&&s.push(n)}return s},Ga=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Wa(n,f(t,r)))}return s},_a=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"},Ha=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Qa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!_a(a))continue;const c=Ms(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:Ha(a)})}}return s},Xa=".lunora-schema.json",$=(e,t)=>{E(e)&&ye(e,"utf8")===t||Bt(e,t,"utf8")},v=(e,t)=>{if(t===""){Vt(e,{force:!0});return}$(e,t)},Ja=e=>{const t=g(e,"package.json");if(E(t))try{const s=JSON.parse(ye(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Za=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Ya=e=>{let t=E(e)?e:de(e);for(;t&&t!==de(t);){const s=g(t,"tsconfig.json");if(E(s))return s;t=de(t)}},ft=e=>e.replaceAll("\\","/"),ec=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new q("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new q("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new q("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},tc=e=>{const t=Ya(e);return t?new Xe({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xe({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Mc=(e,t)=>{const s=d(t),r=g(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>ft(c))),o=ft(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},zc=e=>{const t=Za(),s=t?ge.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),n=g(r,"schema.ts");if(!E(n))throw new q("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??tc(r),a=Ts(o,n,e.projectRoot),c=_t(o,r),l=ms(o,r),p=As(o,r),y=Ks(o,r),O=Ns(o,r),R=ui(o,r),Se=pn(o,r),S=zs(o,r),T=Is(o,r),N=Ht(o,r);ec(S,N);const Q=Jt(o,r,S,N),C=Xt(o,r),Ne=e.lint===!1?[]:Ut({adminRoutes:er(o,r),aiRawRuns:or(o,r),aiToolSideEffects:xr(o,r),argumentDerivedFetches:Ar(o,r),argumentValidators:Fr(o,r),authApiCalls:Qt(o,r),authConfigs:zr(o,r),browserUrlAccesses:Ur(o,r),configCalls:Zr(o,r),containerKeyAccesses:en(o,r),containerOverrides:cn(o,r),containers:C,exportSinks:En(o,r),failOpenGuards:bn(o,r),flagSecurityDefaults:Rn(o,r),geoIndexUsages:jn(o,r),httpActionGuards:Hn(o,r),httpHeaderWrites:ni(o,r),identityClaimReads:xi(o,r),imageDeliveryUrlAccesses:Ai(o,r),inserts:xs(o,r),kvKeyAccesses:Si(o,r),mailRecipientAccesses:Ii(o,r),maskProcedures:hs(o,r),maskStrategies:Es(o,r),mutatorWrites:Ci(o,r),nondeterministicCalls:vs(o,r),normalizeIdAuthorizations:Xi(o,r),notifyCalls:Ps(o,r),notifyConfig:bs(o,r),ownerFieldWrites:no(o,r),unrestrictedWhereBranches:ja(o,r),paymentWebhooks:lo(o,r),privilegedDispatches:vo(o,r),procedureProtections:qo(o,r),queries:ws(o,r),queues:T,r2sqlCalls:Ls(o,r),ratelimitKeySelectors:Ho(o,r),rawRowReturns:ta(o,r),relationLoads:aa(o,r),rlsProcedures:Os(o,r),schema:a,secretLiterals:la(o,r),shapes:y,softDeleteReads:ma(o,r),sqlInterpolations:Sa(o,r),storageKeyAccesses:va(o,r),storageUploads:Fa(o,r),vectorNamespaceAccesses:Ga(o,r),workflowCalls:Qa(o,r),workflows:S,wranglerVariables:e.wranglerVariables}),Tt=Fs(o,r),Ct=ys(o,r),X=Rs(o,r),A=wn(o,r),J=A.ai,Z=A.payments,ve=A.kv,be=A.access,Y=E(g(r,"flags.ts")),kt=Y?ps(o,r):[],ee=E(g(r,"notify.ts")),te=A.hyperdrive,se=Ds(o,r),Kt=se.usesSandboxBrowser||se.usesSandboxContainer,re=A.browser||se.usesSandboxBrowser,ne=A.images,ie=A.analytics,Pe=A.pipelines,oe=A.r2sql,ae=A.x402,w=io(e.projectRoot),M=Fn(A,{containerCount:C.length,cronCount:Q.length,dependencies:w,hasPaymentTables:On(a.tables),queueCount:T.length,storageColumnCount:Object.keys(Zt(a)).length,storageRuleCount:X.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:S.length}),F=w.has("lunorash"),we=t?ge.now():0,Ie=Yt(a,F),Le=es({agents:N,functions:c,httpRoutes:l,useUmbrella:F,workflows:S}),Oe=ts({agents:N,containers:C,env:Se,hasAccessFacade:be,hasAi:J,hasAnalytics:ie,hasBrowser:re,hasFlags:Y,hasHyperdrive:te,hasImages:ne,hasKv:ve,hasNotify:ee,hasPayments:Z,hasPipelines:Pe,hasR2sql:oe,hasX402:ae,identity:R,queues:T,schema:a,storageRuleBuckets:X.rules.map(m=>m.bucket),useUmbrella:F,workflows:S}),Fe=ss({agents:N,functions:c,migrations:p,mutators:O,shapes:y,useUmbrella:F,usesSandbox:Kt}),De=rs({advisories:Ne,agents:N,containers:C,env:Se,flagKeys:kt,hasAccessFacade:be,hasAi:J,hasAnalytics:ie,hasBrowser:re,hasFlags:Y,hasHyperdrive:te,hasImages:ne,hasKv:ve,hasNotify:ee,hasPayments:Z,hasPipelines:Pe,hasR2sql:oe,hasX402:ae,maskMetadata:Ct,mutators:O,queues:T,rlsMetadata:Tt,schema:a,shapes:y,storageRules:X,studioFeatures:M,useUmbrella:F,workflows:S}),Te=ns(y,w.has("@lunora/db"),F),Ce=is(C,a.jurisdiction),ke=os(S),Ke=as(N),Re=cs(T),Me=us(Q),ze=ls(a.vectorIndexes),z=ds(a,F),je=gs(w.has("@lunora/seed")),j=e.apiSpec??"openapi",ce=j==="openapi"||j==="both",ue=j==="openrpc"||j==="both",qe=js({emailAgents:N.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:w.has("@lunora/cloudflare-access"),hasAi:J,hasAnalytics:ie,hasAuth:w.has("@lunora/auth"),hasBrowser:re,hasFramework:w.has("@lunora/astro")||w.has("@lunora/svelte")||w.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:te,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:ne,hasKv:M.kv,hasNotify:ee,hasPayments:Z,hasR2sql:oe,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:M.scheduler,hasStorage:M.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:S.length>0,hasX402:ae,identity:R,jurisdiction:a.jurisdiction,useUmbrella:F,voiceAgents:N.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:ce,wantsOpenRpc:ue}),Be=Ja(e.projectRoot),Ve=qs({functions:c,httpRoutes:l,version:Be}),Ue=Vs({functions:c,version:Be}),We=`${JSON.stringify(Ve,void 0,2)}
2
- `,Ge=`${JSON.stringify(Ue,void 0,2)}
3
- `,_e=Bs(Ve),He=Us(Ue),Qe=Ws(a,p.map(m=>m.id)),le=g(r,Xa),Rt=E(le),x=g(r,"_generated");if(e.dryRun||(E(x)||qt(x,{recursive:!0}),$(g(x,"app.ts"),qe),$(g(x,"dataModel.ts"),Ie),$(g(x,"api.ts"),Le),$(g(x,"server.ts"),Oe),$(g(x,"functions.ts"),Fe),$(g(x,"shard.ts"),De),$(g(x,"crons.ts"),Me),$(g(x,"vectors.ts"),ze),$(g(x,"drizzle.global.ts"),z.global),$(g(x,"drizzle.shard.ts"),z.shard),v(g(x,"containers.ts"),Ce),v(g(x,"workflows.ts"),ke),v(g(x,"agents.ts"),Ke),v(g(x,"queues.ts"),Re),v(g(x,"seed.ts"),je),v(g(x,"collections.ts"),Te),v(g(x,"openapi.json"),ce?We:""),v(g(x,"openapi.ts"),ce?_e:""),v(g(x,"openrpc.json"),ue?Ge:""),v(g(x,"openrpc.ts"),ue?He:""),(!Rt||e.updateSchemaBaseline===!0)&&$(le,Gs(Qe))),t){const m=ge.now(),Mt=Math.round(m-s),zt=Math.round(we-s),jt=Math.round(m-we);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${zt.toString()}ms, emit ${jt.toString()}ms)`)}return{advisories:Ne,agents:N,containers:C,cronTriggers:fs(Q),generated:{agents:Ke,api:Le,app:qe,collections:Te,containers:Ce,crons:Me,dataModel:Ie,drizzleGlobal:z.global,drizzleShard:z.shard,functions:Fe,openApi:We,openApiModule:_e,openRpc:Ge,openRpcModule:He,queues:Re,seed:je,server:Oe,shard:De,vectors:ze,workflows:ke},outputDirectory:x,queues:T,schemaSnapshot:Qe,schemaSnapshotPath:le,workflows:S}};export{Xa as SCHEMA_SNAPSHOT_FILENAME,tc as createCodegenProject,Mc as refreshCodegenProject,zc as runCodegen};
@@ -1 +0,0 @@
1
- import{existsSync as f}from"node:fs";import{join as l}from"node:path";import{SyntaxKind as c,Node as n}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{d as u}from"./parse-validator-CSDlMEvE.mjs";const m="shapes.ts",p=new Set(["@lunora/server","lunorash/server"]),d=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(n.isImportSpecifier(e))return p.has(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},x=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!n.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(c.ImportDeclaration);return i!==void 0&&p.has(i.getModuleSpecifierValue())}return!1},S=r=>{if(n.isIdentifier(r))return d(r);if(n.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&n.isIdentifier(t)&&x(t)}return!1},h=r=>{const[t]=r.getArguments();if(!t||!n.isObjectLiteralExpression(t))return;const e=t.getProperty("table");if(!e||!n.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&n.isStringLiteral(i)?i.getLiteralValue():void 0},E=r=>{const[t]=r.getArguments();if(!t||!n.isObjectLiteralExpression(t))return{};const e=t.getProperty("args");if(!e||!n.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!n.isObjectLiteralExpression(i)?{}:u(i)},I=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==c.CallExpression)continue;const s=i,a=s.getExpression();if(!S(a))continue;const o=e.getNameNode();if(!n.isIdentifier(o))throw g(o,"defineShape exports must be plain named exports (no destructuring)");t.push({args:E(s),exportName:o.getText(),filePath:"shapes",table:h(s)})}return t},L=(r,t)=>{const e=l(t,m);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=I(i);return s.sort((a,o)=>a.exportName.localeCompare(o.exportName)),s};export{m as SHAPES_FILENAME,L as discoverShapes};
@@ -1 +0,0 @@
1
- import{LunoraError as L}from"@lunora/errors";import{isValidCronExpression as A,compileCronSchedule as b,CRON_SCHEDULE_KINDS as O}from"@lunora/scheduler";import{SyntaxKind as p,Node as n}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{listLunoraSourceFiles as S}from"./discoverFunctions-BdibLQmc.mjs";import{n as $}from"./paths-BmX5O1sG.mjs";const I=new Set([...O,"cron"]),j=new Set(["@lunora/scheduler","@lunora/server"]),y=e=>{const t=e.getSymbol();if(!t)return e.getText()==="cronJobs";for(const r of t.getDeclarations())if(n.isImportSpecifier(r))return j.has(r.getImportDeclaration().getModuleSpecifierValue())?r.getNameNode().getText()==="cronJobs":!1;return!1},R=e=>{const t=new Set;for(const r of e.getVariableDeclarations()){const i=r.getInitializer();if(i?.getKind()!==p.CallExpression)continue;const a=i.getExpression();n.isIdentifier(a)&&y(a)&&t.add(r.getName())}return t},P=e=>{let t=e;for(;n.isCallExpression(t)||n.isPropertyAccessExpression(t);)t=t.getExpression();return n.isIdentifier(t)?t.getText():void 0},C=(e,t)=>{const r=e.getArguments()[t];return r&&(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))?r.getLiteralValue():void 0},_=(e,t)=>{if(n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)||n.isNumericLiteral(e))return e.getLiteralValue();if(n.isTrueLiteral(e))return!0;if(n.isFalseLiteral(e))return!1;if(n.isPrefixUnaryExpression(e)&&e.getOperatorToken()===p.MinusToken){const r=e.getOperand();if(n.isNumericLiteral(r))return-r.getLiteralValue()}if(n.isObjectLiteralExpression(e))return g(e,t);if(n.isArrayLiteralExpression(e))return e.getElements().map(r=>_(r,t));throw f(e,`Cron job "${t}" passes a non-static value where a literal is required; codegen can only read literals.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500})},g=(e,t)=>{const r={};for(const i of e.getProperties()){if(!n.isPropertyAssignment(i))throw f(i,`Cron job "${t}" uses an unsupported object property (shorthand/spread/method) where a static literal is required.`,{code:"CRON_NON_STATIC_VALUE",name:"LunoraError",status:500});const a=i.getInitializer();a&&(r[i.getName()]=_(a,t))}return r},x=(e,t,r)=>{const i=e.getArguments()[t];if(!i||!n.isPropertyAccessExpression(i))throw f(e,`Cron job "${r}" must reference a function statically (e.g. internal.email.digest); codegen cannot resolve a dynamic reference.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const a=i.getName(),o=i.getExpression();if(!n.isPropertyAccessExpression(o))throw f(i,`Cron job "${r}" function reference must be of the form internal.file.fn (two property accesses).`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});const s=o.getName();return`${$(s)}:${a}`},h=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),w=e=>({workflow:{binding:e.bindingName,exportName:e.exportName}}),T=(e,t,r,i,a,o)=>{const s=e.getExpression();if(!n.isIdentifier(s)||s.getText()!==t)return;const c=r.get(e.getName());if(c)return o(c);throw f(e,`Cron job "${i}" targets ${t}.${e.getName()}, but no such ${a} is declared in lunora/${a}s.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})},D=(e,t,r,i,a)=>{const o=e.getArguments()[t];if(o&&n.isPropertyAccessExpression(o)){const s=T(o,"workflows",i,r,"workflow",h);return s||T(o,"agents",a,r,"agent",w)||{functionPath:x(e,t,r)}}if(o&&n.isIdentifier(o)){const s=i.get(o.getText()),c=a.get(o.getText());if(s&&c)throw f(o,`Cron job "${r}" references "${o.getText()}", which is ambiguous: a workflow and an agent are both declared under that name.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500});if(s)return h(s);if(c)return w(c);throw f(o,`Cron job "${r}" references "${o.getText()}", which is neither a function (internal.file.fn / api.file.fn) nor a declared workflow in lunora/workflows.ts nor a declared agent in lunora/agents.ts.`,{code:"CRON_NON_STATIC_FN",name:"LunoraError",status:500})}return{functionPath:x(e,t,r)}},k=(e,t,r,i,a)=>{const o=t.getName();if(!I.has(o)||!r.has(P(t.getExpression())??""))return;const s=C(e,0);if(s===void 0||s.trim()==="")throw f(e,`A cron ".${o}(...)" registration must pass a non-empty string-literal name as its first argument.`,{code:"CRON_NAME_NOT_STATIC",name:"LunoraError",status:500});let c;if(o==="cron"){const l=C(e,1);if(l===void 0)throw f(e,`Cron job "${s}" must pass a string-literal cron expression to ".cron(...)".`,{code:"CRON_EXPR_NOT_STATIC",name:"LunoraError",status:500});if(!A(l))throw f(e,`Cron job "${s}" has an invalid cron expression "${l}" — expected 5 or 6 space-separated fields.`,{code:"CRON_EXPR_INVALID",name:"LunoraError",status:500});c=l}else{const l=e.getArguments()[1];if(!l||!n.isObjectLiteralExpression(l))throw f(e,`Cron job "${s}" must pass an object-literal schedule to ".${o}(...)".`,{code:"CRON_SCHEDULE_NOT_STATIC",name:"LunoraError",status:500});c=b(o,g(l,s))}const u=D(e,2,s,i,a),m=e.getArguments()[3];return{args:m&&n.isObjectLiteralExpression(m)?g(m,s):{},cron:c,name:s,...u}},F=e=>{const t=new Set;for(const r of e){if(t.has(r.name))throw new L("DUPLICATE_CRON_NAME",`Duplicate cron job name "${r.name}": cron names must be unique across the project.`,{status:500});t.add(r.name)}},z=(e,t,r=[],i=[])=>{const a=S(t),o=[],s=new Map(r.map(u=>[u.exportName,u])),c=new Map(i.map(u=>[u.exportName,u]));for(const u of a){const m=e.getSourceFile(u)??e.addSourceFileAtPath(u),l=R(m);if(l.size!==0)for(const d of m.getDescendantsOfKind(p.CallExpression)){const N=d.getExpression();if(!n.isPropertyAccessExpression(N))continue;const E=k(d,N,l,s,c);E&&o.push(E)}}return o.sort((u,m)=>u.name.localeCompare(m.name)),F(o),o};export{z as default};
@@ -1 +0,0 @@
1
- import{readdirSync as k,lstatSync as $}from"node:fs";import{join as w,extname as D,relative as F,sep as C}from"node:path";import{Node as s,SyntaxKind as j}from"ts-morph";import{d as b}from"./parse-validator-CSDlMEvE.mjs";import{n as O}from"./paths-BmX5O1sG.mjs";const d=new Set(["action","mutation","query","stream"]),U=/\bany\b(?!\s*(?:\?\s*)?:)/u,z=/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/gu,L=/^[A-Za-z_$][\w$]*$/u,V=e=>L.test(e)?e:JSON.stringify(e),_=/\.ts$/u,M=(e,t)=>F(e,t).split(C).join("/").replace(_,""),v={internalAction:"action",internalMutation:"mutation",internalQuery:"query"},H={onConnect:"connect",onDisconnect:"disconnect"},R=/(?:^|\/)_generated\/server(?:\.js)?$/u,B=e=>e==="@lunora/server"||R.test(e),A=e=>{const t=e.getSymbol();if(!t)return e.getText();const i=t.getDeclarations();for(const r of i){if(!s.isImportSpecifier(r))continue;const n=r.getImportDeclaration().getModuleSpecifierValue();return B(n)?r.getNameNode().getText():void 0}},h=(e,t=!1)=>{let i=e;for(;s.isCallExpression(i);){const n=i.getExpression();if(!s.isPropertyAccessExpression(n))return;i=n.getExpression()}if(!s.isIdentifier(i))return;const r=A(i);if(r===void 0){if(t)return;const n=i.getSymbol()?.getValueDeclaration();if(n&&s.isVariableDeclaration(n)){const o=n.getInitializer();return o?h(o,!0):void 0}return}return d.has(r)?"public":v[r]?"internal":void 0},q=e=>{let t=e;for(;s.isCallExpression(t);){const i=t.getExpression();if(!s.isPropertyAccessExpression(i))return;if(i.getName()==="expose"){const r=t.getArguments()[0];if(r!==void 0&&s.isObjectLiteralExpression(r)){const n=r.getProperty("rest");if(n!==void 0&&s.isPropertyAssignment(n))return{rest:n.getInitializer()?.getText()==="true"}}return{}}t=i.getExpression()}},J=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return{};const i=t.getProperty("args");if(!i||!s.isPropertyAssignment(i))return{};const r=i.getInitializer();return!r||!s.isObjectLiteralExpression(r)?{}:b(r)},K=(e,t)=>{for(const i of[e.getSymbol(),e.getAliasSymbol()])if(i)for(const r of i.getDeclarations()){const n=r.getSourceFile();if(!(n.isInNodeModules()||n.isDeclarationFile())&&n.getFilePath()===t&&(s.isInterfaceDeclaration(r)||s.isTypeAliasDeclaration(r))&&!r.isExported())return!0}return!1},Q=e=>{const t=[...e.getTypeArguments()];return e.isUnion()&&t.push(...e.getUnionTypes()),e.isIntersection()&&t.push(...e.getIntersectionTypes()),t},P=e=>!e.isObject()||e.isArray()||e.isTuple()||e.getCallSignatures().length>0||e.getConstructSignatures().length>0?!1:e.getStringIndexType()===void 0&&e.getNumberIndexType()===void 0,p=(e,t,i,r=new Set)=>r.has(e)?!1:(r.add(e),K(e,i)||Q(e).some(n=>p(n,t,i,r))?!0:P(e)?e.getProperties().some(n=>p(n.getTypeAtLocation(t),t,i,r)):!1),G=(e,t)=>{const i=e.getValueDeclaration()??e.getDeclarations()[0];return i&&(s.isPropertySignature(i)||s.isPropertyDeclaration(i))&&i.hasQuestionToken()?!0:t.isUnion()&&t.getUnionTypes().some(r=>r.isUndefined())},W=8,Z=(e,t,i,r,n,o)=>{const a=e.getArrayElementType(),c=a?o(a,t,i,r,n):void 0;if(c!==void 0)return a?.isUnion()?`(${c})[]`:`${c}[]`},X=(e,t,i,r,n,o)=>{const a=[];for(const c of e.getUnionTypes()){const l=o(c,t,i,r,n);if(l===void 0)return;a.push(l)}return a.join(" | ")},Y=(e,t,i,r,n,o)=>{if(!P(e))return;const a=[];for(const c of e.getProperties()){const l=c.getTypeAtLocation(t),y=G(c,l),I=y&&l.isUnion()?l.getUnionTypes().filter(f=>!f.isUndefined()):[l],m=[];for(const f of I){const x=o(f,t,i,r+1,n);if(x===void 0)return;m.push(x)}a.push(`${V(c.getName())}${y?"?":""}: ${m.join(" | ")}`)}return a.length>0?`{ ${a.join("; ")} }`:"{}"},g=(e,t,i,r,n)=>{if(r>W||n.has(e))return;if(!p(e,t,i))return e.getText(t);const o=new Set(n).add(e);return e.isArray()?Z(e,t,i,r,o,g):e.isUnion()?X(e,t,i,r,o,g):Y(e,t,i,r,o,g)},S=e=>{const t=e.getType().getCallSignatures()[0];if(!t)return"unknown";let i=t.getReturnType();const r=(i.getSymbol()??i.getAliasSymbol())?.getName();if(r==="Promise"||r==="AsyncIterable"||r==="AsyncIterableIterator"||r==="AsyncGenerator"){const a=i.getTypeArguments()[0];a&&(i=a)}const n=i.getText(e);if(!n||n==="any"||n==="never"||U.test(n.replaceAll(z,"")))return"unknown";const o=e.getSourceFile().getFilePath();return p(i,e,o)?g(i,e,o,0,new Set)??"unknown":n},ee=e=>{const t=e.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return"unknown";const i=t.getProperty("handler");if(!i||!s.isPropertyAssignment(i))return"unknown";const r=i.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":S(r)},te=e=>{const t=e.getArguments()[0];return!t||!(s.isArrowFunction(t)||s.isFunctionExpression(t))?"unknown":S(t)},ie=e=>{let t={},i=e;for(;s.isCallExpression(i);){const r=i.getExpression();if(!s.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const n=i.getArguments()[0];n&&s.isObjectLiteralExpression(n)&&(t={...b(n),...t})}i=r.getExpression()}return t},re=e=>{const t=e.getExpression();if(s.isPropertyAccessExpression(t)){const o=t.getName();if(!d.has(o))return;const a=t.getExpression();if(a.getType().getProperty("__lunoraProcedure"))return{kind:o,receiver:a,visibility:a.getType().getProperty("__lunoraVisibility")?"internal":"public"};const c=h(a);return c?{kind:o,receiver:a,visibility:c}:void 0}if(!s.isIdentifier(t))return;const i=A(t);if(!i)return;if(d.has(i))return{kind:i,visibility:"public"};const r=v[i];if(r)return{kind:r,visibility:"internal"};const n=H[i];if(n)return{kind:"mutation",lifecycle:n,visibility:"internal"}},E=e=>e!==void 0&&(s.isArrowFunction(e)||s.isFunctionExpression(e))?e:void 0,me=e=>s.isPropertyAccessExpression(e)&&e.getName()==="db"||s.isIdentifier(e)&&e.getText()==="db",xe=e=>{const t=e.getArguments()[0],i=E(t);if(i!==void 0)return i;if(t===void 0||!s.isObjectLiteralExpression(t))return;const r=t.getProperty("handler");return r!==void 0&&s.isPropertyAssignment(r)?E(r.getInitializer()):void 0},ne=e=>s.isIdentifier(e)?e.getText():s.isPropertyAccessExpression(e)?e.getName():"",Ee=(e,t)=>{let i=e;for(;s.isCallExpression(i);){const r=i.getExpression();if(!s.isPropertyAccessExpression(r))break;if(r.getName()===t)return!0;i=r.getExpression()}return!1},be=(e,t,i)=>{let r=e;for(;s.isCallExpression(r);){const n=r.getExpression();if(!s.isPropertyAccessExpression(n))break;const o=r.getArguments()[0];if(n.getName()===t&&o!==void 0&&s.isCallExpression(o)&&ne(o.getExpression())===i)return!0;r=n.getExpression()}return!1},N=(e,t=[],i=e)=>{let r;try{r=k(e)}catch{return t}for(const n of r){const o=w(e,n),a=$(o);if(a.isDirectory()){if(n==="_generated"||n==="node_modules")continue;N(o,t,i)}else if(a.isFile()&&D(n)===".ts"){if(n==="schema.ts"&&e===i)continue;t.push(o)}}return t},se=e=>{const t=re(e);if(t){if(t.receiver){const i=q(t.receiver);return{args:ie(t.receiver),...i?{expose:i}:{},kind:t.kind,returnType:te(e),visibility:t.visibility}}return t.lifecycle?{args:{},kind:t.kind,lifecycle:t.lifecycle,returnType:"void",visibility:t.visibility}:{args:J(e),kind:t.kind,returnType:ee(e),visibility:t.visibility}}},oe=8,u=(e,t=0)=>{if(t>oe)return;if(s.isCallExpression(e))return e;if(s.isParenthesizedExpression(e)||s.isAsExpression(e)||s.isSatisfiesExpression(e)||s.isNonNullExpression(e))return u(e.getExpression(),t+1);if(!s.isIdentifier(e)&&!s.isPropertyAccessExpression(e))return;const i=e.getSymbol()?.getValueDeclaration();return i?T(i,t+1):void 0},T=(e,t)=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e)){const i=e.getInitializer();return i?u(i,t):void 0}if(s.isShorthandPropertyAssignment(e))return u(e.getNameNode(),t);if(s.isBindingElement(e)){const i=e.getPropertyNameNode()?.getText()??e.getName(),r=e.getFirstAncestorByKind(j.VariableDeclaration)?.getInitializer()?.getType().getProperty(i)?.getValueDeclaration();return r?T(r,t+1):void 0}},ae=e=>{const t=e.getNameNode();if(s.isObjectBindingPattern(t)){const n=[];for(const o of t.getElements()){const a=u(o.getNameNode());a&&n.push([o.getName(),a])}return n}const i=e.getInitializer(),r=i&&(s.isCallExpression(i)?i:u(i));return r?[[e.getName(),r]]:[]},ce=(e,t,i)=>{const r=se(e);if(r)return{args:r.args,exportName:t,filePath:i,kind:r.kind,returnType:r.returnType,visibility:r.visibility,...r.expose?{expose:r.expose}:{},...r.lifecycle?{lifecycle:r.lifecycle}:{}}},le=(e,t)=>{const i=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations())for(const[o,a]of ae(n)){const c=ce(a,o,t);c&&i.push(c)}return i},ue=e=>{const t=new Map;for(const i of e){const r=O(i.filePath),n=t.get(r);if(n&&n!==i.filePath)throw Object.assign(new Error(`Namespace collision: "${n}" and "${i.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,i.filePath],status:500});t.set(r,i.filePath)}},ve=(e,t)=>{const i=N(t),r=[];for(const n of i){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),a=M(t,n);r.push(...le(o,a))}return r.sort((n,o)=>`${n.filePath}:${n.exportName}`.localeCompare(`${o.filePath}:${o.exportName}`)),ue(r),r};export{Ee as chainHasStep,be as chainUsesWrappedCall,re as classifyProcedureCall,ve as discoverFunctions,E as inlineHandler,me as isDatabaseAccessor,N as listLunoraSourceFiles,M as lunoraRelativePath,xe as procedureHandler,S as unwrapHandlerReturn};
@@ -1 +0,0 @@
1
- import{relative as g,sep as u}from"node:path";import{SyntaxKind as p,Node as a}from"ts-morph";import{diagnosticAt as m}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{listLunoraSourceFiles as h}from"./discoverFunctions-BdibLQmc.mjs";const I=/\.ts$/u,x=r=>{const i=r.getSymbol();if(!i)return r.getText()==="defineMigration";for(const e of i.getDeclarations())if(a.isImportSpecifier(e))return e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/server"?!1:e.getNameNode().getText()==="defineMigration";return!1},d=(r,i)=>{const e=r.getProperty(i);if(!e||!a.isPropertyAssignment(e))return;const t=e.getInitializer();return t&&a.isStringLiteral(t)?t.getLiteralValue():void 0},E=(r,i)=>{const e=r.getInitializer();if(e?.getKind()!==p.CallExpression)return;const t=e.getExpression();if(!a.isIdentifier(t)||!x(t))return;const o=e.getArguments()[0];if(!o||!a.isObjectLiteralExpression(o))return;const n=d(o,"id"),s=r.getName();if(n===void 0||n.trim()==="")throw m(o,`Migration "${s}" in "${i}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});return{exportName:s,filePath:i,id:n,table:d(o,"table")??""}},S=r=>{const i=new Map;for(const e of r){const t=i.get(e.id);if(t!==void 0)throw Object.assign(new Error(`Duplicate migration id "${e.id}": declared in both "${t}" and "${e.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:e.id,name:"LunoraError",paths:[t,e.filePath],status:500});i.set(e.id,e.filePath)}},P=(r,i)=>{const e=h(i),t=[];for(const o of e){const n=r.getSourceFile(o)??r.addSourceFileAtPath(o),s=g(i,o).split(u).join("/").replace(I,"");for(const c of n.getVariableStatements())if(c.isExported())for(const f of c.getDeclarations()){const l=E(f,s);l&&t.push(l)}}return t.sort((o,n)=>o.id.localeCompare(n.id)),S(t),t};export{P as default};