@lunora/codegen 1.0.0-alpha.242 → 1.0.0-alpha.243

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUziztz.mjs";const x=e=>e?{importFragment:"serveRelationFanout, ",override:`
1
+ import{s as h}from"./ir-DBSvhNa-.mjs";import{r as g}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUziztz.mjs";const w=e=>e?{importFragment:"serveRelationFanout, ",override:`
2
2
  protected override async runRelationFanoutRead(functionPath: string, args: Record<string, unknown>): Promise<unknown> {
3
3
  this.ensureMigrated();
4
4
 
@@ -6,7 +6,7 @@ import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUzi
6
6
 
7
7
  return serveRelationFanout(schema as unknown as SchemaLike, db, functionPath, args);
8
8
  }
9
- `}:{importFragment:"",override:""},k=e=>e?{build:`
9
+ `}:{importFragment:"",override:""},R=e=>e?{build:`
10
10
  const aiBinding = config.ai?.(env) ?? (env as Record<string, unknown>).AI;
11
11
  // Correlate AI-Gateway-routed calls with the Lunora trace: thread the
12
12
  // function path + trace id into createAi, which folds them into the
@@ -30,7 +30,7 @@ import{r as p}from"./json-data-Chfs2Cz5.mjs";import{a,G as d}from"./shared-DjUzi
30
30
  const ${e} = {
31
31
  ${i}
32
32
  }${r};
