@lunora/codegen 1.0.0-alpha.106 → 1.0.0-alpha.108

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -817,9 +817,10 @@ interface WorkflowCallIR {
817
817
  }
818
818
  /**
819
819
  * A `ctx.db.query("table")…` read discovered in a function body, reduced to what
820
- * the `filter_without_index` advisor lint needs: which table, whether the chain
821
- * narrows with an index, and whether it filters. `table` is `""` when the
822
- * `query(...)` argument is not a string literal (a dynamic table — not lintable).
820
+ * the query advisor lints need: which table, whether the chain narrows with an
821
+ * index, whether it filters, and which terminal materializes the result.
822
+ * `table` is `""` when the `query(...)` argument is not a string literal (a
823
+ * dynamic table — not lintable).
823
824
  */
824
825
  interface QueryReadIR {
825
826
  /** Exported procedure the read sits in, or `""` at module scope. */
@@ -841,6 +842,18 @@ interface QueryReadIR {
841
842
  line: number;
842
843
  /** Queried table name, or `""` when the argument is not a string literal. */
843
844
  table: string;
845
+ /**
846
+ * The materializing call the chain ends in — `"collect"`, `"take"`,
847
+ * `"paginate"`, `"first"`, `"unique"`, … — i.e. how much of the narrowed set
848
+ * the read actually loads.
849
+ *
850
+ * `undefined` when the chain reaches no recognised terminal (a reader passed
851
+ * on, a bare `query(...)`) AND when a feeder predating this field produced
852
+ * the read. The two are deliberately not distinguished: no consumer could act
853
+ * on the difference, so the terminal-shaped lints skip the read either way
854
+ * rather than guessing a terminal.
855
+ */
856
+ terminal?: string;
844
857
  }
845
858
  /**
846
859
  * A `ctx.authApi.<method>(...)` call discovered in a function body, attributed
@@ -2308,6 +2321,17 @@ interface PlatformDiagnostic {
2308
2321
  * dot keeps it tucked away next to the schema it describes.
2309
2322
  */
2310
2323
  declare const SCHEMA_SNAPSHOT_FILENAME = ".lunora-schema.json";
2324
+ /**
2325
+ * Walk up from `startPath` until we find a `tsconfig.json` or hit the file
2326
+ * system root. Returns the absolute path to the tsconfig, or `undefined`.
2327
+ *
2328
+ * Exported (see the bottom-of-file `export { findTsconfig }`) so a long-lived
2329
+ * caller (the Vite dev-loop's cached-Project invalidation) can ask "which
2330
+ * tsconfig would {@link createCodegenProject} resolve right now?" without
2331
+ * duplicating the walk — recomputing it per call is a handful of `existsSync`
2332
+ * checks, negligible next to a Project rebuild.
2333
+ */
2334
+ declare const findTsconfig: (startPath: string) => string | undefined;
2311
2335
  /**
2312
2336
  * Construct the ts-morph `Project` codegen discovers over. Prefers the user's
2313
2337
  * `tsconfig.json` (when one is found walking up from `lunoraDirectory`) so
@@ -2328,9 +2352,16 @@ declare const createCodegenProject: (lunoraDirectory: string) => Project;
2328
2352
  * removes Project source files under `lunoraDirectory` that no longer exist on
2329
2353
  * disk (the classic stale-deleted-file cache bug).
2330
2354
  *
2331
- * Files outside `lunoraDirectory` (e.g. those pulled in by the user's tsconfig)
2332
- * are left untouchedthey back type resolution and rarely change in the
2333
- * dev-loop; a tsconfig change invalidates the whole cached Project upstream.
2355
+ * Files outside `lunoraDirectory` e.g. a shared validator or type pulled in
2356
+ * via the user's tsconfig are also `refreshFromFileSystemSync()`ed, but only
2357
+ * the ones already loaded into the Project; none are added. `resolveValidatorAlias`
2358
+ * (parse-validator.ts) follows `getAliasedSymbol()` across module boundaries, so a
2359
+ * validator defined outside `lunoraDirectory` is genuinely read from whatever
2360
+ * source the Project currently holds — leaving those files stale made a reused
2361
+ * Project (the Vite dev loop) silently disagree with a fresh one (`lunora
2362
+ * codegen`) about the same source. `node_modules` is excluded: its `.d.ts` set
2363
+ * dominates the file count and never changes mid dev-loop, so refreshing it would
2364
+ * reinstate close to the full re-parse cost this cache exists to avoid.
2334
2365
  */
2335
2366
  declare const refreshCodegenProject: (project: Project, lunoraDirectory: string) => void;
2336
2367
  /**
@@ -2720,10 +2751,13 @@ declare const discoverNotifyConfig: (project: Project, lunoraDirectory: string)
2720
2751
  */
2721
2752
  declare const readPackageDependencies: (projectRoot: string) => Set<string> | undefined;
2722
2753
  /**
2723
- * Discover `ctx.db.query("table")…` reads under the lunora source directory and
2724
- * reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
2725
- * returned — an unfiltered read is never a `filter_without_index` candidate, so
2726
- * dropping the rest keeps the lint input small.
2754
+ * Discover every `ctx.db.query("table")…` read under the lunora source directory
2755
+ * and reduce each to a {@link QueryReadIR}.
2756
+ *
2757
+ * Reads without a `.filter()` are kept too. They are never
2758
+ * `filter_without_index` candidates (that lint gates on `hasFilter`), but an
2759
+ * unfiltered, unindexed `.collect()` is the read `unbounded_collect` exists for
2760
+ * — and dropping it here is precisely why nothing could see it.
2727
2761
  */
2728
2762
  declare const discoverQueries: (project: Project, lunoraDirectory: string) => QueryReadIR[];
2729
2763
  /** The only file queues may be declared in — mirrors `lunora/workflows.ts`. */
@@ -3572,4 +3606,4 @@ declare const secretKindOf: (value: string) => string | undefined;
3572
3606
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
3573
3607
  declare const redact: (value: string) => string;
3574
3608
  declare const VERSION = "0.0.0";
3575
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3609
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -817,9 +817,10 @@ interface WorkflowCallIR {
817
817
  }
818
818
  /**
819
819
  * A `ctx.db.query("table")…` read discovered in a function body, reduced to what
820
- * the `filter_without_index` advisor lint needs: which table, whether the chain
821
- * narrows with an index, and whether it filters. `table` is `""` when the
822
- * `query(...)` argument is not a string literal (a dynamic table — not lintable).
820
+ * the query advisor lints need: which table, whether the chain narrows with an
821
+ * index, whether it filters, and which terminal materializes the result.
822
+ * `table` is `""` when the `query(...)` argument is not a string literal (a
823
+ * dynamic table — not lintable).
823
824
  */
824
825
  interface QueryReadIR {
825
826
  /** Exported procedure the read sits in, or `""` at module scope. */
@@ -841,6 +842,18 @@ interface QueryReadIR {
841
842
  line: number;
842
843
  /** Queried table name, or `""` when the argument is not a string literal. */
843
844
  table: string;
845
+ /**
846
+ * The materializing call the chain ends in — `"collect"`, `"take"`,
847
+ * `"paginate"`, `"first"`, `"unique"`, … — i.e. how much of the narrowed set
848
+ * the read actually loads.
849
+ *
850
+ * `undefined` when the chain reaches no recognised terminal (a reader passed
851
+ * on, a bare `query(...)`) AND when a feeder predating this field produced
852
+ * the read. The two are deliberately not distinguished: no consumer could act
853
+ * on the difference, so the terminal-shaped lints skip the read either way
854
+ * rather than guessing a terminal.
855
+ */
856
+ terminal?: string;
844
857
  }
845
858
  /**
846
859
  * A `ctx.authApi.<method>(...)` call discovered in a function body, attributed
@@ -2308,6 +2321,17 @@ interface PlatformDiagnostic {
2308
2321
  * dot keeps it tucked away next to the schema it describes.
2309
2322
  */
2310
2323
  declare const SCHEMA_SNAPSHOT_FILENAME = ".lunora-schema.json";
2324
+ /**
2325
+ * Walk up from `startPath` until we find a `tsconfig.json` or hit the file
2326
+ * system root. Returns the absolute path to the tsconfig, or `undefined`.
2327
+ *
2328
+ * Exported (see the bottom-of-file `export { findTsconfig }`) so a long-lived
2329
+ * caller (the Vite dev-loop's cached-Project invalidation) can ask "which
2330
+ * tsconfig would {@link createCodegenProject} resolve right now?" without
2331
+ * duplicating the walk — recomputing it per call is a handful of `existsSync`
2332
+ * checks, negligible next to a Project rebuild.
2333
+ */
2334
+ declare const findTsconfig: (startPath: string) => string | undefined;
2311
2335
  /**
2312
2336
  * Construct the ts-morph `Project` codegen discovers over. Prefers the user's
2313
2337
  * `tsconfig.json` (when one is found walking up from `lunoraDirectory`) so
@@ -2328,9 +2352,16 @@ declare const createCodegenProject: (lunoraDirectory: string) => Project;
2328
2352
  * removes Project source files under `lunoraDirectory` that no longer exist on
2329
2353
  * disk (the classic stale-deleted-file cache bug).
2330
2354
  *
2331
- * Files outside `lunoraDirectory` (e.g. those pulled in by the user's tsconfig)
2332
- * are left untouchedthey back type resolution and rarely change in the
2333
- * dev-loop; a tsconfig change invalidates the whole cached Project upstream.
2355
+ * Files outside `lunoraDirectory` e.g. a shared validator or type pulled in
2356
+ * via the user's tsconfig are also `refreshFromFileSystemSync()`ed, but only
2357
+ * the ones already loaded into the Project; none are added. `resolveValidatorAlias`
2358
+ * (parse-validator.ts) follows `getAliasedSymbol()` across module boundaries, so a
2359
+ * validator defined outside `lunoraDirectory` is genuinely read from whatever
2360
+ * source the Project currently holds — leaving those files stale made a reused
2361
+ * Project (the Vite dev loop) silently disagree with a fresh one (`lunora
2362
+ * codegen`) about the same source. `node_modules` is excluded: its `.d.ts` set
2363
+ * dominates the file count and never changes mid dev-loop, so refreshing it would
2364
+ * reinstate close to the full re-parse cost this cache exists to avoid.
2334
2365
  */
2335
2366
  declare const refreshCodegenProject: (project: Project, lunoraDirectory: string) => void;
2336
2367
  /**
@@ -2720,10 +2751,13 @@ declare const discoverNotifyConfig: (project: Project, lunoraDirectory: string)
2720
2751
  */
2721
2752
  declare const readPackageDependencies: (projectRoot: string) => Set<string> | undefined;
2722
2753
  /**
2723
- * Discover `ctx.db.query("table")…` reads under the lunora source directory and
2724
- * reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
2725
- * returned — an unfiltered read is never a `filter_without_index` candidate, so
2726
- * dropping the rest keeps the lint input small.
2754
+ * Discover every `ctx.db.query("table")…` read under the lunora source directory
2755
+ * and reduce each to a {@link QueryReadIR}.
2756
+ *
2757
+ * Reads without a `.filter()` are kept too. They are never
2758
+ * `filter_without_index` candidates (that lint gates on `hasFilter`), but an
2759
+ * unfiltered, unindexed `.collect()` is the read `unbounded_collect` exists for
2760
+ * — and dropping it here is precisely why nothing could see it.
2727
2761
  */
2728
2762
  declare const discoverQueries: (project: Project, lunoraDirectory: string) => QueryReadIR[];
2729
2763
  /** The only file queues may be declared in — mirrors `lunora/workflows.ts`. */
@@ -3572,4 +3606,4 @@ declare const secretKindOf: (value: string) => string | undefined;
3572
3606
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
3573
3607
  declare const redact: (value: string) => string;
3574
3608
  declare const VERSION = "0.0.0";
3575
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3609
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as L,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as G}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as y}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as k}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as W,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as j}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as B,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as X}from"./packem_shared/discover-queries-i4Vd2si7.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as fe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,M as Re,B as ge,p as Me,L as Ce,R as he,C as _e,V as Le,Q as Ie,$ as Te,E as Fe,m as De,F as Pe}from"./packem_shared/emit-BbLyaTLJ.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-DkO-Qvoo.mjs";import{buildOpenApiDocument as ye,emitOpenApi as be,emitOpenApiModule as ke}from"./packem_shared/buildOpenApiDocument-B8-PH9af.mjs";import{OPENRPC_VERSION as We,buildOpenRpcDocument as Ke,emitOpenRpc as Qe,emitOpenRpcModule as je}from"./packem_shared/OPENRPC_VERSION-Bzh1vxcl.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as Be,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,refreshCodegenProject as Ze,runCodegen as er}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CXtgvIcd.mjs";import{SchemaSnapshotParseError as or,buildSchemaSnapshot as tr,evaluateSchemaDrift as sr,parseSchemaSnapshot as ar}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as mr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as fr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{SDK_LANGUAGES as nr,SDK_TARGETS as Sr,generateSdk as lr}from"./packem_shared/SDK_LANGUAGES-fIqQtE14.mjs";import{redact as xr,secretKindOf as Ar}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as vr,findSolutionByMessage as Nr}from"@lunora/errors";import{isTypedSchema as Rr}from"./packem_shared/isTypedSchema-9wiKtXr2.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,L as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,vr as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,w as NOTIFY_FILENAME,We as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,nr as SDK_LANGUAGES,Sr as SDK_TARGETS,ne as SHAPES_FILENAME,or as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,ye as buildOpenApiDocument,Ke as buildOpenRpcDocument,tr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,M as discoverContainers,h as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,y as discoverMaskProcedures,k as discoverMigrations,K as discoverMutators,j as discoverNondeterministicCalls,B as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,fe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,Ge as emitApp,ge as emitCollections,Me as emitContainers,Ce as emitCrons,he as emitDataModel,_e as emitDrizzleSchema,Le as emitFunctions,be as emitOpenApi,ke as emitOpenApiModule,Qe as emitOpenRpc,je as emitOpenRpcModule,Ie as emitServer,Te as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,sr as evaluateSchemaDrift,Nr as findLunoraSolution,m as formatAdvisories,lr as generateSdk,Rr as isTypedSchema,d as lintSchema,ar as parseSchemaSnapshot,Be as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,xr as redact,Ze as refreshCodegenProject,Je as resolveCodegenTarget,er as runCodegen,mr as schemaFromIr,Ar as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,fr as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CQvIhQ04.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as S}from"./packem_shared/describeErrorLevelFindings-IhNx9gPr.mjs";import{CodegenDiagnosticError as E,diagnosticAt as x}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-Dk-k250h.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-XfNbxqlq.mjs";import{CONTAINERS_FILENAME as g,discoverContainers as M}from"./packem_shared/CONTAINERS_FILENAME-DQpyhY6c.mjs";import{default as h}from"./packem_shared/discoverCrons-RlATa0_t.mjs";import{FLAGS_FILENAME as I,discoverFlags as L}from"./packem_shared/FLAGS_FILENAME-Boqm0YCP.mjs";import{discoverFunctions as F}from"./packem_shared/discoverFunctions-4TNKUv7P.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-DQivLBqT.mjs";import{default as G}from"./packem_shared/discoverInserts-D6szWzrV.mjs";import{default as b}from"./packem_shared/discoverMaskProcedures-BBPqLXA5.mjs";import{default as y}from"./packem_shared/discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as W,discoverMutators as K}from"./packem_shared/MUTATORS_FILENAME-Cp_JxLSz.mjs";import{default as j}from"./packem_shared/discoverNondeterministicCalls-Bxr652Rz.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as B,discoverNotifyConfig as q}from"./packem_shared/NOTIFY_FILENAME-DwyJ5I4Q.mjs";import{default as Y}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{I as X}from"./packem_shared/discover-queries-CU9o_j87.mjs";import{QUEUES_FILENAME as ee,discoverQueues as re}from"./packem_shared/QUEUES_FILENAME-QpMZsde0.mjs";import{default as te}from"./packem_shared/discoverR2sqlCalls-DMxG6gHr.mjs";import{discoverRlsMetadata as ae,default as ie}from"./packem_shared/discoverRlsMetadata-B63ARnKG.mjs";import{discoverSandboxUsage as de}from"./packem_shared/discoverSandboxUsage-DBM98vVh.mjs";import{default as pe}from"./packem_shared/discoverSchema-BNr7PVcZ.mjs";import{SHAPES_FILENAME as ne,discoverShapes as Se}from"./packem_shared/SHAPES_FILENAME-WxXOsYfe.mjs";import{default as Ee}from"./packem_shared/discoverStorageRulesMetadata-_40MGqRX.mjs";import{WORKFLOWS_FILENAME as Ae,discoverWorkflows as ue}from"./packem_shared/WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{S as Ne,h as Oe,M as Re,B as ge,p as Me,L as Ce,R as he,C as _e,V as Ie,Q as Le,$ as Te,E as Fe,m as De,F as Pe}from"./packem_shared/emit-BbLyaTLJ.mjs";import{emitApp as Ge}from"./packem_shared/emitApp-DkO-Qvoo.mjs";import{buildOpenApiDocument as be,emitOpenApi as ke,emitOpenApiModule as ye}from"./packem_shared/buildOpenApiDocument-B8-PH9af.mjs";import{OPENRPC_VERSION as We,buildOpenRpcDocument as Ke,emitOpenRpc as Qe,emitOpenRpcModule as je}from"./packem_shared/OPENRPC_VERSION-Bzh1vxcl.mjs";import{DEFAULT_TARGET as we,platformMatrixIds as Be,readProjectTarget as qe,resolveCodegenTarget as Je}from"./packem_shared/DEFAULT_TARGET-CH5disA3.mjs";import{SCHEMA_SNAPSHOT_FILENAME as $e,createCodegenProject as Xe,findTsconfig as Ze,refreshCodegenProject as er,runCodegen as rr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-lAJi8U-X.mjs";import{SchemaSnapshotParseError as tr,buildSchemaSnapshot as sr,evaluateSchemaDrift as ar,parseSchemaSnapshot as ir}from"./packem_shared/SchemaSnapshotParseError-BkgxjBPQ.mjs";import{schemaFromIr as dr}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as pr,validatorIrToJsonSchema as cr}from"./packem_shared/LUNORA_ERROR_CODES-zfAI2OFs.mjs";import{SDK_LANGUAGES as Sr,SDK_TARGETS as lr,generateSdk as Er}from"./packem_shared/SDK_LANGUAGES-fIqQtE14.mjs";import{redact as Ar,secretKindOf as ur}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as Nr,findSolutionByMessage as Or}from"@lunora/errors";import{isTypedSchema as gr}from"./packem_shared/isTypedSchema-9wiKtXr2.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,g as CONTAINERS_FILENAME,E as CodegenDiagnosticError,we as DEFAULT_TARGET,I as FLAGS_FILENAME,Ne as GENERATED_HEADER,pr as LUNORA_ERROR_CODES,Nr as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,w as NOTIFY_FILENAME,We as OPENRPC_VERSION,ee as QUEUES_FILENAME,$e as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Sr as SDK_LANGUAGES,lr as SDK_TARGETS,ne as SHAPES_FILENAME,tr as SchemaSnapshotParseError,e as VERSION,Ae as WORKFLOWS_FILENAME,be as buildOpenApiDocument,Ke as buildOpenRpcDocument,sr as buildSchemaSnapshot,Xe as createCodegenProject,c as describeErrorLevelFindings,x as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,M as discoverContainers,h as discoverCrons,L as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverInserts,b as discoverMaskProcedures,y as discoverMigrations,K as discoverMutators,j as discoverNondeterministicCalls,B as discoverNotifyCalls,q as discoverNotifyConfig,X as discoverQueries,re as discoverQueues,te as discoverR2sqlCalls,ae as discoverRlsMetadata,ie as discoverRlsProcedures,de as discoverSandboxUsage,pe as discoverSchema,Se as discoverShapes,Ee as discoverStorageRulesMetadata,ue as discoverWorkflows,Oe as emitAgents,Re as emitApi,Ge as emitApp,ge as emitCollections,Me as emitContainers,Ce as emitCrons,he as emitDataModel,_e as emitDrizzleSchema,Ie as emitFunctions,ke as emitOpenApi,ye as emitOpenApiModule,Qe as emitOpenRpc,je as emitOpenRpcModule,Le as emitServer,Te as emitShard,Fe as emitVectors,De as emitWorkflows,Pe as emitWranglerCronTriggers,n as errorAdvisoryNames,S as errorPlatformDiagnosticNames,ar as evaluateSchemaDrift,Or as findLunoraSolution,Ze as findTsconfig,m as formatAdvisories,Er as generateSdk,gr as isTypedSchema,d as lintSchema,ir as parseSchemaSnapshot,Be as platformMatrixIds,Y as readPackageDependencies,qe as readProjectTarget,Ar as redact,er as refreshCodegenProject,Je as resolveCodegenTarget,rr as runCodegen,dr as schemaFromIr,ur as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,cr as validatorIrToJsonSchema};
@@ -1,9 +1,9 @@
1
- import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,M as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,P as ls,F as us}from"./emit-BbLyaTLJ.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,y as Ss}from"./discover-queries-i4Vd2si7.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Os from"./discoverInserts-D6szWzrV.mjs";import Cs,{discoverMaskStrategies as Fs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-DkO-Qvoo.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-B8-PH9af.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-Bzh1vxcl.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
1
+ import{existsSync as b,mkdirSync as qt,readFileSync as dt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as le}from"node:path";import{performance as ue}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Ge}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as _t}from"./formatAdvisories-CQvIhQ04.mjs";import{discoverAgents as Gt}from"./AGENTS_FILENAME-Dk-k250h.mjs";import{discoverContainers as Ht}from"./CONTAINERS_FILENAME-DQpyhY6c.mjs";import{diagnosticAt as Z}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Y}from"./module-specifiers-8FEEiUcv.mjs";import{r as de,Q as Qt,R as Jt,a as Xt,M as Zt,V as Yt,$ as es,B as ts,p as ss,m as rs,h as ns,f as is,L as os,E as as,C as cs,P as ls,F as us}from"./emit-BbLyaTLJ.mjs";import{g as h,p as E,P as N,C as $,O as gt,z as ds,R as pt,h as gs}from"./discover-ast-7ABwvTVn.mjs";import ps from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as fs}from"./QUEUES_FILENAME-QpMZsde0.mjs";import{discoverSandboxUsage as ms}from"./discoverSandboxUsage-DBM98vVh.mjs";import hs from"./discoverStorageRulesMetadata-_40MGqRX.mjs";import{discoverWorkflows as xs}from"./WORKFLOWS_FILENAME-Dz80zqeT.mjs";import{gatePlatformFeatures as Es,resolveCodegenTarget as ys}from"./DEFAULT_TARGET-CH5disA3.mjs";import{i as I,a as D,e as x,c as A,r as $s,b as vs,s as ee,d as bs,f as Ns,I as Ss}from"./discover-queries-CU9o_j87.mjs";import{classifyProcedureCall as M,inlineHandler as As,procedureHandler as ft,chainUsesWrappedCall as mt,isDatabaseAccessor as R,chainHasStep as ws,discoverFunctions as Ps,resolveStandardSchemaType as Is}from"./discoverFunctions-4TNKUv7P.mjs";import Ts from"./discoverAuthApiCalls-XfNbxqlq.mjs";import Ls from"./discoverCrons-RlATa0_t.mjs";import{discoverFlagKeys as ks}from"./FLAGS_FILENAME-Boqm0YCP.mjs";import Ds from"./discoverHttpRoutes-DQivLBqT.mjs";import Fs from"./discoverInserts-D6szWzrV.mjs";import Os,{discoverMaskStrategies as Cs,discoverMaskMetadata as Ks,discoverMaskHasNonLiteralPolicy as Rs}from"./discoverMaskProcedures-BBPqLXA5.mjs";import Ms from"./discoverMigrations-rbjxflR8.mjs";import{MUTATORS_FILENAME as js,isDefineMutatorCallee as zs,discoverMutators as qs}from"./MUTATORS_FILENAME-Cp_JxLSz.mjs";import Bs from"./discoverNondeterministicCalls-Bxr652Rz.mjs";import{discoverNotifyConfig as Us,discoverNotifyCalls as Vs}from"./NOTIFY_FILENAME-DwyJ5I4Q.mjs";import Ws from"./discoverR2sqlCalls-DMxG6gHr.mjs";import _s,{discoverRlsMetadata as Gs}from"./discoverRlsMetadata-B63ARnKG.mjs";import Hs from"./discoverSchema-BNr7PVcZ.mjs";import{secretKindOf as Qs,redact as Js,isHeuristicSecretKind as Xs,isSecretishName as Zs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Ys}from"./SHAPES_FILENAME-WxXOsYfe.mjs";import{emitApp as er}from"./emitApp-DkO-Qvoo.mjs";import{buildOpenApiDocument as tr,emitOpenApiModule as sr}from"./buildOpenApiDocument-B8-PH9af.mjs";import{buildOpenRpcDocument as rr,emitOpenRpcModule as nr}from"./OPENRPC_VERSION-Bzh1vxcl.mjs";import{y as ir}from"./parse-validator-CusS8QwU.mjs";import{buildSchemaSnapshot as or}from"./SchemaSnapshotParseError-BkgxjBPQ.mjs";const ar=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},cr=(e,t)=>{if(t===void 0)return;const s=ar(e).filter(i=>!t.has(i.name));if(s.length===0)return;const r=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
2
2
  `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
3
  ${r}
4
4
 
5
- Install them with your package manager, then re-run codegen.`)},lr="env.ts",ur=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},gr=e=>{if(o.isIdentifier(e))return ur(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&dr(t)}return!1},pr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!gr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},fr=(e,t)=>{const s=g(t,lr);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=pr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},mr=e=>{const t=r=>o.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getInitializer(),n=r.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(n)))for(const a of n.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},hr=(e,t)=>{const s=Object.fromEntries(de.map(r=>[r.key,!1]));for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=mr(i);for(const c of de)if(!s[c.key]){if(n.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(de.every(c=>s[c.key]))break}return s},xr=["providerSubscriptionId","state"],Er=["providerEventId","processedAt"],He=(e,t)=>t.every(s=>s in e.shape),yr=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&He(t,xr)&&He(s,Er)},$r=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),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:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),ht="identity.ts",vr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},br=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},Nr=e=>{if(o.isIdentifier(e))return vr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&br(t)}return!1},Sr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!Nr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Ar=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Sr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},wr=(e,t)=>{const s=new Map,r=new Map,i=new Map;for(const n of e)s.set(n.name,`workflow "${n.exportName}"`),r.set(n.bindingName,`workflow "${n.exportName}"`),i.set(n.className,`workflow "${n.exportName}"`);for(const n of t){const a=s.get(n.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${n.name}": produced by both ${a} and agent "${n.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(n.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${n.bindingName}": produced by both ${c} and agent "${n.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(n.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${n.className}": produced by both ${u} and agent "${n.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Pr=e=>{const{lunoraDirectory:t,project:s,projectRoot:r,schema:i}=e,n=Ar(s,t),a=fr(s,t),c=xs(s,t),u=fs(s,t),d=Gt(s,t);wr(c,d);const y=Ht(s,t),w=hs(s,t),p=Es(hr(s,t),ys(r,e.target)),v=p.usage,C=ms(s,t),j=v.browser||C.usesSandboxBrowser,z=ps(r),U=z??new Set,T=U.has("lunorash");cr(i,z);const F=b(g(t,"flags.ts")),q=b(g(t,"notify.ts"));return{agents:d,containers:y,dataModelContent:Jt(i),declaredDependencies:z,dependencies:U,env:a,featureUsage:v,hasBrowser:j,hasFlags:F,hasNotify:q,identity:n,platformGate:p,queues:u,serverContent:Qt({agents:d,containers:y,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:j,hasFlags:F,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:q,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:n,queues:u,schema:i,storageRuleBuckets:w.rules.map(se=>se.bucket),useUmbrella:T,workflows:c}),storageRulesMetadata:w,usesSandbox:C.usesSandboxBrowser||C.usesSandboxContainer,useUmbrella:T,workflows:c}},xt=new Set(["delete","get","head","options","patch","post","put"]),Ir=new Set(["handler","stream"]),Tr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Qe=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Lr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!o.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},kr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return Lr(s)},Dr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Qe.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&Qe.has(s.getText()))return!0}return!1},Or=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||!Ir.has(r.getName()))return;const i=kr(s);if(!i||!Tr.test(i.path))return;const n=s.getArguments()[0],a=n!==void 0&&(o.isArrowFunction(n)||o.isFunctionExpression(n))&&Dr(n);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Cr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=Or(i,t);n&&s.push(n)}return s},Fr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Cr(i,E(t,r)))}return s},Kr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Rr=(e,t)=>{if(!Kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)||D(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Mr=(e,t)=>N(e,t,Rr),jr=new Set(["generateText","streamText"]),zr=new Set(["messages","prompt","system"]),qr=[{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"]}],Br=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const i of qr)if(i.methods.has(s)&&i.prefixes.some(n=>r===n||r.startsWith(`${n}.`)))return`${r}.${s}`},Ur=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Br(t);if(s!==void 0)return s}},Vr=e=>{const t=new Set,s=e.getFirstAncestor(n=>o.isArrowFunction(n)||o.isFunctionExpression(n)||o.isFunctionDeclaration(n)),[r]=s?.getParameters()??[],i=r?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const n of i.getElements()){const a=n.getPropertyNameNode()?.getText()??n.getName(),c=n.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Wr=e=>{if($s(e))return!0;const t=Vr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},_r=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!zr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Wr(s))return!0}return!1},Gr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());if(i===void 0||!jr.has(i))continue;const[n]=r.getArguments();if(n===void 0||!o.isObjectLiteralExpression(n))continue;let a;for(const c of n.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=Ur(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(r),file:t,line:r.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:_r(n)})}return s},Hr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Gr(i,E(t,r)))}return s},Qr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},Jr=(e,t)=>{if(!Qr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Xr=(e,t)=>N(e,t,Jr),Et=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),Zr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!o.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:Et(r)}},Yr=e=>{const t=[];let s=!1,r=e;for(;o.isCallExpression(r);){const i=r.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&o.isObjectLiteralExpression(n)?(t.push(n),s||=Et(n)):s=!0}r=i.getExpression()}return{objects:t,opaque:s}},yt=(e,t)=>t?Yr(t):Zr(e),en=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),tn=/\.check\(|\.meta\(|length|max/iu,sn=/\bv\.any\s*\(/u,rn=/\bv\.string\s*\(/u,nn=e=>sn.test(e),on=e=>rn.test(e)&&!tn.test(e),an=e=>{const t=[],s=[];for(const r of e)for(const i of r.getProperties()){if(!o.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!n)continue;const a=n.getText(),c=i.getName();nn(a)?t.push(c):on(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},cn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(r?.visibility!=="public")return;const{objects:i}=yt(s,r.receiver),{anyArgs:n,unboundedStringArgs:a}=an(i);if(!(n.length===0&&a.length===0))return{anyArgs:n,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},ln=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=cn(i,t);n&&s.push(n)}return s},un=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ln(i,E(t,r)))}return s},ge=e=>e?.getKind()===l.TrueKeyword,dn=e=>e?.getKind()===l.FalseKeyword,gn=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,pn=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),fn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),mn=e=>e!==void 0&&o.isCallExpression(e)&&pn.has(A(e.getExpression())??""),hn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),xn=e=>{const t=$(e,"advanced"),s=$(e,"emailAndPassword"),r=$(e,"session");return{analyzable:!0,disableCsrfCheck:ge($(t,"disableCSRFCheck")),emailPasswordEnabled:ge($(s,"enabled")),requireEmailVerification:ge($(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:fn($(e,"plugins"))&&mn($(e,"database")),secureCookiesDisabled:dn($(t,"useSecureCookies")),sessionFreshAgeZero:gn($(r,"freshAge")),trustedOriginsWildcard:hn($(e,"trustedOrigins"))}},En=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),yn=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(n=>o.isSpreadAssignment(n)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!r?xn(s):En();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...i}},$n=(e,t)=>N(e,t,yn),vn=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},bn=(e,t,s)=>{const r=vn(e.getExpression(),s);if(r===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!I(i)||D(i))&&!(s.requireUnmodifiedReach===!0&&!vs(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:r}},Nn=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const n=bn(i,t,s);n&&r.push(n)}return r},te=(e,t,s)=>{const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...Nn(n,E(t,i),s))}return r},Sn=new Set(["content","pdf","scrape","screenshot"]),An=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Sn}),wn=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Pn=new Set(["RateLimiter"]),In=new Set(["extend"]),$t=e=>{const t=[],s=[];let r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(n);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},Je=e=>e&&o.isObjectLiteralExpression(e)?$t(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Tn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&o.isObjectLiteralExpression(r)?r:void 0},Ln=e=>{if(o.isObjectLiteralExpression(e))return e;if(o.isParenthesizedExpression(e)){const t=e.getExpression();return o.isObjectLiteralExpression(t)?t:void 0}return o.isBlock(e)?Tn(e):void 0},kn=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&Ln(t.getBody());return s?$t(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());i!==void 0&&(wn.has(i)?s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])}):In.has(i)&&s.push({callee:i,file:t,line:r.getStartLineNumber(),...kn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(l.NewExpression)){const i=A(r.getExpression());i===void 0||!Pn.has(i)||s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])})}return s},On=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(i,E(t,r)))}return s},Xe="ctx.containers.",Cn=e=>{if(!e.startsWith(Xe))return!1;const t=e.slice(Xe.length);return t.length>0&&!t.includes(".")},Fn=(e,t)=>te(e,t,{argIndex:0,matchReceiver:Cn,methods:new Set(["get"])}),Kn=new Set(["allow","deny","setAllowed"]),Rn=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Mn=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Rn(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},jn=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Kn.has(s.getName()))return;const r=s.getExpression();if(!(!o.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},zn=(e,t)=>Mn(e,t)??jn(e,t),qn=(e,t)=>N(e,t,zn),Bn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Un=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Bn.has(s)?s:void 0},Vn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(o.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(r)){const i=r.getName();t.push(i);const n=r.getInitializer();n&&o.isStringLiteral(n)&&n.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r)||o.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Wn=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=Un(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?Vn(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},_n=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Gn=new Set(["dbRateLimit","rateLimit"]),Hn=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Qn=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const r=_n.get(s);if(r!==void 0)return{callee:s,exportName:x(e),failOpen:Hn(e.getArguments()[r]),file:t,limitName:Gn.has(s)?gt(e):"",line:e.getStartLineNumber()}},Jn=(e,t)=>N(e,t,Qn),Xn=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ds(t.getExpression())},Zn=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Yn=(e,t)=>{if(!Xn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),n=Zn(r);if(!(i.length===0||n===void 0))return{defaultValue:n,exportName:x(e),file:t,key:i,line:e.getStartLineNumber()}},ei=(e,t)=>N(e,t,Yn),ti=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},si=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ri=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression))ti(a)&&s.push({file:n,indexName:si(a),line:a.getStartLineNumber()})}return s},ni=new Set(["delete","get","head","options","patch","post","put"]),ii=new Set(["handler","stream"]),oi=new Set(["runAction","runMutation"]),ai=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,Ze=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,Ye=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return o.isIdentifier(r)?r.getText():void 0;if(o.isObjectBindingPattern(r)){for(const i of r.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const n=i.getNameNode();return o.isIdentifier(n)?n.getText():void 0}}},et=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&r.unshift(s);for(const i of r){const n=i.getExpression();if(!o.isPropertyAccessExpression(n))continue;const a=n.getName(),c=n.getExpression();if(oi.has(a)&&Q(c,t))return a;if(ai.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},tt=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(l.PropertyAccessExpression))if(r.getName()==="auth"&&Q(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getNameNode();if(!(!o.isObjectBindingPattern(i)||!Q(r.getInitializer(),t))){for(const n of i.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="auth")return!0}}return!1},ci=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ii.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))return;const i=r.getName();if(ni.has(i)){const n=r.getExpression();return o.isIdentifier(n)&&n.getText()==="httpRoute"?i.toUpperCase():void 0}s=r.getExpression()}},li=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ze(e.getArguments()[0]),u=c&&Ye(c,!0);if(!c||u===void 0)return;const d=et(c,u);return d===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:tt(c,u),sideEffect:d}}const r=ci(e);if(r===void 0)return;const i=Ze(e.getArguments()[0]),n=i&&Ye(i,!1);if(!i||n===void 0)return;const a=et(i,n);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:tt(i,n),sideEffect:a}},ui=(e,t)=>N(e,t,li),di=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),gi=new Set(["append","set"]),he=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():"",vt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",st=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(s=>di.has(he(s.getExpression()))&&Ns(s,t)),pi=(e,t)=>{if(st(e,t))return!0;const s=ee(e);return s!==void 0&&st(s,t)},me=(e,t)=>bs(e,t)&&!pi(e,t),fi=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ee(e);return t!==void 0&&o.isNewExpression(t)&&he(t.getExpression())==="Headers"},J=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ee(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},xe=(e,t,s)=>{for(const r of e.getProperties())if(o.isPropertyAssignment(r)){const i=r.getInitializer();i!==void 0&&me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:vt(r.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(r)){const i=r.getNameNode();me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(r)){const i=J(r.getExpression());i!==void 0&&xe(i,t,s)}},bt=(e,t)=>{const s=J(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!o.isPropertyAssignment(r))return;const i=J(r.getInitializer());i!==void 0&&xe(i,"response-init",t)},mi=(e,t)=>{const s=he(e.getExpression());if(s==="Response")bt(e.getArguments()[1],t);else if(s==="Headers"){const r=J(e.getArguments()[0]);r!==void 0&&xe(r,"headers-ctor",t)}},hi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const r=s.getName(),i=s.getExpression();if(r==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){bt(e.getArguments()[1],t);return}if(gi.has(r)&&fi(i)){const n=e.getArguments()[1];n!==void 0&&me(n,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:vt(e.getArguments()[0]),line:n.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},xi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))mi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))hi(s,t)},Ei=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=As(e.getArguments()[0]);if(r===void 0)return[];const i=r.getParameters()[1];if(i===void 0)return[];const n=i.getNameNode();if(!o.isIdentifier(n))return[];const a=[];return xi(r,{exportName:x(e),relativePath:t,requestName:n.getText(),rows:a}),a},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression))s.push(...Ei(r,t));return s},$i=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(i,E(t,r)))}return s},vi=new Set(["auth","context.auth","ctx.auth"]),bi="userId",Ni=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},Si=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of r.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[n]=i.getArguments();return n&&o.isObjectLiteralExpression(n)?Ni(n):void 0}},rt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return vi.has(e.getExpression().getText())?e:void 0},Ai=e=>{if(o.isPropertyAccessExpression(e)&&rt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&rt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},wi=(e,t,s)=>{const r=[];for(const i of e.getDescendants()){const n=Ai(i);n!==void 0&&r.push({declared:n===bi||s.has(n),exportName:x(i),file:t,key:n,line:i.getStartLineNumber()})}return r},Pi=(e,t)=>{const s=Si(e,t);if(s===void 0)return[];const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...wi(n,E(t,i),s))}return r},Ii=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=$(s,"key");if(!(!r||!I(r)||D(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Ti=(e,t)=>N(e,t,Ii),Li=new Set(["delete","get","getRaw","getWithMetadata","put"]),ki=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Li}),Di=new Set(["queue","send"]),nt=new Set(["bcc","cc","to"]),Oi=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Di.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Ci=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return nt.has(t.getName())&&I(r)&&!D(r)}if(!o.isPropertyAssignment(t)||!nt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&I(s)&&!D(s)}):!1,Fi=(e,t)=>{const s=Oi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Ci(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Ki=(e,t)=>N(e,t,Fi),Ri=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Mi=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},ji=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return zs(s.getExpression())?s:void 0},zi=e=>{const t=ji(e),s=t===void 0?void 0:Mi(t);if(s===void 0)return[];const r=e.getNameNode(),i=o.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(n=>Ri(n)).map(n=>({exportName:i,file:"lunora/mutators.ts",line:n.getStartLineNumber()}))},qi=e=>e.getVariableDeclarations().flatMap(t=>zi(t)),Bi=(e,t)=>{const s=g(t,js);if(!b(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return qi(r)},Ui=new Set(["delete","get","patch"]),Vi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Wi=new Set(["auth","identity","session","user"]),_i=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Gi=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!R(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},Hi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const r=s.getNameNode();return o.isIdentifier(r)?r.getText():void 0},Qi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ji=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Xi=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Qi(s.getExpression(),t)&&Ji(s.getThenStatement())),Zi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))continue;const i=r.getName();if(!Ui.has(i))continue;const n=r.getExpression();if(!(R(n)||o.isPropertyAccessExpression(n)&&R(n.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&o.isIdentifier(a)&&a.getText()===t)return i}},Yi=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},eo=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Yi(s)==="ctx")),to=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>_i.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),so=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Vi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Wi.has(t.getName()))return!0}return eo(e)||to(e)},ro=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=so(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const y=Gi(d);if(y===void 0)continue;const w=Hi(d);if(w===void 0||c.has(w)||!Xi(i,w))continue;const p=Zi(i,w);p!==void 0&&(c.add(w),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:y,usesRls:n,visibility:r.visibility}))}return u},no=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ro(c,n))}return s},io=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),oo=new Set(["insert","insertManyUnsafe","patch","replace"]),ao=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!oo.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},co=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())o.isObjectLiteralExpression(r)&&s.push(r);return s},lo=(e,t,s,r)=>{const i=[];for(const n of e.getProperties()){let a,c;o.isPropertyAssignment(n)?(a=n.getName(),c=n.getInitializer()):o.isShorthandPropertyAssignment(n)&&(a=n.getName(),c=n.getNameNode()),!(a===void 0||c===void 0||!io.has(a))&&I(c)&&!D(c)&&i.push({exportName:x(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return i},uo=(e,t)=>{const s=ao(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?co(r,s).flatMap(i=>lo(i,s,e,t)):[]},go=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const n of uo(i,t)){const a=s(n.exportName);r.push(a===void 0?n:{...n,visibility:a})}return r},po=(e,t,s=[])=>{const r=[],i=new Map(s.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));for(const n of h(t)){const a=e.getSourceFile(n)??e.addSourceFileAtPath(n),c=E(t,n);r.push(...go(a,c,u=>i.get(`${c}:${u}`)))}return r},fo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?mo(t.getInitializer()):void 0},xo=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!fo.has(s))return;const[r]=e.getArguments(),i=r&&o.isObjectLiteralExpression(r)?ho(r):void 0;return{callee:s,exportName:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Eo=(e,t)=>N(e,t,xo),yo=new Set(["defineQueue","defineWorkflow"]),$o=new Set(["run","runAction","runMutation","runQuery"]),vo=new Set(["api","internal"]),bo=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},No=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(o.isArrowFunction(r)||o.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},St=(e,t)=>e===t||e.startsWith(`${t}.`),At=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},it=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},wt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>it(s));return o.isIdentifier(e)&&it(e)&&t.push(e),t},So=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Ao=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(l.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const i=r.getInitializer(),n=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;n&&o.isIdentifier(n)&&s.push(`${n.getText()}.body`)}return s},wo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:Ao(e),i=new Set,n=a=>At(a).some(c=>r.some(u=>St(c.getText(),u)))?!0:wt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&n(c))for(const u of So(a))i.add(u)}return{names:i,prefixes:r}},Po=(e,t)=>At(e).some(s=>t.prefixes.some(r=>St(s.getText(),r)))?!0:wt(e).some(s=>t.names.has(s.getText())),Io=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!o.isIdentifier(s)||!vo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},To=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const i=wo(e,t,r),n=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!$o.has(c.getName())||c.getExpression().getText()!==r)continue;const u=a.getArguments()[1];if(!u||!Po(u,i))continue;const d=Io(a.getArguments()[0]);d!==void 0&&n.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return n},Lo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=bo(r);if(i===void 0||!yo.has(i))continue;const n=No(r);n!==void 0&&s.push(...To(n,i==="defineQueue"?"queue":"workflow",t))}return s},ko=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Lo(i,E(t,r)))}return s},ot={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},at=new Set(["account","credential","member","passkey","session","user"]),Do=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Oo=e=>{const t=Do(e).at(-1);if(!t)return!1;const s=t.endsWith("s")?t.slice(0,-1):t;return at.has(t)||at.has(s)},Co=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Fo=(e,t)=>{const{objects:s,opaque:r}=yt(e,t);return en(s).some(i=>Co(i))?!0:r?void 0:!1},Ee=e=>{const t=e.getExpression();if(o.isIdentifier(t))return t.getText();if(o.isPropertyAccessExpression(t))return t.getName()},Ko=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ro=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&o.isCallExpression(t)?t:void 0},H={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mo=e=>{const t=Ro(e),s=t?Ee(t):void 0;if(t&&s==="protectPublic"){const r=Ko(t);return{...H,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in ot?{...H,[ot[s]]:!0}:H},jo=e=>{const t={...H};let s=e;for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))break;const i=r.getName()==="use"?s.getArguments()[0]:void 0;if(i){const n=Mo(i);t.usesCaptcha||=n.usesCaptcha,t.usesEmailGate||=n.usesEmailGate,t.usesMask||=n.usesMask,t.usesRateLimit||=n.usesRateLimit,t.usesRls||=n.usesRls}s=r.getExpression()}return t},zo=new Set(["insert","insertMany","insertManyUnsafe","replace"]),qo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!zo.has(t.getName()))return!1;const s=t.getExpression();if(!(o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!r||!(o.isStringLiteral(r)||o.isNoSubstitutionTemplateLiteral(r))?!1:Oo(r.getLiteralText())},Bo=new Set(["create","runAfter","runAt","send","sendBatch"]),Uo=new Set(["queues","scheduler","workflows"]),Vo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Bo.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Uo.has(s.getName())){const r=s.getExpression();if(o.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Pt=new Set(["generateObject","generateText","streamObject","streamText"]),_o=e=>{const t=Ee(e);return t!==void 0&&Pt.has(t)},Go=e=>{const t=Ee(e);if(t===void 0||!Pt.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(r=>o.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Ho=new Set(["log","span","trace"]),Qo=new Set(["ai"]),Jo=new Set(["email","mail"]),Xo=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),pe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"}),Zo=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Yo=new Set(["every","filter","flatMap","forEach","map","some"]),ea=new Set(["all","allSettled","race"]),ta=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const r=s.getName();if(Yo.has(r))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&ea.has(r))return t},sa=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Zo.has(t.getKind())){const s=ta(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},ra=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const r=s.getParent();if(!o.isCallExpression(r)||r.getExpression()!==s)return!1;t=r}},na=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ia=e=>{let t=!1,s=!0;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Xo.has(r.getName()))continue;const i=r.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const n=na(r);n&&(t=!0,!sa(n)&&!ra(n)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},oa=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="Error"}),ct="lunora-advisor-exempt",aa=/^[\s*/]+/u,ca=/[\w-]/u,la=e=>{const t=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
5
+ Install them with your package manager, then re-run codegen.`)},lr="env.ts",ur=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},dr=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},gr=e=>{if(o.isIdentifier(e))return ur(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&dr(t)}return!1},pr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!gr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},fr=(e,t)=>{const s=g(t,lr);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=pr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},mr=e=>{const t=r=>o.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getInitializer(),n=r.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(n)))for(const a of n.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},hr=(e,t)=>{const s=Object.fromEntries(de.map(r=>[r.key,!1]));for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=mr(i);for(const c of de)if(!s[c.key]){if(n.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(de.every(c=>s[c.key]))break}return s},xr=["providerSubscriptionId","state"],Er=["providerEventId","processedAt"],He=(e,t)=>t.every(s=>s in e.shape),yr=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&He(t,xr)&&He(s,Er)},$r=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),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:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),ht="identity.ts",vr=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return Y(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},br=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(l.ImportDeclaration);return r!==void 0&&Y(r.getModuleSpecifierValue())}return!1},Nr=e=>{if(o.isIdentifier(e))return vr(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&br(t)}return!1},Sr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==l.CallExpression||!Nr(r.getExpression()))continue;const i=s.getNameNode();if(!o.isIdentifier(i))throw Z(i,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:i.getText()})}return t},Ar=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Sr(r);if(i.length!==0){if(i.length>1)throw Z(r,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(n=>n.exportName).join(", ")}); exactly one is allowed`);return i[0]}},wr=(e,t)=>{const s=new Map,r=new Map,i=new Map;for(const n of e)s.set(n.name,`workflow "${n.exportName}"`),r.set(n.bindingName,`workflow "${n.exportName}"`),i.set(n.className,`workflow "${n.exportName}"`);for(const n of t){const a=s.get(n.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${n.name}": produced by both ${a} and agent "${n.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(n.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${n.bindingName}": produced by both ${c} and agent "${n.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(n.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${n.className}": produced by both ${u} and agent "${n.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Pr=e=>{const{lunoraDirectory:t,project:s,projectRoot:r,schema:i}=e,n=Ar(s,t),a=fr(s,t),c=xs(s,t),u=fs(s,t),d=Gt(s,t);wr(c,d);const y=Ht(s,t),w=hs(s,t),p=Es(hr(s,t),ys(r,e.target)),v=p.usage,O=ms(s,t),j=v.browser||O.usesSandboxBrowser,z=ps(r),U=z??new Set,T=U.has("lunorash");cr(i,z);const C=b(g(t,"flags.ts")),q=b(g(t,"notify.ts"));return{agents:d,containers:y,dataModelContent:Jt(i),declaredDependencies:z,dependencies:U,env:a,featureUsage:v,hasBrowser:j,hasFlags:C,hasNotify:q,identity:n,platformGate:p,queues:u,serverContent:Qt({agents:d,containers:y,env:a,hasAccessFacade:v.access,hasAi:v.ai,hasAnalytics:v.analytics,hasBrowser:j,hasFlags:C,hasHyperdrive:v.hyperdrive,hasImages:v.images,hasKv:v.kv,hasNotify:q,hasPayments:v.payments,hasPipelines:v.pipelines,hasR2sql:v.r2sql,hasX402:v.x402,identity:n,queues:u,schema:i,storageRuleBuckets:w.rules.map(se=>se.bucket),useUmbrella:T,workflows:c}),storageRulesMetadata:w,usesSandbox:O.usesSandboxBrowser||O.usesSandboxContainer,useUmbrella:T,workflows:c}},xt=new Set(["delete","get","head","options","patch","post","put"]),Ir=new Set(["handler","stream"]),Tr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Qe=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Lr=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!o.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},kr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return Lr(s)},Dr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(Qe.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&Qe.has(s.getText()))return!0}return!1},Fr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=s.getExpression();if(!o.isPropertyAccessExpression(r)||!Ir.has(r.getName()))return;const i=kr(s);if(!i||!Tr.test(i.path))return;const n=s.getArguments()[0],a=n!==void 0&&(o.isArrowFunction(n)||o.isFunctionExpression(n))&&Dr(n);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Or=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=Fr(i,t);n&&s.push(n)}return s},Cr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Or(i,E(t,r)))}return s},Kr=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Rr=(e,t)=>{if(!Kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)||D(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Mr=(e,t)=>N(e,t,Rr),jr=new Set(["generateText","streamText"]),zr=new Set(["messages","prompt","system"]),qr=[{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"]}],Br=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const i of qr)if(i.methods.has(s)&&i.prefixes.some(n=>r===n||r.startsWith(`${n}.`)))return`${r}.${s}`},Ur=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Br(t);if(s!==void 0)return s}},Vr=e=>{const t=new Set,s=e.getFirstAncestor(n=>o.isArrowFunction(n)||o.isFunctionExpression(n)||o.isFunctionDeclaration(n)),[r]=s?.getParameters()??[],i=r?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const n of i.getElements()){const a=n.getPropertyNameNode()?.getText()??n.getName(),c=n.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Wr=e=>{if($s(e))return!0;const t=Vr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},_r=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!zr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Wr(s))return!0}return!1},Gr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());if(i===void 0||!jr.has(i))continue;const[n]=r.getArguments();if(n===void 0||!o.isObjectLiteralExpression(n))continue;let a;for(const c of n.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=Ur(c),a!==void 0))break;a!==void 0&&s.push({exportName:x(r),file:t,line:r.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:_r(n)})}return s},Hr=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Gr(i,E(t,r)))}return s},Qr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},Jr=(e,t)=>{if(!Qr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!I(s)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Xr=(e,t)=>N(e,t,Jr),Et=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),Zr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!o.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:Et(r)}},Yr=e=>{const t=[];let s=!1,r=e;for(;o.isCallExpression(r);){const i=r.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const n=r.getArguments()[0];n&&o.isObjectLiteralExpression(n)?(t.push(n),s||=Et(n)):s=!0}r=i.getExpression()}return{objects:t,opaque:s}},yt=(e,t)=>t?Yr(t):Zr(e),en=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),tn=/\.check\(|\.meta\(|length|max/iu,sn=/\bv\.any\s*\(/u,rn=/\bv\.string\s*\(/u,nn=e=>sn.test(e),on=e=>rn.test(e)&&!tn.test(e),an=e=>{const t=[],s=[];for(const r of e)for(const i of r.getProperties()){if(!o.isPropertyAssignment(i))continue;const n=i.getInitializer();if(!n)continue;const a=n.getText(),c=i.getName();nn(a)?t.push(c):on(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},cn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(r?.visibility!=="public")return;const{objects:i}=yt(s,r.receiver),{anyArgs:n,unboundedStringArgs:a}=an(i);if(!(n.length===0&&a.length===0))return{anyArgs:n,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},ln=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=cn(i,t);n&&s.push(n)}return s},un=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ln(i,E(t,r)))}return s},ge=e=>e?.getKind()===l.TrueKeyword,dn=e=>e?.getKind()===l.FalseKeyword,gn=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,pn=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),fn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),mn=e=>e!==void 0&&o.isCallExpression(e)&&pn.has(A(e.getExpression())??""),hn=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),xn=e=>{const t=$(e,"advanced"),s=$(e,"emailAndPassword"),r=$(e,"session");return{analyzable:!0,disableCsrfCheck:ge($(t,"disableCSRFCheck")),emailPasswordEnabled:ge($(s,"enabled")),requireEmailVerification:ge($(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:fn($(e,"plugins"))&&mn($(e,"database")),secureCookiesDisabled:dn($(t,"useSecureCookies")),sessionFreshAgeZero:gn($(r,"freshAge")),trustedOriginsWildcard:hn($(e,"trustedOrigins"))}},En=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),yn=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(n=>o.isSpreadAssignment(n)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!r?xn(s):En();return{exportName:x(e),file:t,line:e.getStartLineNumber(),...i}},$n=(e,t)=>N(e,t,yn),vn=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},bn=(e,t,s)=>{const r=vn(e.getExpression(),s);if(r===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!I(i)||D(i))&&!(s.requireUnmodifiedReach===!0&&!vs(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:r}},Nn=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const n=bn(i,t,s);n&&r.push(n)}return r},te=(e,t,s)=>{const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...Nn(n,E(t,i),s))}return r},Sn=new Set(["content","pdf","scrape","screenshot"]),An=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Sn}),wn=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Pn=new Set(["RateLimiter"]),In=new Set(["extend"]),$t=e=>{const t=[],s=[];let r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(n);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},Je=e=>e&&o.isObjectLiteralExpression(e)?$t(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Tn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&o.isObjectLiteralExpression(r)?r:void 0},Ln=e=>{if(o.isObjectLiteralExpression(e))return e;if(o.isParenthesizedExpression(e)){const t=e.getExpression();return o.isObjectLiteralExpression(t)?t:void 0}return o.isBlock(e)?Tn(e):void 0},kn=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&Ln(t.getBody());return s?$t(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=A(r.getExpression());i!==void 0&&(wn.has(i)?s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])}):In.has(i)&&s.push({callee:i,file:t,line:r.getStartLineNumber(),...kn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(l.NewExpression)){const i=A(r.getExpression());i===void 0||!Pn.has(i)||s.push({callee:i,file:t,line:r.getStartLineNumber(),...Je(r.getArguments()[0])})}return s},Fn=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(i,E(t,r)))}return s},Xe="ctx.containers.",On=e=>{if(!e.startsWith(Xe))return!1;const t=e.slice(Xe.length);return t.length>0&&!t.includes(".")},Cn=(e,t)=>te(e,t,{argIndex:0,matchReceiver:On,methods:new Set(["get"])}),Kn=new Set(["allow","deny","setAllowed"]),Rn=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Mn=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Rn(e)))return{detail:"enableInternet: true",exportName:x(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},jn=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Kn.has(s.getName()))return;const r=s.getExpression();if(!(!o.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:x(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},zn=(e,t)=>Mn(e,t)??jn(e,t),qn=(e,t)=>N(e,t,zn),Bn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Un=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Bn.has(s)?s:void 0},Vn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(o.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(r)){const i=r.getName();t.push(i);const n=r.getInitializer();n&&o.isStringLiteral(n)&&n.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(r)||o.isMethodDeclaration(r)||o.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Wn=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=Un(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?Vn(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},_n=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Gn=new Set(["dbRateLimit","rateLimit"]),Hn=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Qn=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const r=_n.get(s);if(r!==void 0)return{callee:s,exportName:x(e),failOpen:Hn(e.getArguments()[r]),file:t,limitName:Gn.has(s)?gt(e):"",line:e.getStartLineNumber()}},Jn=(e,t)=>N(e,t,Qn),Xn=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ds(t.getExpression())},Zn=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Yn=(e,t)=>{if(!Xn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),n=Zn(r);if(!(i.length===0||n===void 0))return{defaultValue:n,exportName:x(e),file:t,key:i,line:e.getStartLineNumber()}},ei=(e,t)=>N(e,t,Yn),ti=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},si=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ri=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression))ti(a)&&s.push({file:n,indexName:si(a),line:a.getStartLineNumber()})}return s},ni=new Set(["delete","get","head","options","patch","post","put"]),ii=new Set(["handler","stream"]),oi=new Set(["runAction","runMutation"]),ai=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,Ze=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,Ye=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return o.isIdentifier(r)?r.getText():void 0;if(o.isObjectBindingPattern(r)){for(const i of r.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const n=i.getNameNode();return o.isIdentifier(n)?n.getText():void 0}}},et=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&r.unshift(s);for(const i of r){const n=i.getExpression();if(!o.isPropertyAccessExpression(n))continue;const a=n.getName(),c=n.getExpression();if(oi.has(a)&&Q(c,t))return a;if(ai.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},tt=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(l.PropertyAccessExpression))if(r.getName()==="auth"&&Q(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(l.VariableDeclaration)){const i=r.getNameNode();if(!(!o.isObjectBindingPattern(i)||!Q(r.getInitializer(),t))){for(const n of i.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="auth")return!0}}return!1},ci=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ii.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))return;const i=r.getName();if(ni.has(i)){const n=r.getExpression();return o.isIdentifier(n)&&n.getText()==="httpRoute"?i.toUpperCase():void 0}s=r.getExpression()}},li=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=Ze(e.getArguments()[0]),u=c&&Ye(c,!0);if(!c||u===void 0)return;const d=et(c,u);return d===void 0?void 0:{exportName:x(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:tt(c,u),sideEffect:d}}const r=ci(e);if(r===void 0)return;const i=Ze(e.getArguments()[0]),n=i&&Ye(i,!1);if(!i||n===void 0)return;const a=et(i,n);return a===void 0?void 0:{exportName:x(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:tt(i,n),sideEffect:a}},ui=(e,t)=>N(e,t,li),di=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),gi=new Set(["append","set"]),he=e=>o.isIdentifier(e)?e.getText():o.isPropertyAccessExpression(e)?e.getName():"",vt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",st=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(s=>di.has(he(s.getExpression()))&&Ns(s,t)),pi=(e,t)=>{if(st(e,t))return!0;const s=ee(e);return s!==void 0&&st(s,t)},me=(e,t)=>bs(e,t)&&!pi(e,t),fi=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ee(e);return t!==void 0&&o.isNewExpression(t)&&he(t.getExpression())==="Headers"},J=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ee(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},xe=(e,t,s)=>{for(const r of e.getProperties())if(o.isPropertyAssignment(r)){const i=r.getInitializer();i!==void 0&&me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:vt(r.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(r)){const i=r.getNameNode();me(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(r)){const i=J(r.getExpression());i!==void 0&&xe(i,t,s)}},bt=(e,t)=>{const s=J(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!o.isPropertyAssignment(r))return;const i=J(r.getInitializer());i!==void 0&&xe(i,"response-init",t)},mi=(e,t)=>{const s=he(e.getExpression());if(s==="Response")bt(e.getArguments()[1],t);else if(s==="Headers"){const r=J(e.getArguments()[0]);r!==void 0&&xe(r,"headers-ctor",t)}},hi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const r=s.getName(),i=s.getExpression();if(r==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){bt(e.getArguments()[1],t);return}if(gi.has(r)&&fi(i)){const n=e.getArguments()[1];n!==void 0&&me(n,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:vt(e.getArguments()[0]),line:n.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},xi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))mi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))hi(s,t)},Ei=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=As(e.getArguments()[0]);if(r===void 0)return[];const i=r.getParameters()[1];if(i===void 0)return[];const n=i.getNameNode();if(!o.isIdentifier(n))return[];const a=[];return xi(r,{exportName:x(e),relativePath:t,requestName:n.getText(),rows:a}),a},yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression))s.push(...Ei(r,t));return s},$i=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yi(i,E(t,r)))}return s},vi=new Set(["auth","context.auth","ctx.auth"]),bi="userId",Ni=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},Si=(e,t)=>{const s=g(t,ht);if(!b(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of r.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[n]=i.getArguments();return n&&o.isObjectLiteralExpression(n)?Ni(n):void 0}},rt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return vi.has(e.getExpression().getText())?e:void 0},Ai=e=>{if(o.isPropertyAccessExpression(e)&&rt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&rt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},wi=(e,t,s)=>{const r=[];for(const i of e.getDescendants()){const n=Ai(i);n!==void 0&&r.push({declared:n===bi||s.has(n),exportName:x(i),file:t,key:n,line:i.getStartLineNumber()})}return r},Pi=(e,t)=>{const s=Si(e,t);if(s===void 0)return[];const r=[];for(const i of h(t)){const n=e.getSourceFile(i)??e.addSourceFileAtPath(i);r.push(...wi(n,E(t,i),s))}return r},Ii=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=$(s,"key");if(!(!r||!I(r)||D(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber()}},Ti=(e,t)=>N(e,t,Ii),Li=new Set(["delete","get","getRaw","getWithMetadata","put"]),ki=(e,t)=>te(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Li}),Di=new Set(["queue","send"]),nt=new Set(["bcc","cc","to"]),Fi=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Di.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Oi=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return nt.has(t.getName())&&I(r)&&!D(r)}if(!o.isPropertyAssignment(t)||!nt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&I(s)&&!D(s)}):!1,Ci=(e,t)=>{const s=Fi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Oi(r)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},Ki=(e,t)=>N(e,t,Ci),Ri=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Mi=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},ji=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return zs(s.getExpression())?s:void 0},zi=e=>{const t=ji(e),s=t===void 0?void 0:Mi(t);if(s===void 0)return[];const r=e.getNameNode(),i=o.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(n=>Ri(n)).map(n=>({exportName:i,file:"lunora/mutators.ts",line:n.getStartLineNumber()}))},qi=e=>e.getVariableDeclarations().flatMap(t=>zi(t)),Bi=(e,t)=>{const s=g(t,js);if(!b(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return qi(r)},Ui=new Set(["delete","get","patch"]),Vi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Wi=new Set(["auth","identity","session","user"]),_i=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),Gi=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!R(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},Hi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const r=s.getNameNode();return o.isIdentifier(r)?r.getText():void 0},Qi=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Ji=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Xi=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Qi(s.getExpression(),t)&&Ji(s.getThenStatement())),Zi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))continue;const i=r.getName();if(!Ui.has(i))continue;const n=r.getExpression();if(!(R(n)||o.isPropertyAccessExpression(n)&&R(n.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&o.isIdentifier(a)&&a.getText()===t)return i}},Yi=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},eo=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Yi(s)==="ctx")),to=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>_i.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),so=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Vi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Wi.has(t.getName()))return!0}return eo(e)||to(e)},ro=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=so(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const y=Gi(d);if(y===void 0)continue;const w=Hi(d);if(w===void 0||c.has(w)||!Xi(i,w))continue;const p=Zi(i,w);p!==void 0&&(c.add(w),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:y,usesRls:n,visibility:r.visibility}))}return u},no=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ro(c,n))}return s},io=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),oo=new Set(["insert","insertManyUnsafe","patch","replace"]),ao=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!oo.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},co=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())o.isObjectLiteralExpression(r)&&s.push(r);return s},lo=(e,t,s,r)=>{const i=[];for(const n of e.getProperties()){let a,c;o.isPropertyAssignment(n)?(a=n.getName(),c=n.getInitializer()):o.isShorthandPropertyAssignment(n)&&(a=n.getName(),c=n.getNameNode()),!(a===void 0||c===void 0||!io.has(a))&&I(c)&&!D(c)&&i.push({exportName:x(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return i},uo=(e,t)=>{const s=ao(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?co(r,s).flatMap(i=>lo(i,s,e,t)):[]},go=(e,t,s)=>{const r=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const n of uo(i,t)){const a=s(n.exportName);r.push(a===void 0?n:{...n,visibility:a})}return r},po=(e,t,s=[])=>{const r=[],i=new Map(s.map(n=>[`${n.filePath}:${n.exportName}`,n.visibility]));for(const n of h(t)){const a=e.getSourceFile(n)??e.addSourceFileAtPath(n),c=E(t,n);r.push(...go(a,c,u=>i.get(`${c}:${u}`)))}return r},fo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),mo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?mo(t.getInitializer()):void 0},xo=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!fo.has(s))return;const[r]=e.getArguments(),i=r&&o.isObjectLiteralExpression(r)?ho(r):void 0;return{callee:s,exportName:x(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Eo=(e,t)=>N(e,t,xo),yo=new Set(["defineQueue","defineWorkflow"]),$o=new Set(["run","runAction","runMutation","runQuery"]),vo=new Set(["api","internal"]),bo=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},No=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(o.isArrowFunction(r)||o.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},St=(e,t)=>e===t||e.startsWith(`${t}.`),At=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},it=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},wt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>it(s));return o.isIdentifier(e)&&it(e)&&t.push(e),t},So=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Ao=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(l.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const i=r.getInitializer(),n=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;n&&o.isIdentifier(n)&&s.push(`${n.getText()}.body`)}return s},wo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:Ao(e),i=new Set,n=a=>At(a).some(c=>r.some(u=>St(c.getText(),u)))?!0:wt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&n(c))for(const u of So(a))i.add(u)}return{names:i,prefixes:r}},Po=(e,t)=>At(e).some(s=>t.prefixes.some(r=>St(s.getText(),r)))?!0:wt(e).some(s=>t.names.has(s.getText())),Io=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!o.isIdentifier(s)||!vo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},To=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const i=wo(e,t,r),n=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!$o.has(c.getName())||c.getExpression().getText()!==r)continue;const u=a.getArguments()[1];if(!u||!Po(u,i))continue;const d=Io(a.getArguments()[0]);d!==void 0&&n.push({dispatchKind:t,file:s,handlerExport:x(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return n},Lo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=bo(r);if(i===void 0||!yo.has(i))continue;const n=No(r);n!==void 0&&s.push(...To(n,i==="defineQueue"?"queue":"workflow",t))}return s},ko=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Lo(i,E(t,r)))}return s},ot={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},at=new Set(["account","credential","member","passkey","session","user"]),Do=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),Fo=e=>{const t=Do(e).at(-1);if(!t)return!1;const s=t.endsWith("s")?t.slice(0,-1):t;return at.has(t)||at.has(s)},Oo=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Co=(e,t)=>{const{objects:s,opaque:r}=yt(e,t);return en(s).some(i=>Oo(i))?!0:r?void 0:!1},Ee=e=>{const t=e.getExpression();if(o.isIdentifier(t))return t.getText();if(o.isPropertyAccessExpression(t))return t.getName()},Ko=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Ro=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&o.isCallExpression(t)?t:void 0},H={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mo=e=>{const t=Ro(e),s=t?Ee(t):void 0;if(t&&s==="protectPublic"){const r=Ko(t);return{...H,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in ot?{...H,[ot[s]]:!0}:H},jo=e=>{const t={...H};let s=e;for(;o.isCallExpression(s);){const r=s.getExpression();if(!o.isPropertyAccessExpression(r))break;const i=r.getName()==="use"?s.getArguments()[0]:void 0;if(i){const n=Mo(i);t.usesCaptcha||=n.usesCaptcha,t.usesEmailGate||=n.usesEmailGate,t.usesMask||=n.usesMask,t.usesRateLimit||=n.usesRateLimit,t.usesRls||=n.usesRls}s=r.getExpression()}return t},zo=new Set(["insert","insertMany","insertManyUnsafe","replace"]),qo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!zo.has(t.getName()))return!1;const s=t.getExpression();if(!(o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!r||!(o.isStringLiteral(r)||o.isNoSubstitutionTemplateLiteral(r))?!1:Fo(r.getLiteralText())},Bo=new Set(["create","runAfter","runAt","send","sendBatch"]),Uo=new Set(["queues","scheduler","workflows"]),Vo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Bo.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Uo.has(s.getName())){const r=s.getExpression();if(o.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="db":o.isIdentifier(s)&&s.getText()==="db"},Pt=new Set(["generateObject","generateText","streamObject","streamText"]),_o=e=>{const t=Ee(e);return t!==void 0&&Pt.has(t)},Go=e=>{const t=Ee(e);if(t===void 0||!Pt.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(r=>o.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Ho=new Set(["log","span","trace"]),Qo=new Set(["ai"]),Jo=new Set(["email","mail"]),Xo=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),pe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="ctx"}),Zo=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Yo=new Set(["every","filter","flatMap","forEach","map","some"]),ea=new Set(["all","allSettled","race"]),ta=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const r=s.getName();if(Yo.has(r))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&ea.has(r))return t},sa=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Zo.has(t.getKind())){const s=ta(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},ra=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const r=s.getParent();if(!o.isCallExpression(r)||r.getExpression()!==s)return!1;t=r}},na=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},ia=e=>{let t=!1,s=!0;for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Xo.has(r.getName()))continue;const i=r.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const n=na(r);n&&(t=!0,!sa(n)&&!ra(n)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},oa=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const r=s.getExpression();return o.isIdentifier(r)&&r.getText()==="Error"}),ct="lunora-advisor-exempt",aa=/^[\s*/]+/u,ca=/[\w-]/u,la=e=>{const t=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
6
6
  `);for(const s of t.split(`
7
- `)){const r=s.replace(aa,"");if(!r.startsWith(ct))continue;const i=r.slice(ct.length);if(ca.test(i.charAt(0)))continue;const n=i.indexOf("--");return{exempt:!0,exemptReason:(n===-1?"":i.slice(n+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},ua=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},da=(e,t)=>{const s=ua(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const r=s.getSourceFile(),i=s.getText(),n=r.getVariableDeclaration(i)?.getInitializer();return n&&(o.isArrowFunction(n)||o.isFunctionExpression(n))?n:r.getFunction(i)},ga=e=>{let t=!1,s=!1,r=!1,i=!1,n=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(qo(u)&&(n=!0),Vo(u)&&(t=!0),Wo(u)&&(i=!0),_o(u)&&(s=!0),Go(u)&&(r=!0),n&&t&&i&&r)break;const{handlesErrors:a,reachesOutbound:c}=ia(e);return{callsMail:pe(e,Jo),emitsEvent:pe(e,Ho),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||pe(e,Qo),throwsBareError:oa(e),unboundedAiGeneration:r,usesInsertManyUnsafe:i,writesUserTable:n}},pa=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const i=r.receiver?jo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},n=da(e,s);return{...n?ga(n):{},...la(e),...i,analyzableBody:n!==void 0,exportName:e.getName(),file:t,hasEmailArg:Fo(s,r.receiver),kind:r.kind,visibility:r.visibility}},fa=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=pa(i,t);n&&s.push(n)}return s},ma=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fa(i,E(t,r)))}return s},ha=new Set(["dbRateLimit","rateLimit"]),xa=e=>o.isArrowFunction(e)?e.getBody():e,Ea=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!ha.has(s))return;const r=e.getArguments()[2];if(!r)return;const i=$(r,"key");if(!i)return;const n=xa(i);if(!(!I(n)||D(n)))return{callee:s,exportName:x(e),file:t,limitName:gt(e),line:e.getStartLineNumber()}},ya=(e,t)=>N(e,t,Ea),$a=new Set(["findFirst","findFirstOrThrow","findMany","get"]),va=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!$a.has(t.getName()))return;const s=t.getExpression();if(R(s)){const r=e.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&R(s.getExpression()))return s.getName()},ba=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&R(s.getExpression())){const r=t.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Na=e=>{let t=e;for(;o.isAwaitExpression(t)||o.isParenthesizedExpression(t)||o.isNonNullExpression(t)||o.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=Na(e);if(o.isIdentifier(s)){if(t)return;const r=ee(s);return r===void 0?void 0:It(r,!0)}if(o.isCallExpression(s))return va(s)??ba(s)},Sa=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(l.ReturnStatement)){const i=r.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),n=r.getExpression();i===e&&n!==void 0&&s.push(n)}return s},Aa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&ws(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,u=[];for(const d of Sa(i)){const y=It(d);y===void 0||c.has(y)||(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:y,usesMask:a,usesOutput:n,visibility:r.visibility}))}return u},wa=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Aa(c,n))}return s},Pa=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Ia=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=Pa($(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:n.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return i},Ta=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,n))}return s},X=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=X(e.getLeft()),s=X(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},La=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&X(t)!==void 0},ka=/(?:^|\/)__tests__\//u,Da=/\.(?:spec|test)$/u,Oa=e=>ka.test(e)||Da.test(e),Ca=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Fa=(e,t,s)=>Xs(e)?!Oa(s)&&Zs(Ca(t)):!0,Ka=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const n of r){if(La(n))continue;const a=X(n);if(a===void 0)continue;const c=Qs(a);if(c===void 0||!Fa(c,n,t))continue;const u=n.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Js(a)}))}return s},Ra=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ka(i,E(t,r)))}return s},Ma=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=$(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&I(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:n.getStartLineNumber(),table:a.table,visibility:r.visibility})}return i},ja=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ma(c,n))}return s},za=new Set(["query","unsafe"]),qa=e=>{if(!o.isPropertyAccessExpression(e)||!za.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},Ba=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Ua=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Va=(e,t)=>{if(!qa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ba(s)))return{exportName:Ua(e),file:t,line:s.getStartLineNumber()}},Wa=(e,t)=>N(e,t,Va),_a=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ga=e=>{for(const[t,s]of _a)for(const r of s)if(e===r||e.startsWith(r.endsWith("/")?r:`${r}/`))return t},Ha=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of i.getImportDeclarations()){const a=n.getModuleSpecifierValue(),c=Ga(a);c!==void 0&&s.push({file:E(t,r),line:n.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Qa=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ja=(e,t,s=[])=>{const r=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return te(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Qa,requireUnmodifiedReach:!0}).map(i=>{const n=r.get(`${i.file}:${i.exportName}`);return n===void 0?i:{...i,visibility:n}})},Xa=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Za=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ya=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),n==="expiresInSeconds"&&(s=Za(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},ec=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Xa.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},tc=(e,t)=>{const s=ec(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ya(e.getArguments()[s.optionsIndex])}},sc=(e,t)=>N(e,t,tc),rc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),ye=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&rc.has(s)?s:void 0},Tt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Lt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},nc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},$e=(e,t,s,r,i)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${r.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${i.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),ic=(e,t,s)=>{const r=[];for(const i of e.getVariableStatements().filter(n=>n.isExported()))for(const n of i.getDeclarations()){const a=n.getName();if(s.has(`${t}:${a}`)||!Tt(n))continue;const c=ye(n);c!==void 0&&r.push($e(t,a,c,n.getStartLineNumber(),Lt))}return r},oc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const i of e.getExportAssignments().filter(n=>!n.isExportEquals())){const n=ye(i.getExpression());n!==void 0&&r.push($e(t,"default",n,i.getStartLineNumber(),Lt))}return r},ac=(e,t,s)=>{const r=[];for(const i of e.getExportDeclarations().filter(n=>n.getModuleSpecifier()===void 0))for(const n of i.getNamedExports()){const a=n.getAliasNode()?.getText()??n.getName();if(s.has(`${t}:${a}`))continue;const c=n.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Tt(c))continue;const u=ye(c);u!==void 0&&r.push($e(t,a,u,n.getStartLineNumber(),nc))}return r},cc=(e,t,s)=>[...ic(e,t,s),...oc(e,t,s),...ac(e,t,s)],lc=(e,t,s)=>{const r=new Set(s.map(n=>`${n.filePath}:${n.exportName}`)),i=[];for(const n of h(t)){const a=e.getSourceFile(n);a!==void 0&&i.push(...cc(a,E(t,n),r))}return i.toSorted((n,a)=>n.cacheKey.localeCompare(a.cacheKey))},uc=new Set(["when","where"]),fe=new Set(["definePolicy","defineShape"]),dc=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const r=t.getName();return fe.has(r)?r:void 0}if(!o.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(r)){const i=r.getNameNode().getText();return fe.has(i)?i:void 0}const s=t.getText();return fe.has(s)?s:void 0},gc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,kt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(gc(e))return"empty-object";if(o.isParenthesizedExpression(e))return kt(e.getExpression())}},Dt=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Ot=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Dt(t)===e),Ct=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Dt(t)===e),pc=e=>{const t=Ot(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Ct(e).length>0},fc=e=>{const t=[],s=e.getBody();o.isBlock(s)||t.push(s);for(const r of Ot(e)){const i=o.isReturnStatement(r)?r.getExpression():void 0;t.push(i??r)}for(const r of Ct(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},mc=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},hc=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!o.isObjectLiteralExpression(r))return[];const i=[];for(const n of r.getProperties()){if(!o.isPropertyAssignment(n)||!uc.has(n.getName()))continue;const a=n.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&pc(a))for(const c of fc(a)){const u=kt(c);u!==void 0&&i.push({exportName:mc(e),file:s,form:u,key:n.getName(),line:c.getStartLineNumber(),owner:t})}}return i},xc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=dc(r);i!==void 0&&s.push(...hc(r,i,t))}return s},Ec=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xc(i,E(t,r)))}return s},yc=new Set(["query","upsert","upsertMany"]),$c=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(yc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},vc=(e,t)=>{const s=$c(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const i=$(r,"namespace");if(!(!i||!I(i)||D(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},bc=(e,t)=>N(e,t,vc),Nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},Sc=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ac=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Nc(a))continue;const c=gs(a);c!==""&&s.push({exportName:c,file:n,line:a.getStartLineNumber(),workflow:Sc(a)})}}return s},wc=".lunora-schema.json",S=(e,t)=>{b(e)&&dt(e,"utf8")===t||Bt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}S(e,t)},Pc=e=>{const t=g(e,"package.json");if(b(t))try{const s=JSON.parse(dt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Ic=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Tc=e=>{let t=b(e)?e:le(e);for(;t&&t!==le(t);){const s=g(t,"tsconfig.json");if(b(s))return s;t=le(t)}},lt=e=>e.replaceAll("\\","/"),Lc=(e,t,s)=>{if(s&&e.length>0){const n=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${n}), 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 r=new Map;for(const n of t.columns){const a=r.get(n.table)??[];a.push(n.column),r.set(n.table,a)}const i=t.columns.length>0;for(const n of e){if(n.table===void 0){if(i)throw new k("MASK_UNSUPPORTED",`defineShape "${n.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 "${n.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=r.get(n.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${n.exportName}" replicates table "${n.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})}},ut=(e,t,s)=>{const r=e.getSourceFile(t);if(r===void 0){e.createSourceFile(t,s,{overwrite:!0});return}r.getFullText()!==s&&r.replaceWithText(s)},kc=e=>{const t=Tc(e);return t?new Ge({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ge({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},$l=(e,t)=>{const s=h(t),r=g(t,"schema.ts");b(r)&&s.push(r);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>lt(c))),n=lt(t),a=`${n}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===n||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}},vl=e=>{const t=Ic(),s=t?ue.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),i=g(r,"schema.ts");if(!b(i))throw new k("INTERNAL",`schema.ts not found at ${i}`);const n=e.project??kc(r);ir(Is);const a=Hs(n,i,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:y,env:w,featureUsage:p,hasBrowser:v,hasFlags:C,hasNotify:j,identity:z,platformGate:U,queues:T,serverContent:F,storageRulesMetadata:q,usesSandbox:se,useUmbrella:K,workflows:L}=Pr({lunoraDirectory:r,project:n,projectRoot:e.projectRoot,schema:a,target:e.target}),f=g(r,"_generated"),ve=g(f,"dataModel.ts"),be=g(f,"server.ts");ut(n,ve,d),ut(n,be,F);const O=Ps(n,r),Ne=Ds(n,r),Se=Ms(n,r),B=Ys(n,r),re=qs(n,r),ne=Ls(n,r,L,c),V=e.lint===!1?void 0:_t({adminRoutes:Fr(n,r),aiRawRuns:Mr(n,r),aiToolSideEffects:Hr(n,r),argumentDerivedFetches:Xr(n,r),argumentValidators:un(n,r),authApiCalls:Ts(n,r),authConfigs:$n(n,r),browserUrlAccesses:An(n,r),configCalls:On(n,r),containerKeyAccesses:Fn(n,r),containerOverrides:qn(n,r),containers:u,exportSinks:Wn(n,r),staleMigrationImports:Ha(n,r),failOpenGuards:Jn(n,r),flagSecurityDefaults:ei(n,r),geoIndexUsages:ri(n,r),httpActionGuards:ui(n,r),httpHeaderWrites:$i(n,r),identityClaimReads:Pi(n,r),imageDeliveryUrlAccesses:Ti(n,r),inserts:Os(n,r),kvKeyAccesses:ki(n,r),mailRecipientAccesses:Ki(n,r),maskProcedures:Cs(n,r),maskStrategies:Fs(n,r),mutatorWrites:Bi(n,r),nondeterministicCalls:Bs(n,r),normalizeIdAuthorizations:no(n,r),notifyCalls:Vs(n,r),notifyConfig:Us(n,r),ownerFieldWrites:po(n,r,O),unrestrictedWhereBranches:Ec(n,r),paymentWebhooks:Eo(n,r),privilegedDispatches:ko(n,r),procedureProtections:ma(n,r),queries:Ss(n,r),queues:T,r2sqlCalls:Ws(n,r),ratelimitKeySelectors:ya(n,r),rawRowReturns:wa(n,r),relationLoads:Ta(n,r),rlsProcedures:_s(n,r),schema:a,secretLiterals:Ra(n,r),shapes:B,softDeleteReads:ja(n,r),sqlInterpolations:Wa(n,r),storageKeyAccesses:Ja(n,r,O),storageUploads:sc(n,r),vectorNamespaceAccesses:bc(n,r),workflowCalls:Ac(n,r),workflows:L,wranglerVariables:e.wranglerVariables}),Ae=V===void 0?[]:[...Vt(V,{source:"static"}),...lc(n,r,O)],Ft=Gs(n,r),we=Ks(n,r);Lc(B,we,Rs(n,r));const Kt=C?ks(n,r):[],W=$r(p,{containerCount:u.length,cronCount:ne.length,dependencies:y,hasPaymentTables:yr(a.tables),queueCount:T.length,storageColumnCount:Object.keys(Xt(a)).length,storageRuleCount:q.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:L.length}),Pe=t?ue.now():0,Ie=Zt({agents:c,functions:O,httpRoutes:Ne,mutators:re,useUmbrella:K,workflows:L}),Te=Yt({agents:c,functions:O,migrations:Se,mutators:re,shapes:B,useUmbrella:K,usesSandbox:se}),ie=or(a,Se.map(m=>m.id)),Le=es({advisories:Ae,advisorProcedures:V?.procedureProtections??[],agents:c,containers:u,env:w,flagKeys:Kt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:v,hasFlags:C,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:j,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:we,mutators:re,queues:T,rlsMetadata:Ft,schema:a,schemaSnapshot:ie,shapes:B,storageRules:q,studioFeatures:W,useUmbrella:K,workflows:L}),ke=ts(B,y.has("@lunora/db"),K),De=ss(u,a.jurisdiction),Oe=rs(L),Ce=ns(c),Fe=is(T),Ke=os(ne),Re=as(a.vectorIndexes),_=cs(a,K),Me=ls(y.has("@lunora/seed")),G=e.apiSpec??"openapi",oe=G==="openapi"||G==="both",ae=G==="openrpc"||G==="both",je=er({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:y.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:y.has("@lunora/auth"),hasBrowser:v,hasFramework:y.has("@lunora/astro")||y.has("@lunora/svelte")||y.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:W.kv,hasNotify:j,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:L.length>0,hasX402:p.x402,identity:z,jurisdiction:a.jurisdiction,useUmbrella:K,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:oe,wantsOpenRpc:ae}),ze=Pc(e.projectRoot),qe=tr({functions:O,httpRoutes:Ne,version:ze}),Be=rr({functions:O,version:ze}),Ue=`${JSON.stringify(qe,void 0,2)}
7
+ `)){const r=s.replace(aa,"");if(!r.startsWith(ct))continue;const i=r.slice(ct.length);if(ca.test(i.charAt(0)))continue;const n=i.indexOf("--");return{exempt:!0,exemptReason:(n===-1?"":i.slice(n+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},ua=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},da=(e,t)=>{const s=ua(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const r=s.getSourceFile(),i=s.getText(),n=r.getVariableDeclaration(i)?.getInitializer();return n&&(o.isArrowFunction(n)||o.isFunctionExpression(n))?n:r.getFunction(i)},ga=e=>{let t=!1,s=!1,r=!1,i=!1,n=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(qo(u)&&(n=!0),Vo(u)&&(t=!0),Wo(u)&&(i=!0),_o(u)&&(s=!0),Go(u)&&(r=!0),n&&t&&i&&r)break;const{handlesErrors:a,reachesOutbound:c}=ia(e);return{callsMail:pe(e,Jo),emitsEvent:pe(e,Ho),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||pe(e,Qo),throwsBareError:oa(e),unboundedAiGeneration:r,usesInsertManyUnsafe:i,writesUserTable:n}},pa=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const r=M(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const i=r.receiver?jo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},n=da(e,s);return{...n?ga(n):{},...la(e),...i,analyzableBody:n!==void 0,exportName:e.getName(),file:t,hasEmailArg:Co(s,r.receiver),kind:r.kind,visibility:r.visibility}},fa=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const i of r.getDeclarations()){const n=pa(i,t);n&&s.push(n)}return s},ma=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fa(i,E(t,r)))}return s},ha=new Set(["dbRateLimit","rateLimit"]),xa=e=>o.isArrowFunction(e)?e.getBody():e,Ea=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!ha.has(s))return;const r=e.getArguments()[2];if(!r)return;const i=$(r,"key");if(!i)return;const n=xa(i);if(!(!I(n)||D(n)))return{callee:s,exportName:x(e),file:t,limitName:gt(e),line:e.getStartLineNumber()}},ya=(e,t)=>N(e,t,Ea),$a=new Set(["findFirst","findFirstOrThrow","findMany","get"]),va=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!$a.has(t.getName()))return;const s=t.getExpression();if(R(s)){const r=e.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&R(s.getExpression()))return s.getName()},ba=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&R(s.getExpression())){const r=t.getArguments()[0];return r&&o.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},Na=e=>{let t=e;for(;o.isAwaitExpression(t)||o.isParenthesizedExpression(t)||o.isNonNullExpression(t)||o.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=Na(e);if(o.isIdentifier(s)){if(t)return;const r=ee(s);return r===void 0?void 0:It(r,!0)}if(o.isCallExpression(s))return va(s)??ba(s)},Sa=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(l.ReturnStatement)){const i=r.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),n=r.getExpression();i===e&&n!==void 0&&s.push(n)}return s},Aa=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const r=M(s);if(r?.kind!=="query")return[];const i=ft(s);if(i===void 0)return[];const n=r.receiver!==void 0&&ws(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,u=[];for(const d of Sa(i)){const y=It(d);y===void 0||c.has(y)||(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:y,usesMask:a,usesOutput:n,visibility:r.visibility}))}return u},wa=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Aa(c,n))}return s},Pa=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Ia=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=Pa($(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:n.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return i},Ta=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,n))}return s},X=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=X(e.getLeft()),s=X(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},La=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&X(t)!==void 0},ka=/(?:^|\/)__tests__\//u,Da=/\.(?:spec|test)$/u,Fa=e=>ka.test(e)||Da.test(e),Oa=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Ca=(e,t,s)=>Xs(e)?!Fa(s)&&Zs(Oa(t)):!0,Ka=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const n of r){if(La(n))continue;const a=X(n);if(a===void 0)continue;const c=Qs(a);if(c===void 0||!Ca(c,n,t))continue;const u=n.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:Js(a)}))}return s},Ra=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ka(i,E(t,r)))}return s},Ma=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&o.isCallExpression(s)?M(s):void 0;if(!r)return[];const i=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const a=pt(n);if(a===void 0)continue;const c=$(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&I(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:n.getStartLineNumber(),table:a.table,visibility:r.visibility})}return i},ja=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ma(c,n))}return s},za=new Set(["query","unsafe"]),qa=e=>{if(!o.isPropertyAccessExpression(e)||!za.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},Ba=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Ua=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Va=(e,t)=>{if(!qa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ba(s)))return{exportName:Ua(e),file:t,line:s.getStartLineNumber()}},Wa=(e,t)=>N(e,t,Va),_a=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Ga=e=>{for(const[t,s]of _a)for(const r of s)if(e===r||e.startsWith(r.endsWith("/")?r:`${r}/`))return t},Ha=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);for(const n of i.getImportDeclarations()){const a=n.getModuleSpecifierValue(),c=Ga(a);c!==void 0&&s.push({file:E(t,r),line:n.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Qa=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ja=(e,t,s=[])=>{const r=new Map(s.map(i=>[`${i.filePath}:${i.exportName}`,i.visibility]));return te(e,t,{argIndex:0,matchReceiver:i=>i==="ctx.storage"||i.startsWith("ctx.storage."),methods:Qa,requireUnmodifiedReach:!0}).map(i=>{const n=r.get(`${i.file}:${i.exportName}`);return n===void 0?i:{...i,visibility:n}})},Xa=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Za=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ya=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){r=!0;continue}if(o.isPropertyAssignment(i)){const n=i.getName();t.push(n),n==="expiresInSeconds"&&(s=Za(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},ec=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Xa.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},tc=(e,t)=>{const s=ec(e.getExpression());if(s!==void 0)return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ya(e.getArguments()[s.optionsIndex])}},sc=(e,t)=>N(e,t,tc),rc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),ye=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&rc.has(s)?s:void 0},Tt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Lt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},nc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},$e=(e,t,s,r,i)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${r.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${i.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),ic=(e,t,s)=>{const r=[];for(const i of e.getVariableStatements().filter(n=>n.isExported()))for(const n of i.getDeclarations()){const a=n.getName();if(s.has(`${t}:${a}`)||!Tt(n))continue;const c=ye(n);c!==void 0&&r.push($e(t,a,c,n.getStartLineNumber(),Lt))}return r},oc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const i of e.getExportAssignments().filter(n=>!n.isExportEquals())){const n=ye(i.getExpression());n!==void 0&&r.push($e(t,"default",n,i.getStartLineNumber(),Lt))}return r},ac=(e,t,s)=>{const r=[];for(const i of e.getExportDeclarations().filter(n=>n.getModuleSpecifier()===void 0))for(const n of i.getNamedExports()){const a=n.getAliasNode()?.getText()??n.getName();if(s.has(`${t}:${a}`))continue;const c=n.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Tt(c))continue;const u=ye(c);u!==void 0&&r.push($e(t,a,u,n.getStartLineNumber(),nc))}return r},cc=(e,t,s)=>[...ic(e,t,s),...oc(e,t,s),...ac(e,t,s)],lc=(e,t,s)=>{const r=new Set(s.map(n=>`${n.filePath}:${n.exportName}`)),i=[];for(const n of h(t)){const a=e.getSourceFile(n);a!==void 0&&i.push(...cc(a,E(t,n),r))}return i.toSorted((n,a)=>n.cacheKey.localeCompare(a.cacheKey))},uc=new Set(["when","where"]),fe=new Set(["definePolicy","defineShape"]),dc=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const r=t.getName();return fe.has(r)?r:void 0}if(!o.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(r)){const i=r.getNameNode().getText();return fe.has(i)?i:void 0}const s=t.getText();return fe.has(s)?s:void 0},gc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,kt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(gc(e))return"empty-object";if(o.isParenthesizedExpression(e))return kt(e.getExpression())}},Dt=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Ft=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Dt(t)===e),Ot=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Dt(t)===e),pc=e=>{const t=Ft(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Ot(e).length>0},fc=e=>{const t=[],s=e.getBody();o.isBlock(s)||t.push(s);for(const r of Ft(e)){const i=o.isReturnStatement(r)?r.getExpression():void 0;t.push(i??r)}for(const r of Ot(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},mc=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},hc=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!o.isObjectLiteralExpression(r))return[];const i=[];for(const n of r.getProperties()){if(!o.isPropertyAssignment(n)||!uc.has(n.getName()))continue;const a=n.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&pc(a))for(const c of fc(a)){const u=kt(c);u!==void 0&&i.push({exportName:mc(e),file:s,form:u,key:n.getName(),line:c.getStartLineNumber(),owner:t})}}return i},xc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const i=dc(r);i!==void 0&&s.push(...hc(r,i,t))}return s},Ec=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xc(i,E(t,r)))}return s},yc=new Set(["query","upsert","upsertMany"]),$c=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(yc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},vc=(e,t)=>{const s=$c(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const i=$(r,"namespace");if(!(!i||!I(i)||D(i)))return{exportName:x(e),file:t,line:e.getStartLineNumber(),method:s}},bc=(e,t)=>N(e,t,vc),Nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},Sc=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ac=(e,t)=>{const s=[];for(const r of h(t)){const i=e.getSourceFile(r)??e.addSourceFileAtPath(r),n=E(t,r);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!Nc(a))continue;const c=gs(a);c!==""&&s.push({exportName:c,file:n,line:a.getStartLineNumber(),workflow:Sc(a)})}}return s},wc=".lunora-schema.json",S=(e,t)=>{b(e)&&dt(e,"utf8")===t||Bt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}S(e,t)},Pc=e=>{const t=g(e,"package.json");if(b(t))try{const s=JSON.parse(dt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Ic=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Tc=e=>{let t=b(e)?e:le(e);for(;t&&t!==le(t);){const s=g(t,"tsconfig.json");if(b(s))return s;t=le(t)}},lt=e=>e.replaceAll("\\","/"),Lc=(e,t,s)=>{if(s&&e.length>0){const n=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${n}), 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 r=new Map;for(const n of t.columns){const a=r.get(n.table)??[];a.push(n.column),r.set(n.table,a)}const i=t.columns.length>0;for(const n of e){if(n.table===void 0){if(i)throw new k("MASK_UNSUPPORTED",`defineShape "${n.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 "${n.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=r.get(n.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${n.exportName}" replicates table "${n.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})}},ut=(e,t,s)=>{const r=e.getSourceFile(t);if(r===void 0){e.createSourceFile(t,s,{overwrite:!0});return}r.getFullText()!==s&&r.replaceWithText(s)},kc=e=>{const t=Tc(e);return t?new Ge({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ge({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},$l=(e,t)=>{const s=h(t),r=g(t,"schema.ts");b(r)&&s.push(r);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>lt(c))),n=lt(t),a=`${n}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===n||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===n||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},vl=e=>{const t=Ic(),s=t?ue.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),i=g(r,"schema.ts");if(!b(i))throw new k("INTERNAL",`schema.ts not found at ${i}`);const n=e.project??kc(r);ir(Is);const a=Hs(n,i,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:y,env:w,featureUsage:p,hasBrowser:v,hasFlags:O,hasNotify:j,identity:z,platformGate:U,queues:T,serverContent:C,storageRulesMetadata:q,usesSandbox:se,useUmbrella:K,workflows:L}=Pr({lunoraDirectory:r,project:n,projectRoot:e.projectRoot,schema:a,target:e.target}),f=g(r,"_generated"),ve=g(f,"dataModel.ts"),be=g(f,"server.ts");ut(n,ve,d),ut(n,be,C);const F=Ps(n,r),Ne=Ds(n,r),Se=Ms(n,r),B=Ys(n,r),re=qs(n,r),ne=Ls(n,r,L,c),V=e.lint===!1?void 0:_t({adminRoutes:Cr(n,r),aiRawRuns:Mr(n,r),aiToolSideEffects:Hr(n,r),argumentDerivedFetches:Xr(n,r),argumentValidators:un(n,r),authApiCalls:Ts(n,r),authConfigs:$n(n,r),browserUrlAccesses:An(n,r),configCalls:Fn(n,r),containerKeyAccesses:Cn(n,r),containerOverrides:qn(n,r),containers:u,exportSinks:Wn(n,r),staleMigrationImports:Ha(n,r),failOpenGuards:Jn(n,r),flagSecurityDefaults:ei(n,r),geoIndexUsages:ri(n,r),httpActionGuards:ui(n,r),httpHeaderWrites:$i(n,r),identityClaimReads:Pi(n,r),imageDeliveryUrlAccesses:Ti(n,r),inserts:Fs(n,r),kvKeyAccesses:ki(n,r),mailRecipientAccesses:Ki(n,r),maskProcedures:Os(n,r),maskStrategies:Cs(n,r),mutatorWrites:Bi(n,r),nondeterministicCalls:Bs(n,r),normalizeIdAuthorizations:no(n,r),notifyCalls:Vs(n,r),notifyConfig:Us(n,r),ownerFieldWrites:po(n,r,F),unrestrictedWhereBranches:Ec(n,r),paymentWebhooks:Eo(n,r),privilegedDispatches:ko(n,r),procedureProtections:ma(n,r),queries:Ss(n,r),queues:T,r2sqlCalls:Ws(n,r),ratelimitKeySelectors:ya(n,r),rawRowReturns:wa(n,r),relationLoads:Ta(n,r),rlsProcedures:_s(n,r),schema:a,secretLiterals:Ra(n,r),shapes:B,softDeleteReads:ja(n,r),sqlInterpolations:Wa(n,r),storageKeyAccesses:Ja(n,r,F),storageUploads:sc(n,r),vectorNamespaceAccesses:bc(n,r),workflowCalls:Ac(n,r),workflows:L,wranglerVariables:e.wranglerVariables}),Ae=V===void 0?[]:[...Vt(V,{source:"static"}),...lc(n,r,F)],Ct=Gs(n,r),we=Ks(n,r);Lc(B,we,Rs(n,r));const Kt=O?ks(n,r):[],W=$r(p,{containerCount:u.length,cronCount:ne.length,dependencies:y,hasPaymentTables:yr(a.tables),queueCount:T.length,storageColumnCount:Object.keys(Xt(a)).length,storageRuleCount:q.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:L.length}),Pe=t?ue.now():0,Ie=Zt({agents:c,functions:F,httpRoutes:Ne,mutators:re,useUmbrella:K,workflows:L}),Te=Yt({agents:c,functions:F,migrations:Se,mutators:re,shapes:B,useUmbrella:K,usesSandbox:se}),ie=or(a,Se.map(m=>m.id)),Le=es({advisories:Ae,advisorProcedures:V?.procedureProtections??[],agents:c,containers:u,env:w,flagKeys:Kt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:v,hasFlags:O,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:j,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:we,mutators:re,queues:T,rlsMetadata:Ct,schema:a,schemaSnapshot:ie,shapes:B,storageRules:q,studioFeatures:W,useUmbrella:K,workflows:L}),ke=ts(B,y.has("@lunora/db"),K),De=ss(u,a.jurisdiction),Fe=rs(L),Oe=ns(c),Ce=is(T),Ke=os(ne),Re=as(a.vectorIndexes),_=cs(a,K),Me=ls(y.has("@lunora/seed")),G=e.apiSpec??"openapi",oe=G==="openapi"||G==="both",ae=G==="openrpc"||G==="both",je=er({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:y.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:y.has("@lunora/auth"),hasBrowser:v,hasFramework:y.has("@lunora/astro")||y.has("@lunora/svelte")||y.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:W.kv,hasNotify:j,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:L.length>0,hasX402:p.x402,identity:z,jurisdiction:a.jurisdiction,useUmbrella:K,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:oe,wantsOpenRpc:ae}),ze=Pc(e.projectRoot),qe=tr({functions:F,httpRoutes:Ne,version:ze}),Be=rr({functions:F,version:ze}),Ue=`${JSON.stringify(qe,void 0,2)}
8
8
  `,Ve=`${JSON.stringify(Be,void 0,2)}
9
- `,We=sr(qe),_e=nr(Be),ce=g(r,wc),Rt=b(ce);if(e.dryRun||(b(f)||qt(f,{recursive:!0}),S(g(f,"app.ts"),je),S(ve,d),S(g(f,"api.ts"),Ie),S(be,F),S(g(f,"functions.ts"),Te),S(g(f,"shard.ts"),Le),S(g(f,"crons.ts"),Ke),S(g(f,"vectors.ts"),Re),S(g(f,"drizzle.global.ts"),_.global),S(g(f,"drizzle.shard.ts"),_.shard),P(g(f,"containers.ts"),De),P(g(f,"workflows.ts"),Oe),P(g(f,"agents.ts"),Ce),P(g(f,"queues.ts"),Fe),P(g(f,"seed.ts"),Me),P(g(f,"collections.ts"),ke),P(g(f,"openapi.json"),oe?Ue:""),P(g(f,"openapi.ts"),oe?We:""),P(g(f,"openrpc.json"),ae?Ve:""),P(g(f,"openrpc.ts"),ae?_e:""),(!Rt||e.updateSchemaBaseline===!0)&&S(ce,Wt(ie))),t){const m=ue.now(),Mt=Math.round(m-s),jt=Math.round(Pe-s),zt=Math.round(m-Pe);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${jt.toString()}ms, emit ${zt.toString()}ms)`)}return{advisories:Ae,advisorContext:V,agents:c,containers:u,cronTriggers:us(ne),generated:{agents:Ce,api:Ie,app:je,collections:ke,containers:De,crons:Ke,dataModel:d,drizzleGlobal:_.global,drizzleShard:_.shard,functions:Te,openApi:Ue,openApiModule:We,openRpc:Ve,openRpcModule:_e,queues:Fe,seed:Me,server:F,shard:Le,vectors:Re,workflows:Oe},outputDirectory:f,platformDiagnostics:U.diagnostics,queues:T,schemaSnapshot:ie,schemaSnapshotPath:ce,workflows:L}};export{wc as SCHEMA_SNAPSHOT_FILENAME,kc as createCodegenProject,$l as refreshCodegenProject,vl as runCodegen};
9
+ `,We=sr(qe),_e=nr(Be),ce=g(r,wc),Rt=b(ce);if(e.dryRun||(b(f)||qt(f,{recursive:!0}),S(g(f,"app.ts"),je),S(ve,d),S(g(f,"api.ts"),Ie),S(be,C),S(g(f,"functions.ts"),Te),S(g(f,"shard.ts"),Le),S(g(f,"crons.ts"),Ke),S(g(f,"vectors.ts"),Re),S(g(f,"drizzle.global.ts"),_.global),S(g(f,"drizzle.shard.ts"),_.shard),P(g(f,"containers.ts"),De),P(g(f,"workflows.ts"),Fe),P(g(f,"agents.ts"),Oe),P(g(f,"queues.ts"),Ce),P(g(f,"seed.ts"),Me),P(g(f,"collections.ts"),ke),P(g(f,"openapi.json"),oe?Ue:""),P(g(f,"openapi.ts"),oe?We:""),P(g(f,"openrpc.json"),ae?Ve:""),P(g(f,"openrpc.ts"),ae?_e:""),(!Rt||e.updateSchemaBaseline===!0)&&S(ce,Wt(ie))),t){const m=ue.now(),Mt=Math.round(m-s),jt=Math.round(Pe-s),zt=Math.round(m-Pe);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${jt.toString()}ms, emit ${zt.toString()}ms)`)}return{advisories:Ae,advisorContext:V,agents:c,containers:u,cronTriggers:us(ne),generated:{agents:Oe,api:Ie,app:je,collections:ke,containers:De,crons:Ke,dataModel:d,drizzleGlobal:_.global,drizzleShard:_.shard,functions:Te,openApi:Ue,openApiModule:We,openRpc:Ve,openRpcModule:_e,queues:Ce,seed:Me,server:C,shard:Le,vectors:Re,workflows:Fe},outputDirectory:f,platformDiagnostics:U.diagnostics,queues:T,schemaSnapshot:ie,schemaSnapshotPath:ce,workflows:L}};export{wc as SCHEMA_SNAPSHOT_FILENAME,kc as createCodegenProject,Tc as findTsconfig,$l as refreshCodegenProject,vl as runCodegen};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as l}from"ts-morph";import{g as N,p as A}from"./discover-ast-7ABwvTVn.mjs";const m=(e,t)=>{if(e.getText()!==t)return!1;const r=e.getParent();return s.isPropertyAccessExpression(r)&&r.getNameNode()===e?!1:!(s.isPropertyAssignment(r)&&r.getNameNode()===e)},x=(e,t)=>s.isIdentifier(e)?m(e,t):e.getDescendantsOfKind(l.Identifier).some(r=>m(r,t)),d=e=>x(e,"ctx"),I=e=>{let t=e;for(;s.isPropertyAccessExpression(t)||s.isElementAccessExpression(t)||s.isNonNullExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t:void 0},C=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e))return e.getName()},E=e=>x(e,"args"),f=e=>{if(!s.isIdentifier(e))return;const t=e.getText(),r=e.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(r===void 0)return;const n=e.getStart();let i,u=-1;for(const o of r.getDescendantsOfKind(l.VariableDeclaration)){if(o.getName()!==t)continue;const a=o.getInitializer(),c=o.getStart();a!==void 0&&c<n&&c>u&&(i=a,u=c)}return i},T=e=>{if(E(e))return!0;const t=f(e);return t!==void 0&&E(t)},q=e=>{if(s.isCallExpression(e)||s.isNewExpression(e))return!1;const t=f(e);return t===void 0||!(s.isCallExpression(t)||s.isNewExpression(t))},L=e=>{if(d(e))return!0;const t=f(e);if(t!==void 0&&d(t))return!0;const r=t??e;return(s.isIdentifier(r)?[r]:r.getDescendantsOfKind(l.Identifier)).some(n=>{const i=f(n);return i!==void 0&&d(i)})},p=(e,t)=>x(e,t),O=(e,t)=>{if(p(e,t))return!0;const r=f(e);if(r!==void 0&&p(r,t))return!0;const n=I(e);if(n!==void 0){const i=f(n);return i!==void 0&&p(i,t)}return!1},P=e=>{for(const t of e.getAncestors())if(s.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},h=new Set(["withGeoIndex","withIndex","withSearchIndex"]),y=new Set(["collect","collectWithScores","first","paginate","take","unique"]),S=e=>{const t=e.getExpression();if(!s.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const r=t.getExpression();return s.isPropertyAccessExpression(r)?r.getName()==="db":s.isIdentifier(r)&&r.getText()==="db"},v=e=>{const t=[];let r=e;for(;;){const n=r.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;t.push(n.getName()),r=i}return t},b=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,w=e=>{let t=e;for(;;){const r=t.getParent();if(!r||!s.isPropertyAccessExpression(r))return!1;const n=r.getParent();if(!n||!s.isCallExpression(n))return!1;if(r.getName()==="filter"){const i=n.getArguments()[0];if(i&&b.test(i.getText()))return!0}t=n}},D=e=>{const t=e.getArguments()[0];return t&&s.isStringLiteral(t)?t.getLiteralText():""},$=(e,t)=>{const r=[];for(const n of N(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),u=A(t,n);for(const o of i.getDescendantsOfKind(l.CallExpression)){if(!S(o))continue;const a=v(o),c=a.includes("filter");r.push({exportName:P(o),file:u,filtersPrimaryKey:c&&w(o),hasFilter:c,hasIndex:a.some(g=>h.has(g)),line:o.getStartLineNumber(),table:D(o),terminal:a.findLast(g=>y.has(g))})}}return r};export{$ as I,L as a,q as b,C as c,O as d,P as e,p as f,T as i,E as r,f as s};
@@ -0,0 +1 @@
1
+ import"ts-morph";import{I as p}from"./discover-queries-CU9o_j87.mjs";import"./discover-ast-7ABwvTVn.mjs";export{p as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.106",
3
+ "version": "1.0.0-alpha.108",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,15 +46,15 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.76",
50
- "@lunora/agent": "1.0.0-alpha.52",
49
+ "@lunora/advisor": "1.0.0-alpha.78",
50
+ "@lunora/agent": "1.0.0-alpha.53",
51
51
  "@lunora/container": "1.0.0-alpha.30",
52
52
  "@lunora/errors": "1.0.0-alpha.21",
53
53
  "@lunora/platform": "1.0.0-alpha.10",
54
54
  "@lunora/queue": "1.0.0-alpha.26",
55
- "@lunora/scheduler": "1.0.0-alpha.29",
55
+ "@lunora/scheduler": "1.0.0-alpha.30",
56
56
  "@lunora/values": "1.0.0-alpha.26",
57
- "@lunora/workflow": "1.0.0-alpha.27",
57
+ "@lunora/workflow": "1.0.0-alpha.28",
58
58
  "jsonc-parser": "^3.3.1",
59
59
  "quicktype-core": "^26.0.0",
60
60
  "ts-morph": "^28.0.0"
@@ -1 +0,0 @@
1
- import{Node as s,SyntaxKind as g}from"ts-morph";import{g as E,p as N}from"./discover-ast-7ABwvTVn.mjs";const x=(e,t)=>{if(e.getText()!==t)return!1;const r=e.getParent();return s.isPropertyAccessExpression(r)&&r.getNameNode()===e?!1:!(s.isPropertyAssignment(r)&&r.getNameNode()===e)},p=(e,t)=>s.isIdentifier(e)?x(e,t):e.getDescendantsOfKind(g.Identifier).some(r=>x(r,t)),l=e=>p(e,"ctx"),A=e=>{let t=e;for(;s.isPropertyAccessExpression(t)||s.isElementAccessExpression(t)||s.isNonNullExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t:void 0},F=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e))return e.getName()},m=e=>p(e,"args"),a=e=>{if(!s.isIdentifier(e))return;const t=e.getText(),r=e.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(r===void 0)return;const n=e.getStart();let i,f=-1;for(const o of r.getDescendantsOfKind(g.VariableDeclaration)){if(o.getName()!==t)continue;const c=o.getInitializer(),u=o.getStart();c!==void 0&&u<n&&u>f&&(i=c,f=u)}return i},K=e=>{if(m(e))return!0;const t=a(e);return t!==void 0&&m(t)},C=e=>{if(s.isCallExpression(e)||s.isNewExpression(e))return!1;const t=a(e);return t===void 0||!(s.isCallExpression(t)||s.isNewExpression(t))},T=e=>{if(l(e))return!0;const t=a(e);if(t!==void 0&&l(t))return!0;const r=t??e;return(s.isIdentifier(r)?[r]:r.getDescendantsOfKind(g.Identifier)).some(n=>{const i=a(n);return i!==void 0&&l(i)})},d=(e,t)=>p(e,t),$=(e,t)=>{if(d(e,t))return!0;const r=a(e);if(r!==void 0&&d(r,t))return!0;const n=A(e);if(n!==void 0){const i=a(n);return i!==void 0&&d(i,t)}return!1},P=e=>{for(const t of e.getAncestors())if(s.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},y=new Set(["withIndex","withSearchIndex"]),I=e=>{const t=e.getExpression();if(!s.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const r=t.getExpression();return s.isPropertyAccessExpression(r)?r.getName()==="db":s.isIdentifier(r)&&r.getText()==="db"},h=e=>{const t=[];let r=e;for(;;){const n=r.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;t.push(n.getName()),r=i}return t},v=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,b=e=>{let t=e;for(;;){const r=t.getParent();if(!r||!s.isPropertyAccessExpression(r))return!1;const n=r.getParent();if(!n||!s.isCallExpression(n))return!1;if(r.getName()==="filter"){const i=n.getArguments()[0];if(i&&v.test(i.getText()))return!0}t=n}},S=e=>{const t=e.getArguments()[0];return t&&s.isStringLiteral(t)?t.getLiteralText():""},O=(e,t)=>{const r=[];for(const n of E(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),f=N(t,n);for(const o of i.getDescendantsOfKind(g.CallExpression)){if(!I(o))continue;const c=h(o);c.includes("filter")&&r.push({exportName:P(o),file:f,filtersPrimaryKey:b(o),hasFilter:!0,hasIndex:c.some(u=>y.has(u)),line:o.getStartLineNumber(),table:S(o)})}}return r};export{T as a,C as b,F as c,$ as d,P as e,d as f,K as i,m as r,a as s,O as y};
@@ -1 +0,0 @@
1
- import"ts-morph";import{y as p}from"./discover-queries-i4Vd2si7.mjs";import"./discover-ast-7ABwvTVn.mjs";export{p as default};