@lunora/codegen 1.0.0-alpha.164 → 1.0.0-alpha.165
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +11 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-zxE5ds4T.mjs → GENERATED_HEADER-CR0AOQsV.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-BgLkvCYK.mjs → OPENRPC_VERSION-DlF2XS7T.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-CSgeeyQD.mjs +9 -0
- package/dist/packem_shared/{buildOpenApiDocument-qYjkmRTX.mjs → buildOpenApiDocument-CE9SDrBg.mjs} +1 -1
- package/dist/packem_shared/{emit-BNdsZPcd.mjs → emit-Lx7UkoGn.mjs} +195 -186
- package/dist/packem_shared/{emitApp-CxmA4W3C.mjs → emitApp-9dMkNu6n.mjs} +47 -27
- package/package.json +9 -9
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-C9nFNiHX.mjs +0 -9
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as
|
|
1
|
+
import{A as w,G as k}from"./emit-Lx7UkoGn.mjs";const y=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[y(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,h)=>c.localeCompare(h)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:h,wantsOpenRpc:d}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...h?['import { openApiSpec } from "./openapi.js";']:[],...d?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},L=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],N=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: NonNullable<ShardConfig["${a}"]>): this {
|
|
3
3
|
this.shardExtras.${a} = factory;
|
|
4
4
|
|
|
@@ -17,7 +17,12 @@ import{A as f,G as w}from"./emit-BNdsZPcd.mjs";const y=e=>`has${e.charAt(0).toUp
|
|
|
17
17
|
this.reactiveCacheConfig = config;
|
|
18
18
|
|
|
19
19
|
return this;
|
|
20
|
-
}
|
|
20
|
+
}`,` /** Ceiling on the join keys ONE relation-crossing \`where\` predicate may pre-resolve via semijoin before failing closed. Omit for the engine default. */
|
|
21
|
+
public maxRelationKeys(limit: NonNullable<ShardConfig["maxRelationKeys"]>): this {
|
|
22
|
+
this.maxRelationKeysLimit = limit;
|
|
23
|
+
|
|
24
|
+
return this;
|
|
25
|
+
}`," /**\n * Route the shard's `ctx.log` lines, `ctx.trace` spans and `ctx.metrics` measurements to a telemetry sink.\n *\n * The DO half of observability: without it every in-handler signal stays in the shard's local ring buffer (the studio Logs panel) and reaches no collector. The worker half — one `onRpc` event per dispatched RPC — is a `createWorker` option; pass the SAME sink to both via `.extend((env) => ({ observability: sink(env) }))` to correlate them.\n */\n public observability(selector: NonNullable<ShardConfig[\"observability\"]>): this {\n this.observabilitySink = selector;\n\n return this;\n }",' /** Resolution policy for a relation-crossing `where` whose child is co-located in this shard: `"auto"` (cost-based, the engine default), `"always"` (inline correlated EXISTS) or `"never"` (universal semijoin). All three return identical rows. */\n public relationExistsPushDown(mode: NonNullable<ShardConfig["relationExistsPushDown"]>): this {\n this.relationExistsPushDownMode = mode;\n\n return this;\n }',...e.hasAuth?[' /** Wire better-auth — the builder lazily builds the instance, runs `ensureMigrated`, and dispatches `/api/auth/*` inside the worker (instrumented for the auth-failure SLO). Pass `d1` for the D1-backed default, or `namespace` + `internalSecret` to host the auth tables in a Durable Object (what `@better-auth/scim` needs). */\n public auth(declaration: AuthDeclaration<Env>): this {\n // Reject the ambiguous and the empty shapes here rather than at the first\n // request: with neither storage set, auth would silently never answer, and\n // with both it is unclear which one owns the tables.\n if (declaration.d1 && declaration.namespace) {\n throw new Error(".auth(): pass either `d1` or `namespace`, not both — they are two different homes for the same tables.");\n }\n\n if (!declaration.d1 && !declaration.namespace) {\n throw new Error(".auth(): needs `d1` (D1-backed) or `namespace` (Durable-Object-backed) to know where the auth tables live.");\n }\n\n if (declaration.namespace && !declaration.internalSecret) {\n throw new Error(\n ".auth(): `namespace` requires `internalSecret` — the auth DO binding is reachable from any worker bound to it, so identity resolution is gated on a shared secret and would otherwise fail closed on every request.",\n );\n }\n\n this.authDeclaration = declaration;\n\n return this;\n }']:[]," /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */\n public extend(fn: (env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>): this {\n this.extendFns.push(fn);\n\n return this;\n }",...e.hasGlobal?[` /** Back \`.global()\` (cross-tenant) tables with D1 — wires \`ctx.db\` routing, the studio global browser, and reverse cross-shard relations. */
|
|
21
26
|
public global(declaration: GlobalDeclaration<Env>): this {
|
|
22
27
|
this.globalDeclaration = declaration;
|
|
23
28
|
|
|
@@ -52,8 +57,8 @@ import{A as f,G as w}from"./emit-BNdsZPcd.mjs";const y=e=>`has${e.charAt(0).toUp
|
|
|
52
57
|
this.storageDeclaration = declaration;
|
|
53
58
|
|
|
54
59
|
return this;
|
|
55
|
-
}`]:[],...
|
|
56
|
-
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
60
|
+
}`]:[],...q(e)],G=e=>{const t=r=>e.hasScheduler?`
|
|
61
|
+
...(this.schedulerDeclaration ? { scheduler: this.resolveScheduler(env) as unknown as ${r}["scheduler"] } : {}),`:"",a=[" cdc: this.cdcEnabled,"," reactiveCache: this.reactiveCacheConfig,"," ...(this.maxRelationKeysLimit === undefined ? {} : { maxRelationKeys: this.maxRelationKeysLimit }),"," ...(this.observabilitySink === undefined ? {} : { observability: this.observabilitySink }),"," ...(this.relationExistsPushDownMode === undefined ? {} : { relationExistsPushDown: this.relationExistsPushDownMode }),",...e.hasGlobal?[` ...(this.globalDeclaration
|
|
57
62
|
? {
|
|
58
63
|
d1: (rawEnv: Record<string, unknown>, request?: { bookmark?: string; cdc?: boolean; cdcRetentionMs?: number; identity?: Record<string, unknown>; onBookmark?: (bookmark: string | undefined) => void; userId?: string | null }) => {
|
|
59
64
|
const env = rawEnv as Env;
|
|
@@ -124,10 +129,10 @@ import{A as f,G as w}from"./emit-BNdsZPcd.mjs";const y=e=>`has${e.charAt(0).toUp
|
|
|
124
129
|
? {
|
|
125
130
|
scheduler: (rawEnv: Record<string, unknown>) => this.resolveScheduler(rawEnv as Env),
|
|
126
131
|
}
|
|
127
|
-
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...
|
|
132
|
+
: {}),`]:[],...e.hasStorage?[" ...(this.storageDeclaration ? { storage: (rawEnv: Record<string, unknown>) => this.resolveStorage(rawEnv as Env) } : {}),"]:[],...m(e)?[" ...this.shardExtras,"]:[]];return a.length>0?`
|
|
128
133
|
${a.join(`
|
|
129
134
|
`)}
|
|
130
|
-
`:""},
|
|
135
|
+
`:""},W=e=>[...e.tableNames.length>0?[` options.listSchemaTables = () => [${e.tableNames.map(t=>JSON.stringify(t)).join(", ")}];`]:[],...e.hasScheduler?[` if (this.schedulerDeclaration) {
|
|
131
136
|
options.schedulerDO = this.schedulerDeclaration.namespace(env);
|
|
132
137
|
}`]:[],...e.hasWorkflow?[` options.workflowsClient = (workflowEnv) => {
|
|
133
138
|
const source = workflowEnv as Record<string, unknown>;
|
|
@@ -269,7 +274,7 @@ ${a.join(`
|
|
|
269
274
|
}`]:[],...e.voiceAgents&&e.voiceAgents.length>0?[` options.voiceAgents = {
|
|
270
275
|
${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Record<string, unknown>)[${JSON.stringify(t.bindingName)}] as ShardNamespaceLike,`).join(`
|
|
271
276
|
`)}
|
|
272
|
-
};`]:[]],
|
|
277
|
+
};`]:[]],B=e=>[" cronJobs: LUNORA_CRONS,"," functions: LUNORA_FUNCTIONS,",...e.identity?[` identity: lunoraIdentityContract.${e.identity.exportName},`]:[],...e.jurisdiction?[` jurisdiction: ${JSON.stringify(e.jurisdiction)},`]:[],...e.wantsOpenApi?[" openApiSpec,"]:[],...e.wantsOpenRpc?[" openRpcSpec,"]:[],...e.hasQueue?[" queue: (batch: unknown, queueEnv: unknown, _context: ExecutionContextLike, trigger: TriggerTrace): Promise<void> =>"," dispatchQueueBatch(batch as Parameters<typeof dispatchQueueBatch>[0], LUNORA_QUEUE_REGISTRY, {"," capture: shouldCaptureQueue(queueEnv as Record<string, unknown>)",` ? createQueueCaptureSink(queueEnv as Record<string, unknown>${e.jurisdiction?`, { jurisdiction: ${JSON.stringify(e.jurisdiction)} }`:""})`," : undefined,"," env: queueEnv as Record<string, unknown>,"," traceparent: trigger.traceparent,"," }),"]:[]," ...(this.httpRouterApp ? { httpRouter: this.httpRouterApp } : {}),"," routes: this.routeMap,"," shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike),"],P=e=>e.hasScheduler?`
|
|
273
278
|
/** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
|
|
274
279
|
private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
|
|
275
280
|
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
@@ -386,8 +391,8 @@ ${e.voiceAgents.map(t=>` ${JSON.stringify(t.exportName)}: (env as Rec
|
|
|
386
391
|
* Opens a D1 Sessions API session pinned to \`bookmark\` (the caller's own
|
|
387
392
|
* last-known write, when supplied) so reads observe it — read-your-writes
|
|
388
393
|
* across replicas. \`onBookmark\`, when supplied, is invoked with the bookmark
|
|
389
|
-
* produced by each write so the caller (the generated DO) can record it
|
|
390
|
-
*
|
|
394
|
+
* produced by each write so the caller (the generated DO) can record it on the
|
|
395
|
+
* dispatch's bookmark sink and echo \`x-d1-bookmark\` on the response.
|
|
391
396
|
*
|
|
392
397
|
* Wrapped in \`retryingExec\` so D1's documented baseline of transient failures
|
|
393
398
|
* (storage-object resets, isolate memory evictions, dropped connections) does
|
|
@@ -422,8 +427,8 @@ const buildExec = (database: D1DatabaseLike, bookmark?: string, onBookmark?: (bo
|
|
|
422
427
|
// read could pin a replica that has not seen them: read-your-writes
|
|
423
428
|
// lost on the exact path the bookmark exists for. Reporting it after
|
|
424
429
|
// a plain \`SELECT\` too is harmless and correct — the session's
|
|
425
|
-
// bookmark only ever moves forward, and
|
|
426
|
-
//
|
|
430
|
+
// bookmark only ever moves forward, and the sink takes the last
|
|
431
|
+
// value.
|
|
427
432
|
onBookmark?.(session?.getBookmark() ?? undefined);
|
|
428
433
|
|
|
429
434
|
return result.results;
|
|
@@ -583,7 +588,7 @@ const buildGlobalCdcApplier =
|
|
|
583
588
|
|
|
584
589
|
return request.changes.length;
|
|
585
590
|
};
|
|
586
|
-
`:"",H=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),F=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=L(t),n=
|
|
591
|
+
`:"",H=e=>[...e.hasAuth?["AuthDeclaration"]:[],"ComposedApp",...e.hasGlobal?["GlobalDeclaration"]:[],...e.hasScheduler?["SchedulerDeclaration"]:[],"Selector",...e.hasStorage?["StorageDeclaration"]:[]].toSorted((t,a)=>t.localeCompare(a)).join(", "),F=e=>{const t={...e,hasVectors:(e.hasVectors??!0)&&(e.vectorIndexCount??0)>0},{hasAuth:a}=t,r=L(t),n=W(t),i=a?` let auth: LunoraAuth | null = null;
|
|
587
592
|
let authInit: Promise<void> | null = null;
|
|
588
593
|
`:"",o=a?`
|
|
589
594
|
const initAuth = async (env: Env): Promise<void> => {
|
|
@@ -624,22 +629,25 @@ const buildGlobalCdcApplier =
|
|
|
624
629
|
authInit = null;
|
|
625
630
|
throw error;
|
|
626
631
|
}));
|
|
627
|
-
`:"",
|
|
628
|
-
await ensureAuth(env);`:"",s=a?"() => auth":"() => null",
|
|
629
|
-
host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,
|
|
630
|
-
${
|
|
632
|
+
`:"",l=a?`
|
|
633
|
+
await ensureAuth(env);`:"",s=a?"() => auth":"() => null",c=a?"getAuth: () => LunoraAuth | null":"_getAuth: () => null",h=t.hasFramework?` const buildWorker = (env: Env): LunoraWorker =>
|
|
634
|
+
host ? withFrameworkWorker(host, (hostEnv) => this.buildWorkerOptions(hostEnv as Env, ${s})) : createWorker(this.buildWorkerOptions(env, ${s}));`:` const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, ${s}));`,d=t.hasFramework?"host?: FrameworkHostHandler":"",u=t.emailAgents??[],v=u.length>0?` composed.email = dispatchAgentEmail([
|
|
635
|
+
${u.map(p=>` { agent: lunoraAgentDefinitions.${p.exportName}, binding: ${JSON.stringify(p.bindingName)} },`).join(`
|
|
631
636
|
`)}
|
|
632
637
|
]);
|
|
633
638
|
|
|
634
|
-
`:"",
|
|
639
|
+
`:"",f=` /** Materialise the standalone Cloudflare worker + \`ShardDO\` class. */
|
|
635
640
|
public build(): ComposedApp {
|
|
636
641
|
return this.assemble();
|
|
637
|
-
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${
|
|
642
|
+
}${t.hasFramework?"\n\n /** Compose Lunora's realtime plane INTO a meta-framework's Cloudflare handler (SvelteKit/Astro/Nuxt). The framework `host` serves everything except the reserved `/_lunora/*` endpoints; pass the adapter-emitted worker (e.g. SvelteKit's `_worker.js`, Astro's `handle`). */\n public buildFrameworkWorker(host: FrameworkHostHandler): ComposedApp {\n return this.assemble(host);\n }":""}`;return`${k}${I(t).join(`
|
|
638
643
|
`)}
|
|
639
644
|
|
|
640
645
|
/** Read a value off the per-request \`env\`. Returns \`undefined\` to leave the capability unconfigured (its \`ctx.*\`/admin surface stays a clear-error stub). */
|
|
641
646
|
type Selector<Env, T> = (env: Env) => T | undefined;
|
|
642
|
-
|
|
647
|
+
|
|
648
|
+
/** The generated \`createShardDO\` config — \`.observability()\`, \`.maxRelationKeys()\` and the long-tail \`.ai()\` / \`.kv()\` / … methods pass straight through to it. */
|
|
649
|
+
type ShardConfig = NonNullable<Parameters<typeof createShardDO>[0]>;
|
|
650
|
+
|
|
643
651
|
${r.join(`
|
|
644
652
|
|
|
645
653
|
`)}${r.length>0?`
|
|
@@ -659,7 +667,7 @@ interface ComposedApp extends LunoraWorker {
|
|
|
659
667
|
* first request so per-isolate singletons are built once.
|
|
660
668
|
*/
|
|
661
669
|
class AppBuilder<Env extends object> {
|
|
662
|
-
${
|
|
670
|
+
${N(t).join(`
|
|
663
671
|
`)}
|
|
664
672
|
|
|
665
673
|
private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise<void>;
|
|
@@ -668,10 +676,10 @@ ${j(t).join(`
|
|
|
668
676
|
|
|
669
677
|
`)}
|
|
670
678
|
|
|
671
|
-
${
|
|
679
|
+
${f}
|
|
672
680
|
|
|
673
681
|
/** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */
|
|
674
|
-
private assemble(${
|
|
682
|
+
private assemble(${d}): ComposedApp {
|
|
675
683
|
const ShardDO = createShardDO({${G(t)}});
|
|
676
684
|
|
|
677
685
|
// Per-isolate singletons: the worker (and auth instance) are expensive to
|
|
@@ -679,12 +687,12 @@ ${k}
|
|
|
679
687
|
// the same isolate reuses them.
|
|
680
688
|
let worker: LunoraWorker | null = null;
|
|
681
689
|
${i}${o}
|
|
682
|
-
${
|
|
690
|
+
${h}
|
|
683
691
|
|
|
684
692
|
const composed: ComposedApp = {
|
|
685
693
|
ShardDO,
|
|
686
694
|
fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise<Response> => {
|
|
687
|
-
const env = rawEnv as Env;${
|
|
695
|
+
const env = rawEnv as Env;${l}
|
|
688
696
|
worker ??= buildWorker(env);
|
|
689
697
|
|
|
690
698
|
return worker.fetch(request, rawEnv, context);
|
|
@@ -698,7 +706,7 @@ ${d}
|
|
|
698
706
|
worker ??= buildWorker(rawEnv as Env);
|
|
699
707
|
|
|
700
708
|
return worker.serverQuery(request, rawEnv, reference, args, options);
|
|
701
|
-
},${t.hasQueue?`
|
|
709
|
+
},${t.hasQueue||t.hasFramework?`
|
|
702
710
|
queue: async (batch: unknown, rawEnv: unknown, context: ExecutionContextLike): Promise<void> => {
|
|
703
711
|
worker ??= buildWorker(rawEnv as Env);
|
|
704
712
|
|
|
@@ -711,14 +719,26 @@ ${v} if (this.emailHandler) {
|
|
|
711
719
|
|
|
712
720
|
composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context);
|
|
713
721
|
}
|
|
722
|
+
${t.hasFramework?`
|
|
723
|
+
// A framework host may export its own \`email\` (Nitro's \`cloudflare-module\`
|
|
724
|
+
// does). Nothing in Lunora serves one, so when the app registered no handler
|
|
725
|
+
// of its own the host's is the only one there is — forward to it rather than
|
|
726
|
+
// dropping the entry.
|
|
727
|
+
if (!composed.email && host && typeof host === "object" && typeof host.email === "function") {
|
|
728
|
+
composed.email = (message, rawEnv, context) => {
|
|
729
|
+
worker ??= buildWorker(rawEnv as Env);
|
|
714
730
|
|
|
731
|
+
return worker.email?.(message, rawEnv, context) ?? Promise.resolve();
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
`:""}
|
|
715
735
|
return composed;
|
|
716
736
|
}
|
|
717
737
|
${P(t)}${_(t.hasStorage)}
|
|
718
738
|
/** Fan the recorded declarations into the worker-side \`createWorker\` options. */
|
|
719
|
-
private buildWorkerOptions(env: Env, ${
|
|
739
|
+
private buildWorkerOptions(env: Env, ${c}): WorkerOptions {
|
|
720
740
|
const options: WorkerOptions = {
|
|
721
|
-
${
|
|
741
|
+
${B(t).join(`
|
|
722
742
|
`)}
|
|
723
743
|
};
|
|
724
744
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.165",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
51
|
-
"@lunora/container": "1.0.0-alpha.
|
|
52
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.115",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.95",
|
|
51
|
+
"@lunora/container": "1.0.0-alpha.48",
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.35",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.27",
|
|
54
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
55
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
56
|
-
"@lunora/values": "1.0.0-alpha.
|
|
57
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.51",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.58",
|
|
56
|
+
"@lunora/values": "1.0.0-alpha.43",
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.49",
|
|
58
58
|
"jsonc-parser": "^3.3.1",
|
|
59
59
|
"quicktype-core": "^26.0.0",
|
|
60
60
|
"ts-morph": "^28.0.0"
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{existsSync as b,mkdirSync as gs,readFileSync as Ct,writeFileSync as ps,rmSync as ms}from"node:fs";import{join as f,dirname as J}from"node:path";import{performance as he}from"node:perf_hooks";import{runAdvisor as hs}from"@lunora/advisor";import{LunoraError as D}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as st}from"ts-morph";import{serializeSchemaSnapshot as xs}from"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{toAdvisorContext as Es}from"./formatAdvisories-CkEu1eye.mjs";import{s as vs}from"./paths-C-9fwEgQ.mjs";import{discoverAgents as Ss}from"./AGENTS_FILENAME-DHk9gO3E.mjs";import{discoverContainers as ys}from"./CONTAINERS_FILENAME-CqSjcb1-.mjs";import As from"./discoverCrons-C-GrcmEj.mjs";import{diagnosticAt as ie}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ae}from"./module-specifiers-WF8iAydP.mjs";import{C as xe,n as Ft,i as Ns,f as bs,j as Ps,b as Is,c as ws,l as Ts,e as Cs,o as Fs,d as Os,k as Rs,g as Ls,p as Ds,m as ks,a as Ms,h as Ks}from"./emit-BNdsZPcd.mjs";import{listLunoraSourceFiles as m,unwrapExpression as W,listSecurityScanFiles as Ie,objectLiteralFromCallbackBody as Ot,propertyInitializer as A,lunoraRelativePath as v,collectCallRows as I,collectSecurityCallRows as _s,limitNameOf as Rt,isContextIdentifier as ye,handlerOf as zs,isDatabaseAccessor as k,readTargetOf as Lt,enclosingExportName as Us}from"./listLunoraSourceFiles-lHrzFhbX.mjs";import Bs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as $s}from"./QUEUES_FILENAME-BZ6Ak3QY.mjs";import{discoverSandboxUsage as qs}from"./discoverSandboxUsage-zLtQHdkg.mjs";import Vs from"./discoverStorageRulesMetadata-B1gekVBr.mjs";import{a as S,c as z,d as Dt,e as js}from"./classify-procedure-call-C5BOBVM7.mjs";import{discoverWorkflows as Ws}from"./WORKFLOWS_FILENAME-CXgbWxbT.mjs";import{gatePlatformFeatures as Hs,resolveCodegenTarget as Gs}from"./DEFAULT_TARGET-lPq34YeN.mjs";import{i as R,a as _,e as E,r as Ys,b as Xs,s as ce,c as Qs,f as Zs,d as Js}from"./queries-C3PDsG0y.mjs";import en from"./discoverAuthApiCalls-mYYZYULR.mjs";import nt from"./discoverFunctions-BJQ_rvqv.mjs";import{i as tn,r as sn,e as nn}from"./unwrap-handler-return-CmIWbykC.mjs";import rt from"./discoverHttpRoutes-Bsu4ctdh.mjs";import rn from"./discoverHyperdriveCalls-jqn--Zkc.mjs";import on from"./discoverInserts-Bbw_Fkid.mjs";import{m as we,a as te,s as kt,d as an}from"./index-D322boXY.mjs";import{e as Mt}from"./exported-procedure-chains-CH_Ce-wL.mjs";import cn from"./discoverMigrations-ChOwLUzQ.mjs";import{MUTATORS_FILENAME as ln,isDefineMutatorCallee as un,discoverMutators as ot}from"./MUTATORS_FILENAME-DHX1qUP5.mjs";import dn from"./discoverNondeterministicCalls-Cesk1Srg.mjs";import{discoverNotifyConfig as fn,discoverNotifyCalls as gn}from"./NOTIFY_FILENAME-a3lg_dJ9.mjs";import pn from"./discoverR2sqlCalls-DW4RO223.mjs";import mn from"./discoverRlsProcedures-iPEyaH0Q.mjs";import hn from"./discoverRlsMetadata-pjWjG15I.mjs";import xn from"./discoverSchema-C4znXEB-.mjs";import{secretKindOf as En,redact as vn,isHeuristicSecretKind as Sn,isSecretishName as yn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as An}from"./SHAPES_FILENAME-DhZ3JkkH.mjs";import{emitApp as Nn}from"./emitApp-CxmA4W3C.mjs";import{buildOpenApiDocument as bn,emitOpenApiModule as Pn}from"./buildOpenApiDocument-qYjkmRTX.mjs";import{buildOpenRpcDocument as In,emitOpenRpcModule as wn}from"./OPENRPC_VERSION-BgLkvCYK.mjs";import{s as Tn}from"./parse-validator-CMV0eq2a.mjs";import{buildSchemaSnapshot as Cn}from"./SchemaSnapshotParseError-yrVM8bTa.mjs";const it=(e,t="api")=>{const s=new Map;for(const n of e){const o=vs(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new D("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Fn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1}=t,r=[],a=e.tables.filter(c=>c.shardMode==="global");return a.some(c=>c.globalBackend!=="hyperdrive")&&r.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),a.some(c=>c.globalBackend==="hyperdrive")&&r.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&r.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&r.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&r.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"}),r},On=(e,t,s={})=>{if(t===void 0)return;const n=Fn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
|
-
`);throw new D("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
-
${o}
|
|
4
|
-
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},Rn="env.ts",Ln=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ae(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 n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ae(n.getModuleSpecifierValue())}return!1},kn=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},Mn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!kn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ie(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Kn=(e,t)=>{const s=f(t,Rn);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=Mn(n);if(o.length!==0){if(o.length>1)throw ie(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},at="ctx",Kt=e=>{const t=new Set,s=new Set([at]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==at)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},_n=(e,t)=>{const s=Object.fromEntries(xe.map(n=>[n.key,!1]));for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Kt(o);for(const c of xe)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(xe.every(c=>s[c.key]))break}return s},_t="identity.ts",zn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ae(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Un=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ae(n.getModuleSpecifierValue())}return!1},Bn=e=>{if(i.isIdentifier(e))return zn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&Un(t)}return!1},$n=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Bn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ie(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},qn=(e,t)=>{const s=f(t,_t);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=$n(n);if(o.length!==0){if(o.length>1)throw ie(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},Vn=(e,t)=>{const s=W(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return W(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},jn=e=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!i.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||W(s)?.getText()!=="false"}),Wn=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Kt(o).has("secrets")),s.durableStreams||(s.durableStreams=o.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(i.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>jn(Vn(o,u)))})),s.durableStreams&&s.secrets)break}return s},Hn="createWorker",Gn="extend",ct=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,lt=e=>{const t=[],s=ct(A(e,"backupCron"));s!==void 0&&t.push(s);const n=A(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=ct(o.getNameNode());r!==void 0&&t.push(r)}return t},Yn=e=>{const t=S(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Hn)return i.isObjectLiteralExpression(s)?lt(s):[];if(t!==Gn||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=Ot(s.getBody());return n===void 0?[]:lt(n)},Xn=(e,t)=>{const s=[];for(const{filePath:n}of Ie(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...Yn(r))}return[...new Set(s)]},Qn=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new D("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new D("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=o.get(r.className);if(u!==void 0)throw new D("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Zn=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=qn(s,t),a=Kn(s,t),c=Ws(s,t),u=$s(s,t),d=Ss(s,t);Qn(c,d);const y=ys(s,t),x=Vs(s,t),P=As(s,t,c,d),M=Xn(s,t),g=Wn(s,t),T=qs(s,t),C=_n(s,t);C.browser=C.browser||T.usesSandboxBrowser;const $=Hs(C,Gs(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(p=>p.commitOrdered===!0),cronTriggers:P.length>0,crossShardFanout:o.tables.some(p=>typeof p.shardMode=="object"),durableStreams:g.durableStreams,globalTables:o.tables.some(p=>p.shardMode==="global"),queues:u.length>0,secrets:g.secrets,vectorStore:o.vectorIndexes.length>0}),N=$.usage,L=$.signals.vectorStore!==!1,U=Bs(n),q=U??new Set,G=q.has("lunorash");On(o,U,{hasVectors:L,scheduler:N.scheduler||P.length>0,storage:N.storage||x.rules.length>0||Object.keys(Ft(o)).length>0});const K=b(f(t,"flags.ts")),F=b(f(t,"notify.ts"));return{agents:d,containers:y,crons:P,dataModelContent:bs(o),declaredDependencies:U,dependencies:q,entryCronTriggers:M,env:a,featureUsage:N,hasFlags:K,hasNotify:F,identity:r,platformGate:$,queues:u,serverContent:Ns({agents:d,containers:y,env:a,hasAccessFacade:N.access,hasAi:N.ai,hasAnalytics:N.analytics,hasBrowser:N.browser,hasVectors:L,hasFlags:K,hasHyperdrive:N.hyperdrive,hasImages:N.images,hasKv:N.kv,hasNotify:F,hasPayments:N.payments,hasPipelines:N.pipelines,hasR2sql:N.r2sql,hasX402:N.x402,identity:r,queues:u,schema:o,storageRuleBuckets:x.rules.map(p=>p.bucket),useUmbrella:G,workflows:c}),storageRulesMetadata:x,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer||T.usesSandboxFs,useUmbrella:G,workflows:c}},zt=new Set(["delete","get","head","options","patch","post","put"]),Jn=new Set(["handler","stream"]),er=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ut=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),tr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!zt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},sr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||zt.has(n.getName()))break;s=n.getExpression()}return tr(s)},nr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(ut.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&ut.has(s.getText()))return!0}return!1},rr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Jn.has(n.getName()))return;const o=sr(s);if(!o||!er.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&nr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},or=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=rr(o,t);r&&s.push(r)}return s},ir=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...or(o,v(t,n)))}return s},ar=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",cr=(e,t)=>{if(!ar(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)||_(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},lr=(e,t)=>I(e,t,cr),ur=new Set(["generateText","streamText"]),dr=new Set(["messages","prompt","system"]),fr=[{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"]}],gr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of fr)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},pr=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=gr(t);if(s!==void 0)return s}},mr=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},hr=e=>{if(Ys(e))return!0;const t=mr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},xr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!dr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&hr(s))return!0}return!1},Er=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());if(o===void 0||!ur.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(S(c.getExpression())==="tool"&&(a=pr(c),a!==void 0))break;a!==void 0&&s.push({exportName:E(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:xr(r)})}return s},vr=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Er(o,v(t,n)))}return s},Sr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},yr=(e,t)=>{if(!Sr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},Ar=(e,t)=>I(e,t,yr),Ut=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Nr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer();return!n||!i.isObjectLiteralExpression(n)?{objects:[],opaque:!0}:{objects:[n],opaque:Ut(n)}},br=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0];r&&i.isObjectLiteralExpression(r)?(t.push(r),s||=Ut(r)):s=!0}n=o.getExpression()}return{objects:t,opaque:s}},Bt=(e,t)=>t?br(t):Nr(e),Pr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),Ir=new Set(["check","length","max"]),Ae=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},wr=e=>[e,...e.getDescendants()].filter(t=>Ae(t)!==void 0),Tr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(Ir.has(s.getName()))return!0;t=n}},Cr=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=wr(r),c=o.getName();a.some(u=>Ae(u)==="any")?t.push(c):a.some(u=>Ae(u)==="string"&&!Tr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Fr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:o}=Bt(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=Cr(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Or=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Fr(o,t);r&&s.push(r)}return s},Rr=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Or(o,v(t,n)))}return s},Ee=e=>e?.getKind()===l.TrueKeyword,Lr=e=>e?.getKind()===l.FalseKeyword,Dr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,kr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Mr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),Kr=e=>e!==void 0&&i.isCallExpression(e)&&kr.has(S(e.getExpression())??""),_r=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),zr=e=>{const t=A(e,"advanced"),s=A(e,"emailAndPassword"),n=A(e,"session");return{analyzable:!0,disableCsrfCheck:Ee(A(t,"disableCSRFCheck")),emailPasswordEnabled:Ee(A(s,"enabled")),requireEmailVerification:Ee(A(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Mr(A(e,"plugins"))&&Kr(A(e,"database")),secureCookiesDisabled:Lr(A(t,"useSecureCookies")),sessionFreshAgeZero:Dr(A(n,"freshAge")),trustedOriginsWildcard:_r(A(e,"trustedOrigins"))}},Ur=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Br=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?zr(s):Ur();return{exportName:E(e),file:t,line:e.getStartLineNumber(),...o}},$r=(e,t)=>_s(e,t,Br),qr=(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},Vr=(e,t,s)=>{const n=qr(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!R(o)||_(o))&&!(s.requireUnmodifiedReach===!0&&!Xs(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:n}},jr=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=Vr(o,t,s);r&&n.push(r)}return n},le=(e,t,s)=>{const n=[];for(const o of m(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...jr(r,v(t,o),s))}return n},Wr=new Set(["content","pdf","scrape","screenshot"]),Hr=(e,t)=>le(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Wr}),Gr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Yr=new Set(["RateLimiter"]),Xr=new Set(["extend"]),dt="lunora",Qr=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],$t=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Ne=e=>e&&i.isObjectLiteralExpression(e)?$t(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Zr=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Ot(t.getBody());return s?$t(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Jr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());o!==void 0&&(Gr.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ne(n.getArguments()[0])}):Xr.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Zr(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=S(n.getExpression());o===void 0||!Yr.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Ne(n.getArguments()[0])})}return s},eo=(e,t)=>{for(const s of Qr){const n=f(t,s);if(!b(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))S(a.getExpression())===dt&&r.push({callee:dt,file:s,line:a.getStartLineNumber(),...Ne(a.getArguments()[0])});return r}return[]},to=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Ie(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...Jr(r,n))}return s.push(...eo(e,J(t))),s},ft="ctx.containers.",so=e=>{if(!e.startsWith(ft))return!1;const t=e.slice(ft.length);return t.length>0&&!t.includes(".")},no=(e,t)=>le(e,t,{argIndex:0,matchReceiver:so,methods:new Set(["get"])}),ro=new Set(["allow","deny","setAllowed"]),oo=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())},io=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!oo(e)))return{detail:"enableInternet: true",exportName:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},ao=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!ro.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},co=(e,t)=>io(e,t)??ao(e,t),lo=(e,t)=>I(e,t,co),uo=new Set(["defineExportSink","r2Sink","webhookExportSink"]),fo=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return uo.has(s)?s:void 0},go=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},po=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Ie(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=fo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?go(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},mo=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ho=new Set(["dbRateLimit","rateLimit"]),xo=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Eo=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const n=mo.get(s);if(n!==void 0)return{callee:s,exportName:E(e),failOpen:xo(e.getArguments()[n]),file:t,limitName:ho.has(s)?Rt(e):"",line:e.getStartLineNumber()}},vo=(e,t)=>I(e,t,Eo),So=new Set(["boolean","number","object","string"]),yo=e=>{const t=e.getName();if(!So.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&ye(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&ye(n.getExpression()))return t},Ao=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=yo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},No=(e,t)=>{const s=new Map;for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=Ao(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},bo=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=zs(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},gt=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},Po=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=gt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=gt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},Io=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=Po(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},wo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=bo(o);r&&s.push(...Io(r,t))}return s},To=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...wo(o,v(t,n)))}return s},Co=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ye(t.getExpression())},Fo=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Oo=(e,t)=>{if(!Co(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=Fo(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:E(e),file:t,key:o,line:e.getStartLineNumber()}},Ro=(e,t)=>I(e,t,Oo),Lo=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||tn(r))return;const a=e.getSourceFile().getFilePath();return sn(o,e,a)?nn(o,e,a,0,new Set):r},Do=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},ko=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Mo=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))Do(a)&&s.push({file:r,indexName:ko(a),line:a.getStartLineNumber()})}return s},H=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,qt=e=>{const t=e.getArguments()[0],s=H(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&i.isPropertyAssignment(n)?H(n.getInitializer()):void 0},Ko=new Set(["delete","get","head","options","patch","post","put"]),_o=new Set(["handler","stream"]),zo=new Set(["runAction","runMutation"]),Uo=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),se=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,pt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return i.isIdentifier(n)?n.getText():void 0;if(i.isObjectBindingPattern(n)){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="ctx"){const a=o.getNameNode();return i.isIdentifier(a)?a.getText():void 0}}},mt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(zo.has(a)&&se(c,t))return a;if(Uo.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&se(c.getExpression(),t))return`db.${a}`}},ht=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&se(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!se(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},Bo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!_o.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(Ko.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},$o=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=H(e.getArguments()[0]),u=c&&pt(c,!0);if(!c||u===void 0)return;const d=mt(c,u);return d===void 0?void 0:{exportName:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ht(c,u),sideEffect:d}}const n=Bo(e);if(n===void 0)return;const o=H(e.getArguments()[0]),r=o&&pt(o,!1);if(!o||r===void 0)return;const a=mt(o,r);return a===void 0?void 0:{exportName:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:ht(o,r),sideEffect:a}},qo=(e,t)=>I(e,t,$o),Vo=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),jo=new Set(["append","set"]),Vt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",xt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Vo.has(S(n.getExpression())??"")&&Zs(n,t)),Wo=(e,t)=>{if(xt(e,t))return!0;const s=ce(e);return s!==void 0&&xt(s,t)},be=(e,t)=>Qs(e,t)&&!Wo(e,t),Ho=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ce(e);return t!==void 0&&i.isNewExpression(t)&&S(t.getExpression())==="Headers"},ne=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=ce(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Te=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&be(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Vt(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();be(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=ne(n.getExpression());o!==void 0&&Te(o,t,s)}},jt=(e,t)=>{const s=ne(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=ne(n.getInitializer());o!==void 0&&Te(o,"response-init",t)},Go=(e,t)=>{const s=S(e.getExpression());if(s==="Response")jt(e.getArguments()[1],t);else if(s==="Headers"){const n=ne(e.getArguments()[0]);n!==void 0&&Te(n,"headers-ctor",t)}},Yo=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){jt(e.getArguments()[1],t);return}if(jo.has(n)&&Ho(o)){const r=e.getArguments()[1];r!==void 0&&be(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Vt(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Xo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Go(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Yo(s,t)},Qo=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=H(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return Xo(n,{exportName:E(e),relativePath:t,requestName:r.getText(),rows:a}),a},Zo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...Qo(n,t));return s},Jo=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Zo(o,v(t,n)))}return s},ei=new Set(["auth","context.auth","ctx.auth"]),ti="userId",si=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},ni=(e,t)=>{const s=f(t,_t);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(S(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?si(r):void 0}},Et=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return ei.has(e.getExpression().getText())?e:void 0},ri=e=>{if(i.isPropertyAccessExpression(e)&&Et(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Et(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},oi=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=ri(o);r!==void 0&&n.push({declared:r===ti||s.has(r),exportName:E(o),file:t,key:r,line:o.getStartLineNumber()})}return n},ii=(e,t)=>{const s=ni(e,t);if(s===void 0)return[];const n=[];for(const o of m(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...oi(r,v(t,o),s))}return n},ai=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=A(s,"key");if(!(!n||!R(n)||_(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},ci=(e,t)=>I(e,t,ai),li=new Set(["delete","get","getRaw","getWithMetadata","put"]),ui=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return le(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:li}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},di=new Set(["queue","send"]),vt=new Set(["bcc","cc","to"]),fi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!di.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},gi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return vt.has(t.getName())&&R(n)&&!_(n)}if(!i.isPropertyAssignment(t)||!vt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&R(s)&&!_(s)}):!1,pi=(e,t)=>{const s=fi(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!gi(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},mi=(e,t)=>I(e,t,pi),hi=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,xi=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?hi(e):!0,Wt=(e,t=!1)=>{for(const s of e.getProperties()){if(xi(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||Wt(n,!0))return!0}return!1},Ei=(e,t)=>{for(const s of m(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Mt(n))for(const r of we(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||Wt(a)))return!0}}return!1},vi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=te(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=te(a);c!==void 0&&s.push({column:c,strategy:kt(a),table:o})}}return s},Si=(e,t)=>{const s=new Map;for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Mt(o))for(const a of we(r))for(const c of vi(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},yi=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=te(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=te(u);if(d===void 0)continue;const y=kt(u);y!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:y,table:a})}}return o},Ai=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?z(s):void 0;return n?.receiver?we(n.receiver).flatMap(o=>yi(o,e.getName(),t)):[]},Ni=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ai(c,r))}return s},bi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return k(s)},Pi=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},Ii=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return un(s.getExpression())?s:void 0},wi=e=>{const t=Ii(e),s=t===void 0?void 0:Pi(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>bi(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Ti=e=>e.getVariableDeclarations().flatMap(t=>wi(t)),Ci=(e,t)=>{const s=f(t,ln);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Ti(n)},Fi=new Set(["delete","get","patch"]),Oi=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"]),Li=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Di=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():""},ki=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},Mi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ki=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,_i=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Mi(s.getExpression(),t)&&Ki(s.getThenStatement())),zi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!Fi.has(o))continue;const r=n.getExpression();if(!(k(r)||i.isPropertyAccessExpression(r)&&k(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},Ui=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},Bi=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Ui(s)==="ctx")),$i=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Li.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),qi=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Oi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Ri.has(t.getName()))return!0}return Bi(e)||$i(e)},Vi=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=qt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Dt(n.receiver,"use","rls"),a=qi(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const y=Di(d);if(y===void 0)continue;const x=ki(d);if(x===void 0||c.has(x)||!_i(o,x))continue;const P=zi(o,x);P!==void 0&&(c.add(x),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:P,table:y,usesRls:r,visibility:n.visibility}))}return u},ji=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Vi(c,r))}return s},Wi=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Hi=new Set(["insert","insertManyUnsafe","patch","replace"]),Gi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Hi.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Yi=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},Xi=(e,t,s,n)=>{const o=[];for(const r of e.getProperties()){let a,c;i.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):i.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!Wi.has(a))&&R(c)&&!_(c)&&o.push({exportName:E(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return o},Qi=(e,t)=>{const s=Gi(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?Yi(n,s).flatMap(o=>Xi(o,s,e,t)):[]},Zi=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of Qi(o,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Ji=(e,t,s=[])=>{const n=[],o=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of m(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=v(t,r);n.push(...Zi(a,c,u=>o.get(`${c}:${u}`)))}return n},ea=["providerSubscriptionId","state"],ta=["providerEventId","processedAt"],St=(e,t)=>t.every(s=>s in e.shape),sa=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&St(t,ea)&&St(s,ta)},na=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ra=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,oa=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ra(t.getInitializer()):void 0},ia=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!na.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?oa(n):void 0;return{callee:s,exportName:E(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},aa=(e,t)=>I(e,t,ia),ca=new Set(["defineQueue","defineWorkflow"]),la=new Set(["run","runAction","runMutation","runQuery"]),ua=new Set(["api","internal"]),da=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},fa=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},Ht=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Gt=(e,t)=>e===t||e.startsWith(`${t}.`),Yt=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},yt=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)},Xt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>yt(s));return i.isIdentifier(e)&&yt(e)&&t.push(e),t},ga=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},pa=e=>{const t=Ht(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ma=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:pa(e),o=new Set,r=a=>Yt(a).some(c=>n.some(u=>Gt(c.getText(),u)))?!0:Xt(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of ga(a))o.add(u)}return{names:o,prefixes:n}},ha=(e,t)=>Yt(e).some(s=>t.prefixes.some(n=>Gt(s.getText(),n)))?!0:Xt(e).some(s=>t.names.has(s.getText())),xa=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!ua.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Ea=(e,t,s)=>{const n=Ht(e,0);if(n===void 0)return[];const o=ma(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!la.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!ha(u,o))continue;const d=xa(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:E(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},va=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=da(n);if(o===void 0||!ca.has(o))continue;const r=fa(n);r!==void 0&&s.push(...Ea(r,o==="defineQueue"?"queue":"workflow",t))}return s},Sa=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...va(o,v(t,n)))}return s},At={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Nt=new Set(["account","credential","member","passkey","session","user"]),ya=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Aa=e=>{const s=ya(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Nt.has(s)||Nt.has(n)},Na=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ba=(e,t)=>{const{objects:s,opaque:n}=Bt(e,t);return Pr(s).some(o=>Na(o))?!0:n?void 0:!1},Pa=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ia=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},ee={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},wa=e=>{const t=Ia(e),s=t?S(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Pa(t);return{...ee,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in At?{...ee,[At[s]]:!0}:ee},Ta=e=>{const t={...ee};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=wa(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Ca=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Fa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ca.has(t.getName()))return!1;const s=t.getExpression();if(!k(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:Aa(o.getLiteralText())},Oa=new Set(["create","runAfter","runAt","send","sendBatch"]),Ra=new Set(["queues","scheduler","workflows"]),La=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Oa.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Ra.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Da=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return k(s)},Qt=new Set(["generateObject","generateText","streamObject","streamText"]),ka=e=>{const t=S(e.getExpression());return t!==void 0&&Qt.has(t)},Ma=e=>{const t=S(e.getExpression());if(t===void 0||!Qt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Ka=new Set(["log","span","trace"]),_a=new Set(["ai"]),za=new Set(["email","mail"]),Ua=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),ve=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),Ba=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),$a=new Set(["every","filter","flatMap","forEach","map","some"]),qa=new Set(["all","allSettled","race"]),Va=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if($a.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&qa.has(n))return t},ja=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ba.has(t.getKind())){const s=Va(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Wa=e=>{let t=e;for(;;){const s=t.getParent();if(!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Ha=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ga=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Ua.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=Ha(n);r&&(t=!0,!ja(r)&&!Wa(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ya=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),bt="lunora-advisor-exempt",Xa=/^[\s*/]+/u,Qa=/[\w-]/u,Za=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
|
-
`);for(const n of s.split(`
|
|
7
|
-
`)){const o=n.replace(Xa,"");if(!o.startsWith(bt))continue;const r=o.slice(bt.length);if(Qa.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ja=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},ec=(e,t)=>{const s=Ja(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},tc=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Fa(u)&&(r=!0),La(u)&&(t=!0),Da(u)&&(o=!0),ka(u)&&(s=!0),Ma(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ga(e);return{callsMail:ve(e,za),emitsEvent:ve(e,Ka),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||ve(e,_a),throwsBareError:Ya(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},sc=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?Ta(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=ec(e,s);return{...r?tc(r):{},...Za(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:ba(s,n.receiver),kind:n.kind,visibility:n.visibility}},nc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=sc(o,t);r&&s.push(r)}return s},rc=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...nc(o,v(t,n)))}return s},oc=new Set(["dbRateLimit","rateLimit"]),ic=e=>i.isArrowFunction(e)?e.getBody():e,ac=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!oc.has(s))return;const n=e.getArguments()[2];if(!n)return;const o=A(n,"key");if(!o)return;const r=ic(o);if(!(!R(r)||_(r)))return{callee:s,exportName:E(e),file:t,limitName:Rt(e),line:e.getStartLineNumber()}},cc=(e,t)=>I(e,t,ac),lc=new Set(["findFirst","findFirstOrThrow","findMany","get"]),uc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!lc.has(t.getName()))return;const s=t.getExpression();if(k(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&k(s.getExpression()))return s.getName()},dc=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 n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},fc=e=>{let t=W(e)??e;for(;i.isAwaitExpression(t);)t=W(t.getExpression())??t.getExpression();return t},Zt=(e,t=!1)=>{const s=fc(e);if(i.isIdentifier(s)){if(t)return;const n=ce(s);return n===void 0?void 0:Zt(n,!0)}if(i.isCallExpression(s))return uc(s)??dc(s)},gc=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},pc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const o=qt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&js(n.receiver,"output"),a=n.receiver!==void 0&&Dt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of gc(o)){const y=Zt(d);y===void 0||c.has(y)||(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:y,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},mc=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...pc(c,r))}return s},hc=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},xc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?z(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Lt(r);if(a===void 0)continue;const c=hc(A(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},Ec=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...xc(c,r))}return s},re=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=re(e.getLeft()),s=re(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},vc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&re(t)!==void 0},Sc=/(?:^|\/)__tests__\//u,yc=/\.(?:spec|test)$/u,Ac=e=>Sc.test(e)||yc.test(e),Nc=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},bc=(e,t,s)=>Sn(e)?!Ac(s)&&yn(Nc(t)):!0,Pc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(vc(r))continue;const a=re(r);if(a===void 0)continue;const c=En(a);if(c===void 0||!bc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:vn(a)}))}return s},Ic=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Pc(o,v(t,n)))}return s},wc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?z(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Lt(r);if(a===void 0)continue;const c=A(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&R(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},Tc=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...wc(c,r))}return s},Cc=new Set(["query","unsafe"]),Fc=e=>{if(!i.isPropertyAccessExpression(e)||!Cc.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"},Oc=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Rc=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Lc=(e,t)=>{if(!Fc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Oc(s)))return{exportName:Rc(e),file:t,line:s.getStartLineNumber()}},Dc=(e,t)=>I(e,t,Lc),kc=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Mc=e=>{for(const[t,s]of kc)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Kc=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Mc(a);c!==void 0&&s.push({file:v(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},_c=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),zc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return le(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:_c,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Uc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Bc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,$c=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=Bc(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},qc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Uc.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Vc=(e,t)=>{const s=qc(e.getExpression());if(s!==void 0)return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...$c(e.getArguments()[s.optionsIndex])}},jc=(e,t)=>I(e,t,Vc),Wc=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Hc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),Ce=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&Hc.has(s)?s:void 0},Jt=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},es={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},Gc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},Fe=(e,t,s,n,o)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${s}\` but was not registered — ${o.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${o.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),Yc=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(s.has(`${t}:${a}`)||!Jt(r))continue;const c=Ce(r);c!==void 0&&n.push(Fe(t,a,c,r.getStartLineNumber(),es))}return n},Xc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ce(o.getExpression());r!==void 0&&n.push(Fe(t,"default",r,o.getStartLineNumber(),es))}return n},Qc=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(s.has(`${t}:${a}`))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!Jt(c))continue;const u=Ce(c);u!==void 0&&n.push(Fe(t,a,u,r.getStartLineNumber(),Gc))}return n},Zc=(e,t,s)=>[...Yc(e,t,s),...Xc(e,t,s),...Qc(e,t,s)],Jc=(e,t,s)=>{const n=new Set(s.map(r=>`${r.filePath}:${r.exportName}`)),o=[];for(const r of m(t)){const a=e.getSourceFile(r);a!==void 0&&o.push(...Zc(a,v(t,r),n))}return o.toSorted((r,a)=>r.cacheKey.localeCompare(a.cacheKey))},el=new Set(["when","where"]),Se=new Set(["definePolicy","defineShape"]),tl=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return Se.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return Se.has(o)?o:void 0}const s=t.getText();return Se.has(s)?s:void 0},sl=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,ts=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(sl(e))return"empty-object";if(i.isParenthesizedExpression(e))return ts(e.getExpression())}},Oe=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),nl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Oe(t)===e),ss=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Oe(t)===e),rl=e=>{const t=nl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||ss(e).length>0},ol=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>Oe(t)===e),Pe=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",il=(e,t)=>Pe(e)||Pe(t),al=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Pt=e=>!Pe(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),cl=(e,t,s)=>{const n=al.get(e);if(n!==void 0)return il(t,s)?n==="positive"?"negative":"positive":Pt(t)||Pt(s)?void 0:n},j=e=>{if(i.isParenthesizedExpression(e))return j(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=cl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=j(e.getLeft()),o=j(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},It=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},ll=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},ul=e=>i.isReturnStatement(e)?e.getExpression()??e:e,dl=e=>{const t=[];for(const s of ss(e)){const n=j(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of ol(e)){const n=j(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?It(s.getThenStatement()):It(s.getElseStatement())??ll(s);o!==void 0&&t.push(ul(o))}return t},fl=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},gl=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!el.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&rl(a))for(const c of dl(a)){const u=ts(c);u!==void 0&&o.push({exportName:fl(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},pl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=tl(n);o!==void 0&&s.push(...gl(n,o,t))}return s},ml=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pl(o,v(t,n)))}return s},hl=new Set(["query","upsert","upsertMany"]),xl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(hl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},El=(e,t)=>{const s=xl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=A(n,"namespace");if(!(!o||!R(o)||_(o)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},vl=(e,t)=>I(e,t,El),Sl=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"},yl=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Al=(e,t)=>{const s=[];for(const n of m(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Sl(a))continue;const c=Us(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:yl(a)})}}return s},Nl=".lunora-schema.json",w=(e,t)=>{b(e)&&Ct(e,"utf8")===t||ps(e,t,"utf8")},O=(e,t)=>{if(t===""){ms(e,{force:!0});return}w(e,t)},bl=e=>{const t=f(e,"package.json");if(b(t))try{const s=JSON.parse(Ct(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Pl=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Il=e=>{let t=b(e)?e:J(e);for(;t&&t!==J(t);){const s=f(t,"tsconfig.json");if(b(s))return s;t=J(t)}},wt=e=>e.replaceAll("\\","/"),wl=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new D("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new D("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new D("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},oe=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Tt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,Tl=8,Cl=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:y}=e;let x=nt(a,o),P=ot(a,o),M=rt(a,o);it([...x,...P].map(g=>g.filePath)),it(M.filter(g=>g.stream).map(g=>g.filePath),"http-stream");for(let g=1;;g+=1){const T=Ms({agents:t,functions:x,httpRoutes:M,mutators:P,useUmbrella:d,workflows:y}),C=Ks({agents:t,functions:x,migrations:r,mutators:P,shapes:c,useUmbrella:d,usesSandbox:u});if(g>=Tl||Tt(a,s,T)&&Tt(a,n,C))return{apiContent:T,functions:x,functionsContent:C,httpRoutes:M,mutators:P};oe(a,s,T),oe(a,n,C),x=nt(a,o),P=ot(a,o),M=rt(a,o)}},Fl=e=>{const t=Il(e);return t?new st({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new st({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},bu=(e,t)=>{const s=m(t),n=f(t,"schema.ts");b(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const o=new Set(s.map(c=>wt(c))),r=wt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Pu=e=>{const t=Pl(),s=t?he.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),o=f(n,"schema.ts");if(!b(o))throw new D("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??Fl(n);Tn(Lo);const a=xn(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:y,dependencies:x,entryCronTriggers:P,env:M,featureUsage:g,hasFlags:T,hasNotify:C,identity:$,platformGate:N,queues:L,serverContent:U,storageRulesMetadata:q,usesSandbox:G,useUmbrella:K,workflows:F}=Zn({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),p=f(n,"_generated"),Re=f(p,"dataModel.ts"),Le=f(p,"server.ts"),ns=f(p,"api.ts"),rs=f(p,"functions.ts");oe(r,Re,y),oe(r,Le,U);const ue=cn(r,n),V=An(r,n),{apiContent:De,functions:B,functionsContent:ke,httpRoutes:os,mutators:is}=Cl({agents:c,apiPath:ns,generatedFunctionsPath:rs,lunoraDirectory:n,migrations:ue,project:r,shapes:V,useUmbrella:K,usesSandbox:G,workflows:F}),Y=e.lint===!1?void 0:Es({adminRoutes:ir(r,n),aiRawRuns:lr(r,n),aiToolSideEffects:vr(r,n),argumentDerivedFetches:Ar(r,n),argumentValidators:Rr(r,n),authApiCalls:en(r,n),authConfigs:$r(r,n),browserUrlAccesses:Hr(r,n),configCalls:to(r,n),containerKeyAccesses:no(r,n),containerOverrides:lo(r,n),containers:u,exportSinks:po(r,n),staleMigrationImports:Kc(r,n),failOpenGuards:vo(r,n),flagReads:To(r,n),flagSecurityDefaults:Ro(r,n),geoIndexUsages:Mo(r,n),httpActionGuards:qo(r,n),httpHeaderWrites:Jo(r,n),hyperdriveCalls:rn(r,n),identityClaimReads:ii(r,n),imageDeliveryUrlAccesses:ci(r,n),inserts:on(r,n),kvKeyAccesses:ui(r,n,B),mailRecipientAccesses:mi(r,n),maskProcedures:an(r,n),maskStrategies:Ni(r,n),mutatorWrites:Ci(r,n),nondeterministicCalls:dn(r,n),normalizeIdAuthorizations:ji(r,n),notifyCalls:gn(r,n),notifyConfig:fn(r,n),ownerFieldWrites:Ji(r,n,B),unrestrictedWhereBranches:ml(r,n),paymentWebhooks:aa(r,n),privilegedDispatches:Sa(r,n),procedureProtections:rc(r,n),queries:Js(r,n),queues:L,r2sqlCalls:pn(r,n),ratelimitKeySelectors:cc(r,n),rawRowReturns:mc(r,n),relationLoads:Ec(r,n),rlsProcedures:mn(r,n),schema:a,secretLiterals:Ic(r,n),shapes:V,softDeleteReads:Tc(r,n),sqlInterpolations:Dc(r,n),storageKeyAccesses:zc(r,n,B),storageUploads:jc(r,n),vectorNamespaceAccesses:vl(r,n),workflowCalls:Al(r,n),workflows:F,wranglerVariables:e.wranglerVariables}),Me=Y===void 0?[]:[...hs(Y,{source:"static"}),...Jc(r,n,B)],as=hn(r,n),Ke=Si(r,n);wl(V,Ke,Ei(r,n));const cs=T?No(r,n):[],de=N.signals.vectorStore!==!1,X=Wc(g,{containerCount:u.length,cronCount:d.length,dependencies:x,hasPaymentTables:sa(a.tables),queueCount:L.length,storageColumnCount:Object.keys(Ft(a)).length,storageRuleCount:q.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:de,workflowCount:F.length}),_e=t?he.now():0,fe=Cn(a,ue.map(h=>h.id)),ze=Ps({advisories:Me,advisorProcedures:Y?.procedureProtections??[],agents:c,containers:u,env:M,flagKeys:cs,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:T,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:C,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:de,hasX402:g.x402,maskMetadata:Ke,mutators:is,queues:L,rlsMetadata:as,schema:a,schemaSnapshot:fe,shapes:V,storageRules:q,studioFeatures:X,useUmbrella:K,workflows:F}),Ue=Is(V,x.has("@lunora/db"),K),Be=ws(u,a.jurisdiction),$e=Ts(F),qe=Cs(c),Ve=Fs(L),je=Os(d),We=Rs(a.vectorIndexes),Q=Ls(a,K),He=Ds(x.has("@lunora/seed")),Z=e.apiSpec??"openapi",ge=Z==="openapi"||Z==="both",pe=Z==="openrpc"||Z==="both",Ge=Nn({emailAgents:c.filter(h=>h.onEmail===!0).map(h=>({bindingName:h.bindingName,exportName:h.exportName})),hasAccess:x.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:x.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:x.has("@lunora/astro")||x.has("@lunora/svelte")||x.has("@lunora/vue"),hasGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend!=="hyperdrive"),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend==="hyperdrive"),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:X.kv,hasNotify:C,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:L.some(h=>h.mode==="push"),hasScheduler:X.scheduler,hasStorage:X.storage,hasVectors:de,hasWorkflow:F.length>0,hasX402:g.x402,identity:$,jurisdiction:a.jurisdiction,tableNames:a.tables.map(h=>h.name),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(h=>h.voice===!0&&h.voiceBindingName!==void 0).map(h=>({bindingName:h.voiceBindingName,exportName:h.exportName})),wantsOpenApi:ge,wantsOpenRpc:pe}),Ye=bl(e.projectRoot),Xe=bn({functions:B,httpRoutes:os,version:Ye}),Qe=In({functions:B,version:Ye}),Ze=`${JSON.stringify(Xe,void 0,2)}
|
|
8
|
-
`,Je=`${JSON.stringify(Qe,void 0,2)}
|
|
9
|
-
`,et=Pn(Xe),tt=wn(Qe),me=f(n,Nl),ls=b(me);if(e.dryRun||(b(p)||gs(p,{recursive:!0}),w(f(p,"app.ts"),Ge),w(Re,y),w(f(p,"api.ts"),De),w(Le,U),w(f(p,"functions.ts"),ke),w(f(p,"shard.ts"),ze),w(f(p,"crons.ts"),je),w(f(p,"vectors.ts"),We),w(f(p,"drizzle.global.ts"),Q.global),w(f(p,"drizzle.shard.ts"),Q.shard),O(f(p,"containers.ts"),Be),O(f(p,"workflows.ts"),$e),O(f(p,"agents.ts"),qe),O(f(p,"queues.ts"),Ve),O(f(p,"seed.ts"),He),O(f(p,"collections.ts"),Ue),O(f(p,"openapi.json"),ge?Ze:""),O(f(p,"openapi.ts"),ge?et:""),O(f(p,"openrpc.json"),pe?Je:""),O(f(p,"openrpc.ts"),pe?tt:""),(!ls||e.updateSchemaBaseline===!0)&&w(me,xs(fe))),t){const h=he.now(),us=Math.round(h-s),ds=Math.round(_e-s),fs=Math.round(h-_e);console.error(`@lunora/codegen: codegen took ${us.toString()}ms (discovery ${ds.toString()}ms, emit ${fs.toString()}ms)`)}return{advisories:Me,advisorContext:Y,agents:c,containers:u,cronTriggers:[...new Set([...ks(d),...P])],generated:{agents:qe,api:De,app:Ge,collections:Ue,containers:Be,crons:je,dataModel:y,drizzleGlobal:Q.global,drizzleShard:Q.shard,functions:ke,openApi:Ze,openApiModule:et,openRpc:Je,openRpcModule:tt,queues:Ve,seed:He,server:U,shard:ze,vectors:We,workflows:$e},migrations:ue,outputDirectory:p,platformDiagnostics:N.diagnostics,queues:L,schemaSnapshot:fe,schemaSnapshotPath:me,workflows:F}};export{Nl as SCHEMA_SNAPSHOT_FILENAME,Fl as createCodegenProject,Il as findTsconfig,bu as refreshCodegenProject,Pu as runCodegen};
|