33
- `},c={build:"",configField:"",contextField:"",importLines:[],stub:""},w=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
33
+ `},c={build:"",configField:"",contextField:"",importLines:[],stub:""},N=e=>e.size===0?{configField:"",constant:"",override:""}:{configField:"\n /** The `ShardRegistryDO` namespace (typically `env.SHARD_REGISTRY`). This shard registers its key for each `.shardBy()` table it writes, so cross-shard export, sync and migrations reach it. */\n shardRegistry?: (env: Record<string, unknown>) => unknown;",constant:`
34
34
  /** The \`.shardBy()\` tables this shard registers with the shard registry when it writes them. */
35
35
  const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(t=>JSON.stringify(t)).join(", ")}]);
36
36
  `,override:`
@@ -39,7 +39,7 @@ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(t=>JSON.string
39
39
 
40
40
  return namespace === undefined ? undefined : { namespace, shardedTables: SHARDED_TABLES };
41
41
  }
42
- `},R=e=>e?{build:`
42
+ `},S=e=>e?{build:`
43
43
  const kvBinding = config.kv?.(env) ?? (env as Record<string, unknown>).KV;
44
44
  // KV is not this shard's SQLite, so nothing appends a \`__cdc_log\` entry
45
45
  // when a value changes — a subscription that read one can never be proven
@@ -53,31 +53,31 @@ const SHARDED_TABLES: ReadonlySet<string> = new Set([${[...e].map(t=>JSON.string
53
53
  ]);
54
54
  `,configField:`
55
55
  kv?: (env: Record<string, unknown>) => KVNamespaceLike;`,contextField:`
56
- kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:l("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:c,N=(e,t)=>e?{build:`
56
+ kv,`,importLines:['import type { Kv, KVNamespaceLike } from "@lunora/bindings/kv";','import { createKv } from "@lunora/bindings/kv";'],stub:l("kvStub: Kv",'throw new Error("ctx.kv: no KV binding found. Add a \\`kv_namespaces\\` binding (env.KV) to wrangler.jsonc, or pass \\`kv\\` to createShardDO().");',["delete","get","getRaw","getWithMetadata","list","put"])}:c,L=(e,t)=>e?{build:`
57
57
  const flags: import("${t}").LunoraFlags = createFlags(flagsConfig, env, {
58
58
  provider: () => config.flags?.(env),
59
59
  targetingKey: () => flagsConfig.identify?.({ identity: identity ?? null, userId: userId ?? null }),
60
60
  });
61
61
  `,configField:`
62
62
  flags?: (env: Record<string, unknown>) => import("${t}").Provider;`,contextField:`
63
- flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:c,S=e=>e?{build:`
63
+ flags,`,importLines:[`import { createFlags } from "${t}";`,'import flagsConfig from "../flags.js";'],stub:""}:c,$=e=>e?{build:`
64
64
  const { notify, push } = createNotify(notifyConfig, env, { log, metrics });
65
65
  `,configField:"",contextField:`
66
66
  notify,
67
- push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:c,L=e=>e?{build:`
67
+ push,`,importLines:['import { createNotify } from "@lunora/notify";','import notifyConfig from "../notify.js";'],stub:""}:c,A=e=>e?{build:`
68
68
  const envConfig = lunoraEnvContract.${e.exportName}(env);
69
69
  `,configField:"",contextField:`
70
- env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:c,A=e=>e?{build:`
70
+ env: envConfig,`,importLines:['import * as lunoraEnvContract from "../env.js";'],stub:""}:c,F=e=>e?{build:`
71
71
  const access = accessFacade(identity, userId);
72
72
  `,configField:"",contextField:`
73
- access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:c,F=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
73
+ access,`,importLines:['import { accessFacade } from "@lunora/cloudflare-access/context";'],stub:""}:c,C=(e,t,n)=>{if(!t)return{constant:"",evaluateOverride:"",subscriptionOverride:""};const r=s=>`
74
74
  const env = (this.env ?? {}) as Record<string, unknown>;
75
75
  const flags: import("${n}").LunoraFlags = createFlags(flagsConfig, env, {
76
76
  provider: () => config.flags?.(env),
77
77
  targetingKey: ${s},
78
78
  });`,o=`
79
79
  /** Statically-discovered feature flags (\`ctx.flags.<type>("key")\` reads) served via \`__lunora_admin__:listFlags\` + the reactive \`__lunora_flags__:\` channel. */
80
- const LUNORA_FLAG_KEYS = ${p(e,'ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }>')};
80
+ const LUNORA_FLAG_KEYS = ${g(e,'ReadonlyArray<{ key: string; type: "boolean" | "number" | "object" | "string" }>')};
81
81
  `,i=`
82
82
  protected override async evaluateFlags(context?: Record<string, unknown>): Promise<FlagsResult> {${r("undefined")}
83
83
  const evalContext = context as import("${n}").EvaluationContext | undefined;
@@ -132,25 +132,25 @@ const LUNORA_FLAG_KEYS = ${p(e,'ReadonlyArray<{ key: string; type: "boolean" | "
132
132
 
133
133
  return flags.boolean(key, typeof args.default === "boolean" ? args.default : false, context);
134
134
  }
135
- `;return{constant:o,evaluateOverride:i,subscriptionOverride:u}},$=e=>e?{build:`
135
+ `;return{constant:o,evaluateOverride:i,subscriptionOverride:u}},_=e=>e?{build:`
136
136
  const analyticsBinding = config.analytics?.(env) ?? (env as Record<string, unknown>).ANALYTICS;
137
137
  const analytics: AnalyticsClient = analyticsBinding ? createAnalytics(analyticsBinding as AnalyticsEngineDatasetLike) : analyticsStub;
138
138
  `,configField:`
139
139
  analytics?: (env: Record<string, unknown>) => AnalyticsEngineDatasetLike;`,contextField:`
140
- analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:l("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:c,C=e=>e?{build:`
140
+ analytics,`,importLines:['import type { AnalyticsClient, AnalyticsEngineDatasetLike } from "@lunora/bindings/analytics";','import { createAnalytics } from "@lunora/bindings/analytics";'],stub:l("analyticsStub: AnalyticsClient",'throw new Error("ctx.analytics: no Analytics Engine binding found. Add an \\`analytics_engine_datasets\\` binding (env.ANALYTICS) to wrangler.jsonc, or pass \\`analytics\\` to createShardDO().");',["track","writeDataPoint"],{sync:["track","writeDataPoint"]})}:c,E=e=>e?{build:`
141
141
  const imagesBinding = config.images?.(env) ?? (env as Record<string, unknown>).IMAGES;
142
142
  const images: Images = imagesBinding ? createImages({ binding: imagesBinding as ImagesBindingLike }) : imagesStub;
143
143
  `,configField:`
144
144
  images?: (env: Record<string, unknown>) => ImagesBindingLike;`,contextField:`
145
- images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:l("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:c,_=e=>e?{build:`
145
+ images,`,importLines:['import type { Images, ImagesBindingLike } from "@lunora/bindings/images";','import { createImages } from "@lunora/bindings/images";'],stub:l("imagesStub: Images",'throw new Error("ctx.images: no Images binding found. Add an \\`images\\` binding (env.IMAGES) to wrangler.jsonc, or pass \\`images\\` to createShardDO().");',["info","transform"])}:c,O=e=>e?{build:`
146
146
  const sql: SqlClient = config.sql ? config.sql(env) : sqlStub;
147
147
  `,configField:`
148
148
  sql?: (env: Record<string, unknown>) => SqlClient;`,contextField:`
149
- sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:l("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:c,E=e=>e?{build:`
149
+ sql,`,importLines:['import type { SqlClient } from "@lunora/hyperdrive";'],stub:l("sqlStub: SqlClient",'throw new Error("ctx.sql: provide a \\`sql\\` config thunk that builds a SqlClient from your driver, e.g. \\`sql: (env) => fromPostgresJs(postgres(env.HYPERDRIVE.connectionString))\\`.");',["query"])}:c,P=e=>e?{build:`
150
150
  const browser: Browser = config.browser ? config.browser(env) : browserStub;
151
151
  `,configField:`
152
152
  browser?: (env: Record<string, unknown>) => Browser;`,contextField:`
153
- browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:l("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["cancelCrawl","connect","content","crawl","crawlResult","launch","pdf","quickAction","scrape","screenshot","sessions"])}:c,O=e=>e?{build:`
153
+ browser,`,importLines:['import type { Browser } from "@lunora/browser";'],stub:l("browserStub: Browser","throw new Error(\"ctx.browser: provide a \\`browser\\` config thunk, e.g. \\`browser: (env) => createBrowser({ binding: env.BROWSER, launch })\\` with \\`import { launch } from '@cloudflare/playwright'\\`. Session reuse (connect/sessions) additionally needs those two exports passed the same way.\");",["cancelCrawl","connect","content","crawl","crawlResult","launch","pdf","quickAction","scrape","screenshot","sessions"])}:c,q=e=>e?{build:`
154
154
  const r2sqlEnv = env as Record<string, unknown>;
155
155
  const r2sqlAccountId = (r2sqlEnv.R2_SQL_ACCOUNT_ID ?? r2sqlEnv.CLOUDFLARE_ACCOUNT_ID) as string | undefined;
156
156
  const r2sqlToken = r2sqlEnv.R2_SQL_TOKEN as string | undefined;
@@ -161,11 +161,11 @@ const LUNORA_FLAG_KEYS = ${p(e,'ReadonlyArray<{ key: string; type: "boolean" | "
161
161
  ? createR2Sql({ accountId: r2sqlAccountId, apiToken: r2sqlToken, bucket: r2sqlBucket })
162
162
  : r2sqlStub;
163
163
  `,configField:`
164
- r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:l("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:c,P=e=>e?{build:`
164
+ r2sql?: (env: Record<string, unknown>) => R2SqlClient;`,contextField:"",importLines:['import type { R2SqlClient } from "@lunora/bindings/r2sql";','import { createR2Sql } from "@lunora/bindings/r2sql";'],stub:l("r2sqlStub: R2SqlClient",'throw new Error("ctx.r2sql: no R2 SQL credentials found. Set \\`R2_SQL_TOKEN\\`, \\`R2_SQL_ACCOUNT_ID\\` (or \\`CLOUDFLARE_ACCOUNT_ID\\`), and \\`R2_SQL_BUCKET\\` in your env/.dev.vars, or pass an \\`r2sql\\` config thunk to createShardDO().");',["describe","explain","from","query","showDatabases","showTables"],{sync:["from"]})}:c,I=e=>e?{build:`
165
165
  const pipelinesBinding = config.pipelines?.(env) ?? (env as Record<string, unknown>).PIPELINES;
166
166
  const pipelines: PipelineClient = pipelinesBinding ? createPipelines({ binding: pipelinesBinding as PipelineBindingLike }) : pipelinesStub;
167
167
  `,configField:`
168
- pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:l("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:c,q=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(i=>(a(i.exportName,`container export "${i.exportName}"`),a(i.className,`container class "${i.className}"`),`/** Container DO for the \`${i.exportName}\` definition (binding \`${i.bindingName}\`). */
168
+ pipelines?: (env: Record<string, unknown>) => PipelineBindingLike;`,contextField:"",importLines:['import type { PipelineBindingLike, PipelineClient } from "@lunora/bindings/pipelines";','import { createPipelines } from "@lunora/bindings/pipelines";'],stub:l("pipelinesStub: PipelineClient",'throw new Error("ctx.pipelines: no Pipelines binding found. Add a \\`pipelines\\` binding (env.PIPELINES) to wrangler.jsonc, or pass \\`pipelines\\` to createShardDO().");',["send"])}:c,B=(e,t)=>{if(e.length===0)return"";const n=t?`, ${JSON.stringify(t)}`:"",r=e.map(i=>(a(i.exportName,`container export "${i.exportName}"`),a(i.className,`container class "${i.className}"`),`/** Container DO for the \`${i.exportName}\` definition (binding \`${i.bindingName}\`). */
169
169
  export class ${i.className} extends LunoraContainer {
170
170
  public constructor(ctx: ConstructorParameters<typeof LunoraContainer>[0], env: Record<string, unknown>) {
171
171
  super(ctx, env, ${i.exportName}, "${i.exportName}"${n});
@@ -190,7 +190,7 @@ import { ${o} } from "../containers.js";
190
190
 
191
191
  export { ContainerProxy } from "@lunora/container/do";
192
192
 
193
- ${r}`},I=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)a(r.exportName,`container export "${r.exportName}"`),a(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.schedulingPolicy!==void 0||r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
193
+ ${r}`},W=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const r of e)a(r.exportName,`container export "${r.exportName}"`),a(r.bindingName,`container binding "${r.bindingName}"`);const n=e.map(r=>{const o=r.schedulingPolicy!==void 0||r.maxInstances===void 0?"":`, maxInstances: ${String(r.maxInstances)}`;return` { binding: "${r.bindingName}", exportName: "${r.exportName}"${o} },`}).join(`
194
194
  `);return{build:`
195
195
  const containers = createContainerContext(env, LUNORA_CONTAINERS, ${t?JSON.stringify(t):"undefined"}, this.getCurrentTraceparent(), this.getCurrentSampleErrors());
196
196
  `,contextField:`
@@ -199,7 +199,7 @@ ${r}`},I=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],
199
199
  const LUNORA_CONTAINERS: ReadonlyArray<ContainerBindingSpec> = [
200
200
  ${n}
201
201
  ];
202
- `}},B=e=>{if(e.length===0)return"";const t=e.map(r=>(a(r.exportName,`workflow export "${r.exportName}"`),a(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition, reached as \`ctx.exports.${r.className}\`. */
202
+ `}},D=e=>{if(e.length===0)return"";const t=e.map(r=>(a(r.exportName,`workflow export "${r.exportName}"`),a(r.className,`workflow class "${r.className}"`),`/** WorkflowEntrypoint for the \`${r.exportName}\` definition, reached as \`ctx.exports.${r.className}\`. */
203
203
  export class ${r.className} extends LunoraWorkflow<WorkflowParamsOf<typeof ${r.exportName}>, WorkflowOutputOf<typeof ${r.exportName}>> {
204
204
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
205
205
  super(ctx, env, ${r.exportName}, "${r.exportName}");
@@ -227,20 +227,20 @@ type WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params
227
227
  /** Output type carried by a \`defineWorkflow\` definition (its phantom \`__output\`), so each entrypoint keeps the authored return type. */
228
228
  type WorkflowOutputOf<Definition> = Definition extends { __output?: infer Output } ? Output : unknown;
229
229
 
230
- ${t}`},W=e=>{if(e.length===0)return"";const n=e.filter(s=>s.voice).length>0,r=e.map(s=>{a(s.exportName,`agent export "${s.exportName}"`),a(s.className,`agent class "${s.className}"`);const g=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent, reached as \`ctx.exports.${s.className}\`. */
230
+ ${t}`},T=e=>{if(e.length===0)return"";const n=e.filter(s=>s.voice).length>0,r=e.map(s=>{a(s.exportName,`agent export "${s.exportName}"`),a(s.className,`agent class "${s.className}"`);const p=`/** WorkflowEntrypoint for the \`${s.exportName}\` agent, reached as \`ctx.exports.${s.className}\`. */
231
231
  export class ${s.className} extends LunoraWorkflow<AgentRunInput, AgentRunResult> {
232
232
  public constructor(ctx: ConstructorParameters<typeof LunoraWorkflow>[0], env: Record<string, unknown>) {
233
233
  super(ctx, env, compileAgentWorkflow(${s.exportName}, "${s.exportName}"), "${s.exportName}");
234
234
  }
235
235
  }
236
- `;if(!s.voice)return g;const m=s.voiceClassName??"",y=s.voiceBindingName??"";a(m,`agent voice class "${m}"`);const h=`
236
+ `;if(!s.voice)return p;const m=s.voiceClassName??"",y=s.voiceBindingName??"";a(m,`agent voice class "${m}"`);const b=`
237
237
  /** Voice-session Durable Object for the \`${s.exportName}\` agent (binding \`${y}\`). */
238
238
  export class ${m} extends VoiceSessionDO {
239
239
  public constructor(ctx: ConstructorParameters<typeof VoiceSessionDO>[0], env: Record<string, unknown>) {
240
240
  super(ctx, env, ${s.exportName}, "${s.exportName}");
241
241
  }
242
242
  }
243
- `;return`${g}${h}`}).join(`
243
+ `;return`${p}${b}`}).join(`
244
244
  `),o=e.map(s=>s.exportName).join(", ");return`${d}/**
245
245
  * WorkflowEntrypoint classes for the agents declared in \`lunora/agents.ts\`.
246
246
  * Each \`defineAgent\` compiles a replay-safe tool-loop onto a Cloudflare
@@ -255,7 +255,7 @@ import type { AgentRunInput, AgentRunResult } from "@lunora/agent";
255
255
 
256
256
  import { ${o} } from "../agents.js";
257
257
 
258
- ${r}`},D=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)a(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
258
+ ${r}`},j=e=>{const t=e.filter(o=>o.mode==="push");if(t.length===0)return"";for(const o of t)a(o.exportName,`queue export "${o.exportName}"`);const n=t.map(o=>o.exportName).join(", "),r=t.map(o=>` ${JSON.stringify(o.name)}: { binding: ${JSON.stringify(o.bindingName)}, definition: ${o.exportName}, exportName: ${JSON.stringify(o.exportName)} },`).join(`
259
259
  `);return`${d}/**
260
260
  * Push-consumer registry for the queues declared in \`lunora/queues.ts\`. The
261
261
  * composed worker's \`queue(batch, env, ctx)\` entry routes each delivered batch
@@ -270,7 +270,7 @@ import { ${n} } from "../queues.js";
270
270
  export const LUNORA_QUEUE_REGISTRY: QueueRegistry = {
271
271
  ${r}
272
272
  };
273
- `},T=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`workflow export "${n.exportName}"`),a(n.className,`workflow class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}" },`).join(`
273
+ `},U=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`workflow export "${n.exportName}"`),a(n.className,`workflow class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}" },`).join(`
274
274
  `);return{build:`
275
275
  const workflows = createWorkflowContext(env, LUNORA_WORKFLOWS, this.state.exports);
276
276
  `,contextField:`
@@ -279,7 +279,7 @@ ${r}
279
279
  const LUNORA_WORKFLOWS: ReadonlyArray<WorkflowBindingSpec> = [
280
280
  ${t}
281
281
  ];
282
- `}},j=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`queue export "${n.exportName}"`),a(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
282
+ `}},M=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`queue export "${n.exportName}"`),a(n.bindingName,`queue binding "${n.bindingName}"`);const t=e.map(n=>` { binding: "${n.bindingName}", exportName: "${n.exportName}", name: ${JSON.stringify(n.name)} },`).join(`
283
283
  `);return{build:`
284
284
  const queues = createQueueContext(env, LUNORA_QUEUES);
285
285
  `,contextField:`
@@ -288,7 +288,16 @@ ${t}
288
288
  const LUNORA_QUEUES: ReadonlyArray<QueueBindingSpec> = [
289
289
  ${t}
290
290
  ];
291
- `}},U=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`agent export "${n.exportName}"`),a(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
291
+ `}},Q=(e,t)=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};const n=e.map(r=>{a(r.exportName,`topic export "${r.exportName}"`);const o=h(t,r.exportName).map(i=>`{ binding: "${i.bindingName}", exportName: "${i.exportName}" }`).join(", ");return` { exportName: "${r.exportName}", subscriptions: [${o}] },`}).join(`
292
+ `);return{build:`
293
+ const topics = createTopicContext(env, LUNORA_TOPICS);
294
+ `,contextField:`
295
+ topics,`,importLines:['import type { TopicBindingSpec } from "@lunora/queue";','import { createTopicContext } from "@lunora/queue";'],specs:`
296
+ /** Wiring specs for \`ctx.topics\` (codegen-derived from \`lunora/queues.ts\`): each topic's subscription queues. */
297
+ const LUNORA_TOPICS: ReadonlyArray<TopicBindingSpec> = [
298
+ ${n}
299
+ ];
300
+ `}},K=e=>{if(e.length===0)return{build:"",contextField:"",importLines:[],specs:""};for(const n of e)a(n.exportName,`agent export "${n.exportName}"`),a(n.className,`agent class "${n.className}"`);const t=e.map(n=>` { className: "${n.className}", exportName: "${n.exportName}"${n.publicRun===!0?", publicRun: true":""} },`).join(`
292
301
  `);return{build:`
293
302
  const agents = createAgentContext(env, LUNORA_AGENTS, { exports: this.state.exports });
294
303
  `,contextField:`
@@ -299,20 +308,20 @@ ${t}
299
308
  ];
300
309
  `}},f=(e,t,n,r,o)=>({constant:`
301
310
  ${o}
302
- const ${e} = ${p(r,t)};
311
+ const ${e} = ${g(r,t)};
303
312
  `,override:`
304
313
  protected override ${n}(): ${t} {
305
314
  return ${e};
306
315
  }
307
- `}),M=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({className:n.className,exportName:n.exportName,name:n.name}))};return f("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},Q=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name}))};return f("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},K=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
316
+ `}),V=e=>{if(e.length===0)return{constant:"",override:""};const t={workflows:e.map(n=>({className:n.className,exportName:n.exportName,name:n.name}))};return f("LUNORA_WORKFLOWS_INFO","WorkflowsResult","workflowsMetadata",t,"/** Read-only declared-workflow metadata (discovered from `lunora/workflows.ts`) served via `__lunora_admin__:listWorkflows` for the studio's workflows view. */")},H=e=>{if(e.length===0)return{constant:"",override:""};const t={queues:e.map(n=>({binding:n.bindingName,...n.tuning.deadLetterQueue===void 0?{}:{deadLetterQueue:n.tuning.deadLetterQueue},exportName:n.exportName,mode:n.mode,name:n.name,...n.topic===void 0?{}:{topic:n.topic}}))};return f("LUNORA_QUEUES_INFO","QueuesResult","queuesMetadata",t,"/** Read-only declared-queue metadata (discovered from `lunora/queues.ts`) served via `__lunora_admin__:listQueues` for the studio's queues view. */")},G=e=>e?{imports:['import type { LunoraDatabaseLike as LunoraPaymentDbLike, LunoraPayment, PaymentsFromContextOptions } from "@lunora/payment";','import { paymentsFromContext } from "@lunora/payment";'],build:`
308
317
  const payments: LunoraPayment = config.payment
309
318
  ? paymentsFromContext({ auth: { userId: userId ?? null }, db: db as unknown as LunoraPaymentDbLike }, config.payment(env))
310
319
  : paymentStub;
311
320
  `,configField:`
312
321
  payment?: (env: Record<string, unknown>) => PaymentsFromContextOptions;`,contextField:`
313
- payments,`,stub:l("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},V=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
322
+ payments,`,stub:l("paymentStub: LunoraPayment",'throw new Error("ctx.payments: no payment configured. Pass \\`payment\\` to createShardDO().");',["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"],{cast:" as unknown as LunoraPayment",sync:["attach","cancelSubscription","check","createCheckout","createPortalSession","handleWebhook","listBalances","listSubscriptions","track"]})}:{build:"",configField:"",contextField:"",imports:[],stub:""},Y=e=>e?{imports:['import type { X402Pay, X402PayConfig } from "@lunora/x402/pay";','import { lazyX402Pay } from "@lunora/x402/pay";'],build:`
314
323
  const x402: X402Pay = config.x402
315
324
  ? lazyX402Pay(config.x402(env), { getSecret: (name: string) => secrets.get(name) })
316
325
  : x402Stub;
317
326
  `,configField:`
318
- x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:l("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},H=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{q as A,B,D as C,R as a,N as b,F as c,L as d,k as e,$ as f,C as g,_ as h,E as i,O as j,P as k,j as l,I as m,T as n,U as o,K as p,V as q,l as r,M as s,Q as t,w as u,H as v,x as w,A as x,S as y,W as z};
327
+ x402?: (env: Record<string, unknown>) => X402PayConfig;`,stub:l("x402Stub: X402Pay",'throw new Error("ctx.x402: no pay rail configured. Pass \\`x402\\` to createShardDO().");',["fetch"],{cast:" as unknown as X402Pay",sync:["fetch"]})}:{build:"",configField:"",imports:[],stub:""},J=(e,t,n,r,o)=>["AdvisorProcedure","AdvisoryFinding","DatabaseWriterLike","DataMigrationLike","DispatchBookmark","ExportRow",...r?["FlagsResult"]:[],"ImportShardResult","KeyRange","MaskPoliciesResult","MigrationRunResult","QueryReadScope",...n?["QueuesResult"]:[],"RelatedPage","RunShardApplyCdcArgs","RunShardExportArgs","RunShardFindRelatedArgs","RunShardImportArgs","RunShardMigrationArgs","RlsPoliciesResult","RunShardRankBeforeArgs","RunShardRankPageArgs","RunShardWriteArgs","RunShardWriteResult","SchedulerLike",...o?["SearchBackfillProgress"]:[],"TransactionHeadroomTracker","SchemaLike","ShardDOState","ShardRankPageResult","SqlExec","StorageRulesResult","StudioFeaturesResult","SubscriptionIdentity","SystemReaderStorageLike","TelemetrySink",...e?["VectorBackfillProgress"]:[],...t?["WorkflowsResult"]:[],...e?["WriteHook"]:[]];export{T as A,B,D as C,j as D,S as a,L as b,C as c,A as d,R as e,_ as f,E as g,O as h,P as i,q as j,I as k,M as l,Q as m,W as n,U as o,K as p,G as q,l as r,Y as s,V as t,H as u,N as v,J as w,w as x,F as y,$ as z};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.242",
3
+ "version": "1.0.0-alpha.243",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,13 +46,13 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.174",
50
- "@lunora/agent": "1.0.0-alpha.156",
49
+ "@lunora/advisor": "1.0.0-alpha.175",
50
+ "@lunora/agent": "1.0.0-alpha.157",
51
51
  "@lunora/container": "1.0.0-alpha.64",
52
52
  "@lunora/errors": "1.0.0-alpha.48",
53
- "@lunora/platform": "1.0.0-alpha.46",
54
- "@lunora/queue": "1.0.0-alpha.81",
55
- "@lunora/scheduler": "1.0.0-alpha.100",
53
+ "@lunora/platform": "1.0.0-alpha.47",
54
+ "@lunora/queue": "1.0.0-alpha.82",
55
+ "@lunora/scheduler": "1.0.0-alpha.101",
56
56
  "@lunora/values": "1.0.0-alpha.58",
57
57
  "@lunora/workflow": "1.0.0-alpha.69",
58
58
  "jiti": "^2.7.0",
@@ -1 +0,0 @@
1
- import{NODE_CAPABILITIES as f,CLOUDFLARE_CAPABILITIES as h,CELLD_CAPABILITIES as v}from"@lunora/platform";import{readProjectConfigLiterals as m}from"./loadProjectConfig-CKsFNgn3.mjs";const c="cloudflare",b=t=>{const{target:e}=m(t);return e!==void 0&&e.length>0?e:void 0},L=(t,e)=>e??b(t)??c,x=(t,e)=>{if(e!==void 0)return[];const{target:a,unreadable:r}=m(t);return r!==!0||a!==void 0?[]:[{level:"warn",message:`lunora.config declares a \`target\` that codegen cannot read without evaluating it, so the "${c}" surface was emitted. \`runCodegen\` resolves the target synchronously, which means it reads literals only.`,name:"platform_unreadable_target",remediation:`Write \`target\` as a string literal on the config's default export (\`export default { target: "${c}" }\`), or pass \`--target\`.`,target:c}]},u={celld:v,cloudflare:h,node:f},C=()=>Object.keys(u).toSorted((t,e)=>t.localeCompare(e)),w={access:null,ai:"ai",analytics:"analytics",browser:"browser",container:"containers",flags:null,hyperdrive:"hyperdrive",images:"images",kv:"keyValueStore",mail:"mail",notify:null,payments:null,pipelines:"pipelines",r2sql:null,scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows",x402:null},y=["agents","commitOrderedTables","containerEgressPolicy","containerRuntimeScheduling","cronTriggers","crossShardFanout","durableStreams","globalTables","queues","relationGraph","secrets","vectorStore","workerLoaders","workflowRollback","workflowSchedules"],g={agents:"durable agents (`defineAgent`)",commitOrderedTables:"commit-ordered tables (`.commitOrdered()`)",containerEgressPolicy:"container egress policies (`defineContainer({ allowedHosts | deniedHosts | interceptHttps })`)",containerRuntimeScheduling:'per-instance container images and snapshots (`defineContainer({ schedulingPolicy: "durable_object" })`)',cronTriggers:"declared cron triggers (`cronJobs()`)",crossShardFanout:"cross-shard fan-out queries (a `.shardBy(...)` schema)",durableStreams:"durable streams (`.stream(handler, { durable: true })`)",globalTables:"global tables (`.global()`)",queues:"queues (`defineQueue`)",relationGraph:"relation-graph traversal (`ctx.db.related`, derived from `v.id(...)` columns)",secrets:"the secrets store (`ctx.secrets`)",vectorStore:"vector indexes (`.vectorize()`)",workerLoaders:"sandboxed agent scripts (`jsCodeTool`, on Worker Loaders)",workflowRollback:"workflow step rollback (`defineStep({ rollback })`)",workflowSchedules:"scheduled workflow instances (`defineWorkflow({ schedules })`)"},S=(t,e,a)=>({level:"error",message:`${e.name} does not support ${g[t]}, which this app declares.`,name:"platform_unsupported_feature",remediation:`Remove the declaration, or deploy to a target whose capability matrix marks "${t}" as native or emulated.`,target:a}),T=(t,e,a)=>({level:"error",message:`${e.name}'s capability matrix does not declare a support level for ${g[t]}, which this app declares. Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${t}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than letting the app deploy onto a primitive the host may not provide.`,target:a}),k=t=>{const{diagnostics:e,gatedSignals:a,matrix:r,reported:n,signals:d,target:l}=t;for(const s of y){if(d[s]!==!0)continue;const o=r.features[s]?.level;o!=="unsupported"&&o!==void 0||(a[s]=!1,!n.has(s)&&e.push(o==="unsupported"?S(s,r,l):T(s,r,l)))}},_=(t,e,a,r={})=>{const n={...t},d={...r},l=[],s=new Set;for(const[o,i]of Object.entries(w)){if(i===null||!t[o])continue;const p=e.features[i]?.level;p==="unsupported"?(n[o]=!1,s.add(i),l.push({feature:o,level:"error",message:`${e.name} does not support "${o}" (ctx.${o}).`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${o} usage, or deploy to a target whose capability matrix marks "${i}" as native or emulated.`,target:a})):p===void 0&&(n[o]=!1,s.add(i),l.push({feature:o,level:"error",message:`${e.name}'s capability matrix does not declare a support level for "${o}" (ctx.${o}). Treated as unsupported.`,name:"platform_undeclared_feature",remediation:`Rate "${i}" in the ${e.name} capability matrix as "native", "emulated", or "unsupported" — an undeclared feature fails closed rather than shipping a surface the host may not provide.`,target:a}))}return k({diagnostics:l,gatedSignals:d,matrix:e,reported:s,signals:r,target:a}),{diagnostics:l,signals:d,usage:n}},E=(t,e,a={})=>{const r=u[e];return r===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(u).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],signals:{...a},usage:{...t}}:_(t,r,e,a)},I=t=>{const e=u[t];if(e===void 0)return;const a=Object.entries(e.features).filter(([,r])=>r.level==="unsupported").map(([r])=>r).toSorted((r,n)=>r.localeCompare(n));return{id:e.id,name:e.name,unsupported:a}};export{w as CAPABILITY_TO_FEATURE,c as DEFAULT_TARGET,_ as gateAgainstMatrix,E as gatePlatformFeatures,C as platformMatrixIds,b as readProjectTarget,x as readTargetDiagnostics,L as resolveCodegenTarget,I as studioPlatformFor};
@@ -1 +0,0 @@
1
- import{existsSync as g}from"node:fs";import{join as p}from"node:path";import{LunoraError as l}from"@lunora/errors";import{queueDefaultName as f,queueBindingName as y}from"@lunora/queue";import{SyntaxKind as h,Node as s}from"ts-morph";import{diagnosticAt as a}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as m,stringPropertyFor as b}from"./listLunoraSourceFiles-DP-5e-RE.mjs";const q="queues.ts",N=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineQueue";for(const e of t.getDeclarations())if(s.isImportSpecifier(e))return e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue"?!1:e.getNameNode().getText()==="defineQueue";return!1},d=b("queue"),w=(r,t,e)=>{if(s.isNumericLiteral(r))return r.getLiteralValue();throw a(r,`queue "${t}": \`${e}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},E=(r,t)=>{const e=m(r,"name");if(!e||!s.isPropertyAssignment(e))return;const n=d(e.getInitializerOrThrow(),t,"name");if(n.length===0)throw a(e,`queue "${t}": \`name\` must be a non-empty string when provided`);return n},P=(r,t)=>{const e=r.getArguments()[0];if(!e||!s.isObjectLiteralExpression(e))throw a(r,`queue "${t}": defineQueue must be passed an inline object literal`);const n={bindingName:y(t),exportName:t,mode:"push",name:E(e,t)??f(t),tuning:{}},i=m(e,"mode");if(i&&s.isPropertyAssignment(i)){const o=d(i.getInitializerOrThrow(),t,"mode");if(o!=="push"&&o!=="pull")throw a(i,`queue "${t}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(o)})`);n.mode=o}const u=m(e,"deadLetterQueue");u&&s.isPropertyAssignment(u)&&(n.tuning.deadLetterQueue=d(u.getInitializerOrThrow(),t,"deadLetterQueue"));for(const o of["maxBatchSize","maxBatchTimeout","maxRetries","retryDelay"]){const c=m(e,o);c&&s.isPropertyAssignment(c)&&(n.tuning[o]=w(c.getInitializerOrThrow(),t,o))}return n},I=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const n=e.getInitializer();if(n?.getKind()!==h.CallExpression)continue;const i=n,u=i.getExpression();if(!s.isIdentifier(u)||!N(u))continue;const o=e.getNameNode();if(!s.isIdentifier(o))throw a(o,"defineQueue exports must be plain named exports (no destructuring)");t.push(P(i,o.getText()))}return t},Q=r=>{const t=new Map,e=new Map;for(const n of r){const i=t.get(n.name);if(i!==void 0)throw new l("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${n.name}": produced by both "${i}" and "${n.exportName}". Deployed queue names must be unique across the project.`,{status:500});t.set(n.name,n.exportName);const u=e.get(n.bindingName);if(u!==void 0)throw new l("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${n.bindingName}": produced by both "${u}" and "${n.exportName}". Queue export names must yield unique binding names.`,{status:500});e.set(n.bindingName,n.exportName)}},U=(r,t)=>{const e=p(t,q);if(!g(e))return[];const n=r.getSourceFile(e)??r.addSourceFileAtPath(e),i=I(n);return i.sort((u,o)=>u.exportName.localeCompare(o.exportName)),Q(i),i};export{q as QUEUES_FILENAME,U as discoverQueues};
@@ -1,9 +0,0 @@
1
- import{existsSync as w,mkdirSync as Ds,readFileSync as $t,writeFileSync as ks,rmSync as Ms}from"node:fs";import{join as S,dirname as ae}from"node:path";import{performance as we}from"node:perf_hooks";import{runAdvisor as Ks}from"@lunora/advisor";import{LunoraError as $}from"@lunora/errors";import{SyntaxKind as l,Node as i,VariableDeclarationKind as _s,Project as dt}from"ts-morph";import{serializeSchemaSnapshot as zs}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as $s}from"./formatAdvisories-DwmUKYuc.mjs";import{readProjectConfigLiterals as Us}from"./loadProjectConfig-CKsFNgn3.mjs";import{s as Bs}from"./paths-C-9fwEgQ.mjs";import{C as ce}from"./capabilities-DJJWVEtk.mjs";import{isD1GlobalTable as Ut,isHyperdriveGlobalTable as Bt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as js}from"./AGENTS_FILENAME-Bb2jxbOa.mjs";import{discoverContainers as qs}from"./CONTAINERS_FILENAME-CGB4bqUr.mjs";import Vs from"./discoverCrons-0lNudk0S.mjs";import{diagnosticAt as ee}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as pe}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,bindingKeyName as Q,propertyKeyName as y,unwrapExpression as X,listSecurityScanFiles as me,objectLiteralFromCallbackBody as jt,propertyInitializer as N,lunoraRelativePath as x,collectCallRows as F,findObjectProperty as C,collectSecurityCallRows as Ws,limitNameOf as qt,optionsObjectLiteral as Vt,isContextIdentifier as Fe,handlerOf as Hs,isDatabaseAccessor as _,readTargetOf as Wt,enclosingExportName as Gs}from"./listLunoraSourceFiles-DP-5e-RE.mjs";import Ys from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as Qs}from"./QUEUES_FILENAME-CxkPcMH1.mjs";import{discoverSandboxUsage as Xs}from"./discoverSandboxUsage-CrjZ6yNg.mjs";import Zs from"./discoverStorageRulesMetadata-D8VYflWt.mjs";import{a as b,c as z,d as Ht,e as Js}from"./classify-procedure-call-BztLe76A.mjs";import{discoverWorkflows as en}from"./WORKFLOWS_FILENAME-DNaUHGS8.mjs";import{i as tn}from"./ir-BgM8A3XV.mjs";import{gatePlatformFeatures as sn,resolveCodegenTarget as Gt,readTargetDiagnostics as nn,studioPlatformFor as rn}from"./DEFAULT_TARGET-B1zgC6k6.mjs";import{b as Yt,e as on}from"./shard-CCNl561P.mjs";import an from"./emitServer-B8t7Hzb1.mjs";import{emitDataModel as cn}from"./emitDataModel-D3WuEZ4b.mjs";import{i as k,a as U,e as A,r as ln,b as un,s as he,c as dn,f as fn,d as gn}from"./queries-B-f4jO-x.mjs";import{r as ve,s as pn}from"./parse-validator-C94Yiabo.mjs";import mn from"./discoverAuthApiCalls-FxrdBeVt.mjs";import{i as hn,a as vn,e as xn,b as En,d as Sn,c as yn}from"./unwrap-handler-return-CoV_GK33.mjs";import An from"./discoverFunctions-BsmX-sEq.mjs";import bn from"./discoverHttpRoutes-BcXI9CNt.mjs";import Nn from"./discoverHyperdriveCalls-D9qXqTq3.mjs";import Pn from"./discoverInserts-CFJ3IVeI.mjs";import{m as Me,a as ue,s as Qt,d as wn}from"./index-BoaHhVtM.mjs";import{e as Xt}from"./exported-procedure-chains-CmCDiPBV.mjs";import In from"./discoverMigrations-DbrHwcGE.mjs";import{MUTATORS_FILENAME as Tn,isDefineMutatorCallee as Cn,discoverMutators as Fn}from"./MUTATORS_FILENAME-B6cKrN_m.mjs";import On from"./discoverNondeterministicCalls-CSQ_GDcA.mjs";import{discoverNotifyConfig as Rn,discoverNotifyCalls as Ln}from"./NOTIFY_FILENAME-Cri3NT5U.mjs";import Dn from"./discoverR2sqlCalls-fu7fC0i_.mjs";import kn from"./discoverRlsProcedures-BO4qC77y.mjs";import Mn from"./discoverRlsMetadata-CPmAGL0W.mjs";import Kn from"./discoverSchema-D8DBDHEg.mjs";import{secretKindOf as _n,redact as zn,isHeuristicSecretKind as $n,isSecretishName as Un}from"./redact-Cy14LEnc.mjs";import{discoverShapes as Bn}from"./SHAPES_FILENAME-zJgzynXR.mjs";import{emitApp as jn}from"./emitApp--W9G6MZd.mjs";import{buildOpenApiDocument as qn,emitOpenApiModule as Vn}from"./buildOpenApiDocument-nYvBhjxu.mjs";import{buildOpenRpcDocument as Wn,emitOpenRpcModule as Hn}from"./OPENRPC_VERSION-Cl6P9WGv.mjs";import{buildSchemaSnapshot as Gn}from"./SchemaSnapshotParseError-CPOXlFhI.mjs";import{emitCollections as Yn,emitSeed as Qn,emitApi as Xn}from"./emitApi-DdW9RyGG.mjs";import{A as Zn,B as Jn,z as er,C as tr}from"./shard-runtime-B7xvdFPc.mjs";import{emitCrons as sr,emitScheduler as nr,emitShardRegistry as rr,emitVectors as or,emitWranglerCronTriggers as ir}from"./emitCrons-Bop1FTEz.mjs";import ar from"./emitDrizzleSchema-Cv0HtLR3.mjs";import cr from"./emitFunctions-BgNeOZt_.mjs";const ft={error:"ERROR",info:"INFO",warn:"WARN"},gt={ERROR:2,INFO:0,WARN:1},lr=e=>({cacheKey:"advisor_min_severity_invalid",categories:["SCHEMA"],description:"`advisor.minSeverity` in `lunora.config.*` sets the lowest advisory level codegen reports and writes into `_generated/shard.ts`. Codegen reads it by parsing the file, so it has to be a string literal.",detail:e,facing:"INTERNAL",level:"WARN",metadata:{},name:"advisor_min_severity_invalid",remediation:'Set `advisor: { minSeverity: "info" | "warn" | "error" }` as a literal on the config\'s default export.',title:"`advisor.minSeverity` is not a level codegen can read, so every advisory was reported"}),ur=(e,t)=>{const{advisor:s}=Us(e);if(s===void 0||s.minSeverity===void 0&&s.unreadable!==!0)return[...t];const{minSeverity:n}=s,o=n!==void 0&&Object.hasOwn(ft,n)?ft[n]:void 0;return o===void 0?[...t,lr(n===void 0?"`advisor.minSeverity` is not a string literal codegen can read without evaluating the config: a computed value or key, or a spread that could set or override it.":`\`advisor.minSeverity\` is "${n}", which is not one of "info", "warn" or "error".`)]:t.filter(r=>gt[r.level]>=gt[o])},pt=(e,t="api")=>{const s=new Map;for(const n of e){const o=Bs(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 $("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})}}},dr=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>Ut(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>Bt(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ce)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},fr=(e,t,s={})=>{if(t===void 0)return;const n=dr(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 $("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.`)},gr="env.ts",pr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},mr=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&&pe(n.getModuleSpecifierValue())}return!1},hr=e=>{if(i.isIdentifier(e))return pr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&mr(t)}return!1},vr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!hr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ee(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},xr=(e,t)=>{const s=S(t,gr);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=vr(n);if(o.length!==0){if(o.length>1)throw ee(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},mt="ctx",Zt=e=>{const t=new Set,s=new Set([mt]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=Q(a);c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if(Q(r)!==mt)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},Er=(e,t)=>{const s=Object.fromEntries(ce.map(n=>[n.key,!1]));for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Zt(o);for(const c of ce)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(ce.every(c=>s[c.key]))break}return s},Jt="identity.ts",Sr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return pe(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},yr=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&&pe(n.getModuleSpecifierValue())}return!1},Ar=e=>{if(i.isIdentifier(e))return Sr(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&yr(t)}return!1},br=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Ar(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ee(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Nr=(e,t)=>{const s=S(t,Jt);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=br(n);if(o.length!==0){if(o.length>1)throw ee(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},Pr=new Set(["allowedHosts","deniedHosts","interceptHttps"]),wr=(e,t)=>{const s=X(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return X(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},Ir=(e,t)=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(s=>{if(i.isShorthandPropertyAssignment(s))return t.has(y(s));if(!i.isPropertyAssignment(s)||!t.has(y(s)))return!1;const n=X(s.getInitializer())?.getText();return n!=="false"&&n!=="undefined"}),Tr=new Set(["durable"]),Cr=new Set(["rollback"]),Fr=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)?t.getName():t.getText()},Or=new Map([["defineContainer",{keys:Pr,signal:"containerEgressPolicy"}],["defineStep",{keys:Cr,signal:"workflowRollback"}],["stream",{keys:Tr,signal:"durableStreams"}]]),Rr=(e,t)=>{const s=Or.get(Fr(t));if(s!==void 0)return t.getArguments().some(n=>Ir(wr(e,n),s.keys))?s.signal:void 0},Lr=(e,t)=>{const s={containerEgressPolicy:!1,durableStreams:!1,secrets:!1,workflowRollback:!1};for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.secrets||(s.secrets=Zt(o).has("secrets"));for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=Rr(o,r);a!==void 0&&(s[a]=!0)}if(Object.values(s).every(Boolean))break}return s},Dr="createWorker",kr="extend",ht=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,vt=e=>{const t=[],s=ht(N(e,"backupCron"));s!==void 0&&t.push(s);const n=N(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=ht(o.getNameNode());r!==void 0&&t.push(r)}return t},Mr=e=>{const t=b(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===Dr)return i.isObjectLiteralExpression(s)?vt(s):[];if(t!==kr||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=jt(s.getBody());return n===void 0?[]:vt(n)},Kr=(e,t)=>{const s=[];for(const{filePath:n}of me(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...Mr(r))}return[...new Set(s)]},es=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:es(e.inner)},_r=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=es(n);return o!==void 0&&t.has(o)}))},zr=(e,t)=>{const s=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const r=s.get(o.name);if(r!==void 0)throw new $("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${r} and agent "${o.exportName}". Workflow and agent names share one account-wide namespace and must be unique together.`,{status:500});const a=n.get(o.className);if(a!==void 0)throw new $("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${a} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},$r=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=Nr(s,t),a=xr(s,t),c=en(s,t),u=Qs(s,t),d=js(s,t);zr(c,d);const m=qs(s,t),h=Zs(s,t),R=Vs(s,t,c,d),M=Kr(s,t),g=Lr(s,t),I=Xs(s,t),P=Er(s,t);P.browser=P.browser||I.usesSandboxBrowser;const O=sn(P,Gt(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(E=>E.commitOrdered===!0),cronTriggers:R.length>0,crossShardFanout:o.tables.some(E=>tn(E)),containerEgressPolicy:g.containerEgressPolicy,containerRuntimeScheduling:m.some(E=>E.schedulingPolicy==="durable_object"),durableStreams:g.durableStreams,globalTables:o.tables.some(E=>E.shardMode==="global"),queues:u.length>0,relationGraph:_r(o),secrets:g.secrets,vectorStore:o.vectorIndexes.length>0,workerLoaders:I.usesSandboxLoader,workflowRollback:g.workflowRollback,workflowSchedules:c.some(E=>E.schedules!==void 0)}),v=O.usage,D=O.signals.vectorStore!==!1,B=Ys(n),H=B??new Set,te=H.has("lunorash");fr(o,B,{hasVectors:D,scheduler:v.scheduler||R.length>0,storage:v.storage||h.rules.length>0||Object.keys(Yt(o)).length>0,usage:v});const K=w(S(t,"flags.ts")),L=w(S(t,"notify.ts"));return{agents:d,containers:m,crons:R,dataModelContent:cn(o),declaredDependencies:B,dependencies:H,entryCronTriggers:M,env:a,featureUsage:v,hasFlags:K,hasNotify:L,identity:r,platformGate:{...O,diagnostics:[...nn(n,e.target),...O.diagnostics]},queues:u,serverContent:an({agents:d,containers:m,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:v.browser,hasVectors:D,hasFlags:K,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:L,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:r,queues:u,schema:o,storageRuleBuckets:h.rules.map(E=>E.bucket),useUmbrella:te,workflows:c}),storageRulesMetadata:h,usesSandbox:I.usesSandboxBrowser||I.usesSandboxContainer||I.usesSandboxFs,useUmbrella:te,workflows:c}},ts=new Set(["delete","get","head","options","patch","post","put"]),Ur=new Set(["handler","stream"]),Br=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,xt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),jr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ts.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()}},qr=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)||ts.has(n.getName()))break;s=n.getExpression()}return jr(s)},Vr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(xt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&xt.has(s.getText()))return!0}return!1},Wr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!Ur.has(n.getName()))return;const o=qr(s);if(!o||!Br.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&Vr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Hr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Wr(o,t);r&&s.push(r)}return s},Gr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Hr(o,x(t,n)))}return s},Yr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Qr=(e,t)=>{if(!Yr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!k(s)||U(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},Xr=(e,t)=>F(e,t,Qr),Zr=new Set(["generateText","streamText"]),Jr=new Set(["messages","prompt","system"]),eo=[{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"]}],to=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of eo)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},so=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=to(t);if(s!==void 0)return s}},no=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=Q(r),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},ro=e=>{if(ln(e))return!0;const t=no(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},oo=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Jr.has(y(t)))continue;const s=t.getInitializer();if(s!==void 0&&ro(s))return!0}return!1},io=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=b(n.getExpression());if(o===void 0||!Zr.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(b(c.getExpression())==="tool"&&(a=so(c),a!==void 0))break;a!==void 0&&s.push({exportName:A(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:oo(r)})}return s},ao=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...io(o,x(t,n)))}return s},co=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},lo=(e,t)=>{if(!co(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!k(s)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},uo=(e,t)=>F(e,t,lo),Ke=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=ve(s.getExpression());return n===void 0||Ke(n,t)})}finally{t.delete(e)}},fo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=C(t,"args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:ve(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:Ke(o)}},go=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?ve(r):void 0;a===void 0?s=!0:(t.push(a),s||=Ke(a))}n=o.getExpression()}return{objects:t,opaque:s}},_e=(e,t)=>t?go(t):fo(e),ss=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=ve(s.getExpression());return n===void 0?[]:ss(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[y(s)]:[]})}finally{t.delete(e)}},po=e=>e.flatMap(t=>ss(t,new Set)),mo=new Set(["check","length","max"]),Oe=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},ho=e=>[e,...e.getDescendants()].filter(t=>Oe(t)!==void 0),vo=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(mo.has(s.getName()))return!0;t=n}},xo=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=ho(r),c=y(o);a.some(u=>Oe(u)==="any")?t.push(c):a.some(u=>Oe(u)==="string"&&!vo(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Eo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:o}=_e(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=xo(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},So=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Eo(o,t);r&&s.push(r)}return s},yo=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...So(o,x(t,n)))}return s},Ie=e=>e?.getKind()===l.TrueKeyword,Ao=e=>e?.getKind()===l.FalseKeyword,bo=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,No=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Po=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&b(t.getExpression())==="scim"),wo=e=>e!==void 0&&i.isCallExpression(e)&&No.has(b(e.getExpression())??""),Io=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),To=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:Ie(N(t,"disableCSRFCheck")),emailPasswordEnabled:Ie(N(s,"enabled")),requireEmailVerification:Ie(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Po(N(e,"plugins"))&&wo(N(e,"database")),secureCookiesDisabled:Ao(N(t,"useSecureCookies")),sessionFreshAgeZero:bo(N(n,"freshAge")),trustedOriginsWildcard:Io(N(e,"trustedOrigins"))}},Co=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Fo=(e,t)=>{if(b(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?To(s):Co();return{exportName:A(e),file:t,line:e.getStartLineNumber(),...o}},Oo=(e,t)=>Ws(e,t,Fo),Ro=(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},Lo=(e,t,s)=>{const n=Ro(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!k(o)||U(o))&&!(s.requireUnmodifiedReach===!0&&!un(o)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:n}},Do=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=Lo(o,t,s);r&&n.push(r)}return n},xe=(e,t,s)=>{const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Do(r,x(t,o),s))}return n},ko=new Set(["content","pdf","scrape","screenshot"]),Mo=(e,t)=>xe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ko}),Ko=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),_o=new Set(["RateLimiter"]),zo=new Set(["extend"]),Et="lunora",$o=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ns=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=y(o);t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(y(o))}return{analyzable:!n,presentKeys:t,trueKeys:s}},Re=e=>e&&i.isObjectLiteralExpression(e)?ns(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Uo=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&jt(t.getBody());return s?ns(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Bo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=b(n.getExpression());o!==void 0&&(Ko.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Re(n.getArguments()[0])}):zo.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...Uo(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=b(n.getExpression());o===void 0||!_o.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Re(n.getArguments()[0])})}return s},jo=(e,t)=>{for(const s of $o){const n=S(t,s);if(!w(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))b(a.getExpression())===Et&&r.push({callee:Et,file:s,line:a.getStartLineNumber(),...Re(a.getArguments()[0])});return r}return[]},qo=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of me(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...Bo(r,n))}return s.push(...jo(e,ae(t))),s},St="ctx.containers.",Vo=e=>{if(!e.startsWith(St))return!1;const t=e.slice(St.length);return t.length>0&&!t.includes(".")},Wo=(e,t)=>xe(e,t,{argIndex:0,matchReceiver:Vo,methods:new Set(["get"])}),Ho=new Set(["allow","deny","setAllowed"]),Go=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=C(t,"enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Yo=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Go(e)))return{detail:"enableInternet: true",exportName:A(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Qo=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!Ho.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:A(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Xo=(e,t)=>Yo(e,t)??Qo(e,t),Zo=(e,t)=>F(e,t,Xo),Jo=new Set(["defineExportSink","r2Sink","webhookExportSink"]),ei=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Jo.has(s)?s:void 0},ti=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=y(n);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(y(n))}return{analyzable:!0,emptyKeys:s,presentKeys:t}},si=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of me(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=ei(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?ti(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},ni=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ri=new Set(["dbRateLimit","rateLimit"]),oi=e=>{const t=Vt(e);if(!t)return!1;const s=C(t,"failOpen");return s!==void 0&&i.isPropertyAssignment(s)&&s.getInitializer()?.getKind()===l.TrueKeyword},ii=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const n=ni.get(s);if(n!==void 0)return{callee:s,exportName:A(e),failOpen:oi(e.getArguments()[n]),file:t,limitName:ri.has(s)?qt(e):"",line:e.getStartLineNumber()}},ai=(e,t)=>F(e,t,ii),ci=new Set(["boolean","number","object","string"]),li=e=>{const t=e.getName();if(!ci.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Fe(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Fe(n.getExpression()))return t},ui=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=li(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},di=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=ui(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))},fi=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=Hs(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},yt=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},gi=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=yt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=yt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},pi=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=gi(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},mi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=fi(o);r&&s.push(...pi(r,t))}return s},hi=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...mi(o,x(t,n)))}return s},vi=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Fe(t.getExpression())},xi=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Ei=(e,t)=>{if(!vi(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=xi(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:A(e),file:t,key:o,line:e.getStartLineNumber()}},Si=(e,t)=>F(e,t,Ei),yi=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||hn(r))return;const a=e.getSourceFile().getFilePath();if(vn(o,e,a)){const c=xn(o,e,a,0,new Set);return c===void 0&&En(r),c}return r},Ai=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},bi=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Ni=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))Ai(a)&&s.push({file:r,indexName:bi(a),line:a.getStartLineNumber()})}return s},Z=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,rs=e=>{const t=e.getArguments()[0],s=Z(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=C(t,"handler");return n!==void 0&&i.isPropertyAssignment(n)?Z(n.getInitializer()):void 0},Pi=new Set(["delete","get","head","options","patch","post","put"]),wi=new Set(["handler","stream"]),Ii=new Set(["runAction","runMutation"]),Ti=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),J=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,os=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if(Q(s)===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},At=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:os(s,"ctx")},bt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:os(s,"request")},Nt=(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(Ii.has(a)&&J(c,t))return a;if(Ti.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&J(c.getExpression(),t))return`db.${a}`}},Pt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&J(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!J(n.getInitializer(),t))){for(const r of o.getElements())if(Q(r)==="auth")return!0}}return!1},Ci=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,Fi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&J(n.getExpression(),t)},Oi=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],is=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:Oi(s)},Ri=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?is(t,a.getText()):[]}return[]},Li=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=is(s,t.getText());return n.length>0?n:Ri(t,s)},wt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>Fi(o,t)&&Li(o).some(r=>Ci.test(r)))},Di=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!wi.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(Pi.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},ki=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=Z(e.getArguments()[0]),u=c&&At(c,!0);if(!c||u===void 0||wt(c,bt(c,!0)))return;const d=Nt(c,u);return d===void 0?void 0:{exportName:A(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Pt(c,u),sideEffect:d}}const n=Di(e);if(n===void 0)return;const o=Z(e.getArguments()[0]),r=o&&At(o,!1);if(!o||r===void 0||wt(o,bt(o,!1)))return;const a=Nt(o,r);return a===void 0?void 0:{exportName:A(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Pt(o,r),sideEffect:a}},Mi=(e,t)=>F(e,t,ki),Ki=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),_i=new Set(["append","set"]),as=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",It=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Ki.has(b(n.getExpression())??"")&&fn(n,t)),zi=(e,t)=>{if(It(e,t))return!0;const s=he(e);return s!==void 0&&It(s,t)},Le=(e,t)=>dn(e,t)&&!zi(e,t),$i=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=he(e);return t!==void 0&&i.isNewExpression(t)&&b(t.getExpression())==="Headers"},de=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=he(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},ze=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Le(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:as(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Le(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:y(n),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=de(n.getExpression());o!==void 0&&ze(o,t,s)}},cs=(e,t)=>{const s=de(e);if(s===void 0)return;const n=C(s,"headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=de(n.getInitializer());o!==void 0&&ze(o,"response-init",t)},Ui=(e,t)=>{const s=b(e.getExpression());if(s==="Response")cs(e.getArguments()[1],t);else if(s==="Headers"){const n=de(e.getArguments()[0]);n!==void 0&&ze(n,"headers-ctor",t)}},Bi=(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"){cs(e.getArguments()[1],t);return}if(_i.has(n)&&$i(o)){const r=e.getArguments()[1];r!==void 0&&Le(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:as(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},ji=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ui(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Bi(s,t)},qi=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Z(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 ji(n,{exportName:A(e),relativePath:t,requestName:r.getText(),rows:a}),a},Vi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...qi(n,t));return s},Wi=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Vi(o,x(t,n)))}return s},Hi=new Set(["auth","context.auth","ctx.auth"]),Gi="userId",Yi=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(y(s))}return t},Qi=(e,t)=>{const s=S(t,Jt);if(!w(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(b(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Yi(r):void 0}},Tt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Hi.has(e.getExpression().getText())?e:void 0},Xi=e=>{if(i.isPropertyAccessExpression(e)&&Tt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Tt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Zi=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=Xi(o);r!==void 0&&n.push({declared:r===Gi||s.has(r),exportName:A(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Ji=(e,t)=>{const s=Qi(e,t);if(s===void 0)return[];const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Zi(r,x(t,o),s))}return n},ea=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!k(n)||U(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber()}},ta=(e,t)=>F(e,t,ea),sa=e=>{if(i.isComputedPropertyName(e)){const t=e.getExpression();return i.isStringLiteral(t)||i.isNoSubstitutionTemplateLiteral(t)?t.getLiteralValue():void 0}return i.isStringLiteral(e)?e.getLiteralValue():e.getText()},na=e=>e.getProperties().some(t=>{if(i.isSpreadAssignment(t))return!0;const s=sa(t.getNameNode());return s===void 0||s==="namespace"}),ra=(e,t)=>{for(const{filePath:s}of me(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){const r=o.getExpression(),[a]=o.getArguments();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="auth"||a===void 0)&&(!i.isObjectLiteralExpression(a)||na(a)))return o}}},oa="https://lunora.sh/docs/concepts/data-residency#pinning-auth-and-voice",ia=(e,t)=>{if(!(e.jurisdiction===void 0||e.jurisdictionPinsAuth===!0||t===void 0))throw ee(t,`the schema pins Durable Objects to the "${e.jurisdiction}" jurisdiction, and this project also has DO-backed auth (users, sessions, accounts, credentials). Pinning the auth object resolves it to a NEW, EMPTY object: existing users stay in the unpinned one until you copy them across (${oa}). Acknowledge with \`.jurisdiction("${e.jurisdiction}", { pinAuth: true })\`, deploy, then run the copy. For D1-mode auth the acknowledgement changes nothing.`,{code:"JURISDICTION_MOVE",status:422})},aa=new Set(["delete","get","getRaw","getWithMetadata","put"]),ca=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return xe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:aa}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},la=new Set(["queue","send"]),Ct=new Set(["bcc","cc","to"]),ua=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!la.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},da=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return Ct.has(y(t))&&k(n)&&!U(n)}if(!i.isPropertyAssignment(t)||!Ct.has(y(t)))return!1;const s=t.getInitializer();return s!==void 0&&k(s)&&!U(s)}):!1,fa=(e,t)=>{const s=ua(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!da(n)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},ga=(e,t)=>F(e,t,fa),pa=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,ma=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?pa(e):!0,ls=(e,t=!1)=>{for(const s of e.getProperties()){if(ma(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||ls(n,!0))return!0}return!1},ha=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Xt(n))for(const r of Me(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||ls(a)))return!0}}return!1},va=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=ue(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=ue(a);c!==void 0&&s.push({column:c,strategy:Qt(a),table:o})}}return s},xa=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Xt(o))for(const a of Me(r))for(const c of va(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Ea=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=ue(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=ue(u);if(d===void 0)continue;const m=Qt(u);m!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:m,table:a})}}return o},Sa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?z(s):void 0;return n?.receiver?Me(n.receiver).flatMap(o=>Ea(o,e.getName(),t)):[]},ya=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sa(c,r))}return s},Aa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return _(s)},ba=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=C(t,"server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},Na=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Cn(s.getExpression())?s:void 0},Pa=e=>{const t=Na(e),s=t===void 0?void 0:ba(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Aa(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},wa=e=>e.getVariableDeclarations().flatMap(t=>Pa(t)),Ia=(e,t)=>{const s=S(t,Tn);if(!w(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return wa(n)},Ta=new Set(["delete","get","patch"]),Ca=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Fa=new Set(["auth","identity","session","user"]),Oa=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Ra=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!_(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},La=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},Da=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),ka=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Ma=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Da(s.getExpression(),t)&&ka(s.getThenStatement())),Ka=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!Ta.has(o))continue;const r=n.getExpression();if(!(_(r)||i.isPropertyAccessExpression(r)&&_(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},_a=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},za=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>_a(s)==="ctx")),$a=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Oa.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Ua=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Ca.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Fa.has(t.getName()))return!0}return za(e)||$a(e)},Ba=(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=rs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Ht(n.receiver,"use","rls"),a=Ua(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const m=Ra(d);if(m===void 0)continue;const h=La(d);if(h===void 0||c.has(h)||!Ma(o,h))continue;const R=Ka(o,h);R!==void 0&&(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:m,usesRls:r,visibility:n.visibility}))}return u},ja=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ba(c,r))}return s},qa=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Va=new Set(["insert","insertManyUnsafe","patch","replace"]),Wa=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Va.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},Ha=(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},Ft=(e,t)=>{if(i.isPropertyAccessExpression(e)){const s=e.getExpression();return i.isIdentifier(s)&&s.getText()==="args"&&e.getName()===t}if(i.isElementAccessExpression(e)){const s=e.getExpression(),n=e.getArgumentExpression();return i.isIdentifier(s)&&s.getText()==="args"&&n!==void 0&&i.isStringLiteral(n)&&n.getLiteralValue()===t}return!1},Ga=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;for(const a of s.getDescendantsOfKind(l.BinaryExpression)){const c=a.getLeft();if(i.isIdentifier(c)&&c.getText()===t&&a.getOperatorToken().getText().endsWith("="))return}const n=e.getStart();let o,r=-1;for(const a of s.getDescendantsOfKind(l.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getParent();if(!i.isVariableDeclarationList(c)||c.getDeclarationKind()!==_s.Const)continue;const u=a.getInitializer(),d=a.getStart();u!==void 0&&d<n&&d>r&&(o=u,r=d)}return o},Ya=(e,t)=>{if(Ft(e,t))return!0;const s=Ga(e);return s!==void 0&&Ft(s,t)},Qa=(e,t,s,n,o)=>{const r=[];for(const a of e.getProperties()){let c,u;if(i.isPropertyAssignment(a)?(c=y(a),u=a.getInitializer()):i.isShorthandPropertyAssignment(a)&&(c=y(a),u=a.getNameNode()),!(c===void 0||u===void 0||!qa.has(c))&&k(u)&&!U(u)){const d=A(s),m=o(d)===c&&Ya(u,c);r.push({exportName:d,field:c,file:n,line:s.getStartLineNumber(),method:t,...m&&{ownerScoped:!0}})}}return r},Xa=(e,t,s)=>{const n=Wa(e.getExpression());if(n===void 0)return[];const o=e.getArguments()[1];return o?Ha(o,n).flatMap(r=>Qa(r,n,e,t,s)):[]},Za=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of Xa(o,t,a=>s(a).owner)){const{visibility:a}=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Ja=(e,t,s=[],n=[])=>{const o=[],r=new Map;for(const a of s)r.set(`${a.filePath}:${a.exportName}`,{visibility:a.visibility});for(const a of n){const c=`${a.filePath}:${a.exportName}`;r.set(c,{...r.get(c),owner:a.owner})}for(const a of p(t)){const c=e.getSourceFile(a)??e.addSourceFileAtPath(a),u=x(t,a);o.push(...Za(c,u,d=>r.get(`${u}:${d}`)??{}))}return o},ec=["providerSubscriptionId","state"],tc=["providerEventId","processedAt"],Ot=(e,t)=>t.every(s=>s in e.shape),sc=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Ot(t,ec)&&Ot(s,tc)},nc=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),rc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,oc=e=>{const t=C(e,"webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?rc(t.getInitializer()):void 0},ic=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!nc.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?oc(n):void 0;return{callee:s,exportName:A(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},ac=(e,t)=>F(e,t,ic),cc=new Set(["defineQueue","defineWorkflow"]),lc=new Set(["run","runAction","runMutation","runQuery"]),uc=new Set(["api","internal"]),dc=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},fc=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=C(t,"handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},us=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},ds=(e,t)=>e===t||e.startsWith(`${t}.`),fs=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Rt=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)},gs=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Rt(s));return i.isIdentifier(e)&&Rt(e)&&t.push(e),t},gc=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},pc=e=>{const t=us(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},mc=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:pc(e),o=new Set,r=a=>fs(a).some(c=>n.some(u=>ds(c.getText(),u)))?!0:gs(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 gc(a))o.add(u)}return{names:o,prefixes:n}},hc=(e,t)=>fs(e).some(s=>t.prefixes.some(n=>ds(s.getText(),n)))?!0:gs(e).some(s=>t.names.has(s.getText())),vc=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)||!uc.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},xc=(e,t,s)=>{const n=us(e,0);if(n===void 0)return[];const o=mc(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!lc.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!hc(u,o))continue;const d=vc(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:A(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},Ec=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=dc(n);if(o===void 0||!cc.has(o))continue;const r=fc(n);r!==void 0&&s.push(...xc(r,o==="defineQueue"?"queue":"workflow",t))}return s},Sc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ec(o,x(t,n)))}return s},Lt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Dt=new Set(["account","credential","member","passkey","session","user"]),yc=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Ac=e=>{const s=yc(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Dt.has(s)||Dt.has(n)},bc=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Nc=(e,t)=>{const{objects:s,opaque:n}=_e(e,t);return po(s).some(o=>bc(o))?!0:n?void 0:!1},Pc=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!C(t,"captcha"),usesRateLimit:!!C(t,"rateLimit")}},wc=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},le={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Ic=e=>{const t=wc(e),s=t?b(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Pc(t);return{...le,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Lt?{...le,[Lt[s]]:!0}:le},Tc=e=>{const t={...le};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=Ic(o);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Cc=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Fc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Cc.has(t.getName()))return!1;const s=t.getExpression();if(!_(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:Ac(o.getLiteralText())},Oc=new Set(["create","runAfter","runAt","send","sendBatch"]),Rc=new Set(["queues","scheduler","workflows"]),Lc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Oc.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Rc.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},Dc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return _(s)},ps=new Set(["generateObject","generateText","streamObject","streamText"]),kc=e=>{const t=b(e.getExpression());return t!==void 0&&ps.has(t)},Mc=e=>{const t=b(e.getExpression());if(t===void 0||!ps.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!C(s,"maxOutputTokens")},Kc=new Set(["log","span","trace"]),_c=new Set(["ai"]),zc=new Set(["email","mail"]),$c=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),Te=(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"}),Uc=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Bc=new Set(["every","filter","flatMap","forEach","map","some"]),jc=new Set(["all","allSettled","race"]),qc=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(Bc.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&jc.has(n))return t},Vc=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(Uc.has(t.getKind())){const s=qc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Wc=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}},Hc=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}},Gc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!$c.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=Hc(n);r&&(t=!0,!Vc(r)&&!Wc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Yc=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"}),kt="lunora-advisor-exempt",Qc=/^[\s*/]+/u,Xc=/[\w-]/u,Zc=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(Qc,"");if(!o.startsWith(kt))continue;const r=o.slice(kt.length);if(Xc.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:""}},Jc=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=C(t,"handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},el=(e,t)=>{const s=Jc(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)},tl=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Fc(u)&&(r=!0),Lc(u)&&(t=!0),Dc(u)&&(o=!0),kc(u)&&(s=!0),Mc(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=Gc(e);return{callsMail:Te(e,zc),emitsEvent:Te(e,Kc),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Te(e,_c),throwsBareError:Yc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},sl=(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?Tc(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=el(e,s);return{...r?tl(r):{},...Zc(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:Nc(s,n.receiver),kind:n.kind,visibility:n.visibility}},nl=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=sl(o,t);r&&s.push(r)}return s},rl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...nl(o,x(t,n)))}return s},ol=new Set(["dbRateLimit","rateLimit"]),il=e=>i.isArrowFunction(e)?e.getBody():e,al=e=>{if(!i.isArrowFunction(e))return;const t=e.getParameters()[0]?.getNameNode();return t!==void 0&&i.isIdentifier(t)?t:void 0},ms=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getExpression()===e&&t.getName()==="args"},hs=(e,t)=>{const s=t.getSymbol();return s===void 0?[]:e.getDescendantsOfKind(l.Identifier).filter(n=>{if(n.getSymbol()!==s)return!1;const o=n.getParent();return!(i.isPropertyAccessExpression(o)&&o.getNameNode()===n)})},cl=(e,t)=>k(e)||t!==void 0&&hs(e,t).some(s=>ms(s)),ll=(e,t)=>t===void 0?U(e):hs(e,t).some(s=>!ms(s)),ul=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!ol.has(s))return;const n=N(Vt(e.getArguments()[2]),"key");if(!n)return;const o=il(n),r=al(n);if(!(!cl(o,r)||ll(o,r)))return{callee:s,exportName:A(e),file:t,limitName:qt(e),line:e.getStartLineNumber()}},dl=(e,t)=>F(e,t,ul),fl=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),gl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!fl.has(t.getName()))return;const s=t.getExpression();if(_(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&_(s.getExpression()))return s.getName()},pl=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&_(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},ml=e=>{let t=X(e)??e;for(;i.isAwaitExpression(t);)t=X(t.getExpression())??t.getExpression();return t},vs=(e,t=!1)=>{const s=ml(e);if(i.isIdentifier(s)){if(t)return;const n=he(s);return n===void 0?void 0:vs(n,!0)}if(i.isCallExpression(s))return gl(s)??pl(s)},hl=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},vl=(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=rs(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Js(n.receiver,"output"),a=n.receiver!==void 0&&Ht(n.receiver,"use","mask"),c=new Set,u=[];for(const d of hl(o)){const m=vs(d);m===void 0||c.has(m)||(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:m,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},xl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...vl(c,r))}return s},El=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(y(s));return t},Sl=(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=Wt(r);if(a===void 0)continue;const c=El(N(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},yl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sl(c,r))}return s},fe=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=fe(e.getLeft()),s=fe(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Al=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&&fe(t)!==void 0},bl=/(?:^|\/)__tests__\//u,Nl=/\.(?:spec|test)$/u,Pl=e=>bl.test(e)||Nl.test(e),wl=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return y(t);if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Il=(e,t,s)=>$n(e)?!Pl(s)&&Un(wl(t)):!0,Tl=(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(Al(r))continue;const a=fe(r);if(a===void 0)continue;const c=_n(a);if(c===void 0||!Il(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:zn(a)}))}return s},Cl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Tl(o,x(t,n)))}return s},Fl=(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=Wt(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&k(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},Ol=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Fl(c,r))}return s},Rl=new Set(["query","unsafe"]),Ll=e=>{if(!i.isPropertyAccessExpression(e)||!Rl.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"},Dl=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),kl=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Ml=(e,t)=>{if(!Ll(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Dl(s)))return{exportName:kl(e),file:t,line:s.getStartLineNumber()}},Kl=(e,t)=>F(e,t,Ml),_l=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],zl=e=>{for(const[t,s]of _l)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},$l=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=zl(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Ul=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Bl=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return xe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Ul,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},jl=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),ql=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Vl=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=y(o);t.push(r),r==="expiresInSeconds"&&(s=ql(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(y(o))}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Wl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=jl.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},Hl=(e,t)=>{const s=Wl(e.getExpression());if(s!==void 0)return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s.method,...Vl(e.getArguments()[s.optionsIndex])}},Gl=(e,t)=>F(e,t,Hl),Yl=(e,t)=>{const s=rn(t.target);return{...s===void 0?{}:{platform:s},analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,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")}},Ql=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),Xl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||C(s,"args")===void 0)return!1}return _e(e,t).opaque},Zl=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=z(a);c!==void 0&&Xl(a,c.receiver)&&s.push(Ql(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},Jl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...Zl(o,x(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},eu=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["RegisteredWhisperAuthorizer",{call:"onWhisper(handler)",note:"A dropped authorizer has no caller to fail — the whisper topics it was meant to gate silently stay open to every socket on the shard."}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),Ee=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),xs=e=>!e.isAny(),$e=e=>{const t=e.getType();if(!xs(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:eu.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},Es=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Ss={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},tu=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),su={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."},Ue=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,m=d===void 0?o:tu(d),h=c===void 0?m.remediation:`${c} ${m.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${m.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${h}`:h,title:"Procedure exists at runtime but is missing from the generated API"}},nu=(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(Ee(s,t,a)||!Es(r))continue;const c=$e(r);c!==void 0&&n.push(Ue(t,a,c,r.getStartLineNumber(),Ss))}return n},ru=(e,t,s)=>{if(Ee(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=$e(o.getExpression());r!==void 0&&n.push(Ue(t,"default",r,o.getStartLineNumber(),Ss))}return n},ou=(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(Ee(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!Es(c))continue;const u=$e(c);u!==void 0&&n.push(Ue(t,a,u,r.getStartLineNumber(),su))}return n},iu=(e,t,s)=>[...nu(e,t,s),...ru(e,t,s),...ou(e,t,s)],au=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>Ee(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),cu=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),lu=(e,t,s)=>{const n=[],o=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...iu(c,u,s)),o.push(...au(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!xs(a.getType()))&&n.push(cu(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},uu=new Set(["when","where"]),Ce=new Set(["definePolicy","defineShape"]),du=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return Ce.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 Ce.has(o)?o:void 0}const s=t.getText();return Ce.has(s)?s:void 0},fu=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,ys=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(fu(e))return"empty-object";if(i.isParenthesizedExpression(e))return ys(e.getExpression())}},Be=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),gu=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Be(t)===e),As=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Be(t)===e),pu=e=>{const t=gu(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||As(e).length>0},mu=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>Be(t)===e),De=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()==="",hu=(e,t)=>De(e)||De(t),vu=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Mt=e=>!De(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),xu=(e,t,s)=>{const n=vu.get(e);if(n!==void 0)return hu(t,s)?n==="positive"?"negative":"positive":Mt(t)||Mt(s)?void 0:n},Y=e=>{if(i.isParenthesizedExpression(e))return Y(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=xu(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=Y(e.getLeft()),o=Y(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},Kt=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Eu=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Su=e=>i.isReturnStatement(e)?e.getExpression()??e:e,yu=e=>{const t=[];for(const s of As(e)){const n=Y(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of mu(e)){const n=Y(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?Kt(s.getThenStatement()):Kt(s.getElseStatement())??Eu(s);o!==void 0&&t.push(Su(o))}return t},Au=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},bu=(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)||!uu.has(y(r)))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&pu(a))for(const c of yu(a)){const u=ys(c);u!==void 0&&o.push({exportName:Au(e),file:s,form:u,key:y(r),line:c.getStartLineNumber(),owner:t})}}return o},Nu=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=du(n);o!==void 0&&s.push(...bu(n,o,t))}return s},Pu=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Nu(o,x(t,n)))}return s},wu=new Set(["query","upsert","upsertNow"]),Iu=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(wu.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Tu=(e,t)=>{const s=Iu(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=N(n,"namespace");if(!(!o||!k(o)||U(o)))return{exportName:A(e),file:t,line:e.getStartLineNumber(),method:s}},Cu=(e,t)=>F(e,t,Tu),Fu=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"},Ou=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Ru=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Fu(a))continue;const c=Gs(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Ou(a)})}}return s},Lu=".lunora-schema.json",ke=(e,t)=>{w(e)&&$t(e,"utf8")===t||ks(e,t,"utf8")},Du=(e,t)=>{if(t===""){Ms(e,{force:!0});return}ke(e,t)},ku=e=>{const t=S(e,"package.json");if(w(t))try{const s=JSON.parse($t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Mu=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Ku=e=>{let t=w(e)?e:ae(e);for(;t&&t!==ae(t);){const s=S(t,"tsconfig.json");if(w(s))return s;t=ae(t)}},_t=e=>e.replaceAll("\\","/"),_u=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new $("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 $("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 $("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})}},ge=(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)},zt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,zu=8,$u=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:m}=e,h=()=>yn(()=>{const P=An(a,o),O=Fn(a,o);return{functions:P,httpRoutes:bn(a,o),mutators:O}});let{erased:R,value:{functions:M,httpRoutes:g,mutators:I}}=h();pt([...M,...I].map(P=>P.filePath)),pt(g.filter(P=>P.stream).map(P=>P.filePath),"http-stream");for(let P=1;;P+=1){const O=Xn({agents:t,functions:M,httpRoutes:g,mutators:I,useUmbrella:d,workflows:m}),v=cr({agents:t,functions:M,migrations:r,mutators:I,shapes:c,useUmbrella:d,usesSandbox:u});if(P>=zu||zt(a,s,O)&&zt(a,n,v))return{apiContent:O,erased:R,functions:M,functionsContent:v,httpRoutes:g,mutators:I};ge(a,s,O),ge(a,n,v),{erased:R,value:{functions:M,httpRoutes:g,mutators:I}}=h()}},Uu=e=>{const t=Ku(e);return t?new dt({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new dt({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Wd=(e,t)=>{const s=p(t),n=S(t,"schema.ts");w(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=>_t(c))),r=_t(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Hd=e=>{const t=Mu(),s=t?we.now():0,n=S(e.projectRoot,e.lunoraDirectory??"lunora"),o=S(n,"schema.ts");if(!w(o))throw new $("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??Uu(n);pn(yi);const a=Kn(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:m,dependencies:h,entryCronTriggers:R,env:M,featureUsage:g,hasFlags:I,hasNotify:P,identity:O,platformGate:v,queues:D,serverContent:B,storageRulesMetadata:H,usesSandbox:te,useUmbrella:K,workflows:L}=$r({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target});ia(a,a.jurisdiction===void 0?void 0:ra(r,n));const E=S(n,"_generated"),bs=S(E,"dataModel.ts"),Ns=S(E,"server.ts"),Ps=S(E,"api.ts"),ws=S(E,"functions.ts");ge(r,bs,m),ge(r,Ns,B);const se=In(r,n),q=Bn(r,n),{apiContent:je,erased:Is,functions:V,functionsContent:qe,httpRoutes:Ts,mutators:ne}=$u({agents:c,apiPath:Ps,generatedFunctionsPath:ws,lunoraDirectory:n,migrations:se,project:r,shapes:q,useUmbrella:K,usesSandbox:te,workflows:L}),re=e.lint===!1?void 0:$s({adminRoutes:Gr(r,n),aiRawRuns:Xr(r,n),aiToolSideEffects:ao(r,n),argumentDerivedFetches:uo(r,n),argumentValidators:yo(r,n),authApiCalls:mn(r,n),authConfigs:Oo(r,n),browserUrlAccesses:Mo(r,n),configCalls:qo(r,n),containerKeyAccesses:Wo(r,n),containerOverrides:Zo(r,n),containers:u,exportSinks:si(r,n),staleMigrationImports:$l(r,n),failOpenGuards:ai(r,n),flagReads:hi(r,n),flagSecurityDefaults:Si(r,n),geoIndexUsages:Ni(r,n),httpActionGuards:Mi(r,n),httpHeaderWrites:Wi(r,n),hyperdriveCalls:Nn(r,n),identityClaimReads:Ji(r,n),imageDeliveryUrlAccesses:ta(r,n),inserts:Pn(r,n),kvKeyAccesses:ca(r,n,V),mailRecipientAccesses:ga(r,n),maskProcedures:wn(r,n),maskStrategies:ya(r,n),mutatorWrites:Ia(r,n),nondeterministicCalls:On(r,n),normalizeIdAuthorizations:ja(r,n),notifyCalls:Ln(r,n),notifyConfig:Rn(r,n),mutators:ne,ownerFieldWrites:Ja(r,n,V,ne),unrestrictedWhereBranches:Pu(r,n),paymentWebhooks:ac(r,n),privilegedDispatches:Sc(r,n),procedureProtections:rl(r,n),queries:gn(r,n),queues:D,r2sqlCalls:Dn(r,n),ratelimitKeySelectors:dl(r,n),rawRowReturns:xl(r,n),relationLoads:yl(r,n),rlsProcedures:kn(r,n),schema:a,secretLiterals:Cl(r,n),shapes:q,softDeleteReads:Ol(r,n),sqlInterpolations:Kl(r,n),storageKeyAccesses:Bl(r,n,V),storageUploads:Gl(r,n),vectorNamespaceAccesses:Cu(r,n),workflowCalls:Ru(r,n),workflows:L,wranglerVariables:e.wranglerVariables}),Ve=re===void 0?[]:ur(e.projectRoot,[...Ks(re,{source:"static"}),...lu(r,n,{byName:new Set([...L,...D,...c,...u].map(f=>f.exportName)),byPath:new Set([...V,...ne,...q,...se].map(f=>`${f.filePath}:${f.exportName}`))}),...Jl(r,n),...Sn(Is,n)]),Cs=Mn(r,n),We=xa(r,n);_u(q,We,ha(r,n));const Fs=I?di(r,n):[],Se=v.signals.vectorStore!==!1,G=Yl(g,{containerCount:u.length,cronCount:d.length,dependencies:h,hasPaymentTables:sc(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Yt(a)).length,storageRuleCount:H.rules.length,vectorIndexCount:a.vectorIndexes.length,target:Gt(e.projectRoot,e.target),vectorStoreSupported:Se,workflowCount:L.length}),He=t?we.now():0,ye=Gn(a,se.map(f=>f.id)),Ge=on({advisories:Ve.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:re?.procedureProtections??[],agents:c,containers:u,env:M,flagKeys:Fs,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:I,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:P,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:Se,hasX402:g.x402,maskMetadata:We,mutators:ne,queues:D,rlsMetadata:Cs,schema:a,schemaSnapshot:ye,shapes:q,storageRules:H,studioFeatures:G,useUmbrella:K,workflows:L}),Ye=Yn(q,h.has("@lunora/db"),K),Qe=Zn(u,a.jurisdiction),Xe=Jn(L),Ze=er(c),Je=tr(D),et=sr(d),Os=nr(G.scheduler),Rs=rr(a.tables,K),tt=or(a.vectorIndexes),oe=ar(a,K),st=Qn(h.has("@lunora/seed")),ie=e.apiSpec??"openapi",Ae=ie==="openapi"||ie==="both",be=ie==="openrpc"||ie==="both",nt=jn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({className:f.className,exportName:f.exportName})),hasAccess:h.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:h.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:h.has("@lunora/astro")||h.has("@lunora/svelte")||h.has("@lunora/vue")||w(S(e.projectRoot,"src","worker.ts")),hasGlobal:a.tables.some(f=>Ut(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>Bt(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:G.kv,hasNotify:P,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:D.some(f=>f.mode==="push"),hasScheduler:G.scheduler,hasSourcedTables:a.tables.some(f=>f.externalSource!==void 0),hasStorage:G.storage,hasVectors:Se,hasWorkflow:L.length>0,hasX402:g.x402,identity:O,jurisdiction:a.jurisdiction,jurisdictionPinsAuth:a.jurisdictionPinsAuth===!0,tables:a.tables.map(f=>({name:f.name,shardMode:f.shardMode})),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:Ae,wantsOpenRpc:be}),rt=ku(e.projectRoot),ot=qn({functions:V,httpRoutes:Ts,version:rt}),it=Wn({functions:V,version:rt}),at=`${JSON.stringify(ot,void 0,2)}
8
- `,ct=`${JSON.stringify(it,void 0,2)}
9
- `,lt=Vn(ot),ut=Hn(it),Ne=S(n,Lu),Ls=w(Ne),Pe=[];if(!e.dryRun){w(E)||Ds(E,{recursive:!0});const f=(j,W)=>{ke(S(E,j),W),Pe.push(j)},T=(j,W)=>{Du(S(E,j),W),W!==""&&Pe.push(j)};f("app.ts",nt),f("dataModel.ts",m),f("api.ts",je),f("server.ts",B),f("functions.ts",qe),f("shard.ts",Ge),f("crons.ts",et),f("vectors.ts",tt),f("drizzle.global.ts",oe.global),f("drizzle.shard.ts",oe.shard),T("containers.ts",Qe),T("workflows.ts",Xe),T("agents.ts",Ze),T("queues.ts",Je),T("scheduler.ts",Os),T("shardRegistry.ts",Rs),T("seed.ts",st),T("collections.ts",Ye),T("openapi.json",Ae?at:""),T("openapi.ts",Ae?lt:""),T("openrpc.json",be?ct:""),T("openrpc.ts",be?ut:""),(!Ls||e.updateSchemaBaseline===!0)&&ke(Ne,zs(ye))}if(t){const f=we.now(),T=Math.round(f-s),j=Math.round(He-s),W=Math.round(f-He);console.error(`@lunora/codegen: codegen took ${T.toString()}ms (discovery ${j.toString()}ms, emit ${W.toString()}ms)`)}return{advisories:Ve,advisorContext:re,agents:c,containers:u,cronTriggers:[...new Set([...ir(d),...R])],generated:{agents:Ze,api:je,app:nt,collections:Ye,containers:Qe,crons:et,dataModel:m,drizzleGlobal:oe.global,drizzleShard:oe.shard,functions:qe,openApi:at,openApiModule:lt,openRpc:ct,openRpcModule:ut,queues:Je,seed:st,server:B,shard:Ge,vectors:tt,workflows:Xe},migrations:se,outputDirectory:E,platformDiagnostics:v.diagnostics,queues:D,schemaSnapshot:ye,schemaSnapshotPath:Ne,workflows:L,writtenFiles:Pe}};export{Lu as SCHEMA_SNAPSHOT_FILENAME,Uu as createCodegenProject,Ku as findTsconfig,Wd as refreshCodegenProject,Hd as runCodegen};
@@ -1 +0,0 @@
1
- import"./json-data-Chfs2Cz5.mjs";import{v as m,o as r,z as i,m as n,A as o,p as g,l as F,C as u,t as p,n as l,B as f,s as d,q as k}from"./shard-runtime-B7xvdFPc.mjs";import"./shared-DjUziztz.mjs";export{m as buildDoTypeImports,r as emitAgentFragments,i as emitAgents,n as emitContainerFragments,o as emitContainers,g as emitPaymentFragments,F as emitQueueFragments,u as emitQueues,p as emitQueuesMetadataFragments,l as emitWorkflowFragments,f as emitWorkflows,d as emitWorkflowsMetadataFragments,k as emitX402Fragments};
@@ -1 +0,0 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./ir-BgM8A3XV.mjs";import"./json-data-Chfs2Cz5.mjs";import{e as f}from"./shard-CCNl561P.mjs";import"./shard-runtime-B7xvdFPc.mjs";import"./shared-DjUziztz.mjs";export{f as default};
@@ -1 +0,0 @@
1
- const o=d=>typeof d.shardMode=="object"&&d.shardMode.kind==="shardBy";export{o as i};