@lunora/codegen 1.0.0-alpha.78 → 1.0.0-alpha.79

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
@@ -3,7 +3,8 @@ export type { Finding } from '@lunora/advisor';
3
3
  import { LunoraError } from '@lunora/errors';
4
4
  export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, type Solution as LunoraSolution, type SolutionRule as LunoraSolutionRule, findSolutionByMessage as findLunoraSolution } from '@lunora/errors';
5
5
  import { Node, Project } from 'ts-morph';
6
- import { StudioFeaturesResult } from '@lunora/do';
6
+ import { StudioFeaturesResult } from '@lunora/shard-engine';
7
+ import '@lunora/platform';
7
8
  import { Schema } from '@lunora/server';
8
9
  import { JsonSchema } from '@lunora/values';
9
10
  /**
@@ -2701,6 +2702,231 @@ declare const emitOpenRpc: (input: OpenRpcEmitInput) => string;
2701
2702
  * the object returned by {@link buildOpenRpcDocument} (reused, never recomputed).
2702
2703
  */
2703
2704
  declare const emitOpenRpcModule: (document_: Record<string, unknown>) => string;
2705
+ /**
2706
+ * The canonical capability list. **Order is load-bearing** for the `emit-app.ts`
2707
+ * long-tail: the fluent methods are emitted in the order the `appMethod`-bearing
2708
+ * rows appear here, so this array is ordered to reproduce the original
2709
+ * `LONG_TAIL` sequence (ai, analytics, browser, hyperdrive, images, kv, payment,
2710
+ * r2sql, vectors). The `serverCtxField` rows are referenced by name in the ctx
2711
+ * interface templates, so their order here is not output-affecting.
2712
+ */
2713
+ declare const CAPABILITY_ROWS: readonly [{
2714
+ readonly contextProperty: "access";
2715
+ readonly key: "access";
2716
+ readonly moduleSpecifier: "@lunora/cloudflare-access";
2717
+ }, {
2718
+ readonly appMethod: {
2719
+ readonly configKey: "ai";
2720
+ readonly doc: "Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).";
2721
+ readonly method: "ai";
2722
+ };
2723
+ readonly contextProperty: "ai";
2724
+ readonly key: "ai";
2725
+ readonly moduleSpecifier: "@lunora/ai";
2726
+ }, {
2727
+ readonly appMethod: {
2728
+ readonly configKey: "analytics";
2729
+ readonly doc: "Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).";
2730
+ readonly method: "analytics";
2731
+ };
2732
+ readonly contextProperty: "analytics";
2733
+ readonly key: "analytics";
2734
+ readonly moduleSpecifier: "@lunora/bindings/analytics";
2735
+ readonly serverCtxField: {
2736
+ readonly field: "\n /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */\n readonly analytics: import(\"@lunora/bindings/analytics\").AnalyticsClient;";
2737
+ readonly tier: "every";
2738
+ };
2739
+ }, {
2740
+ readonly appMethod: {
2741
+ readonly configKey: "browser";
2742
+ readonly doc: "Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).";
2743
+ readonly method: "browser";
2744
+ };
2745
+ readonly contextProperty: "browser";
2746
+ readonly key: "browser";
2747
+ readonly moduleSpecifier: "@lunora/browser";
2748
+ readonly serverCtxField: {
2749
+ readonly field: "\n /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */\n readonly browser: import(\"@lunora/browser\").Browser;";
2750
+ readonly tier: "action";
2751
+ };
2752
+ }, {
2753
+ readonly contextProperty: "containers";
2754
+ readonly key: "container";
2755
+ readonly moduleSpecifier: "@lunora/container";
2756
+ }, {
2757
+ readonly contextProperty: "flags";
2758
+ readonly key: "flags";
2759
+ readonly moduleSpecifier: "@lunora/flags";
2760
+ }, {
2761
+ readonly appMethod: {
2762
+ readonly configKey: "sql";
2763
+ readonly doc: "Wire the Hyperdrive SQL client backing `ctx.sql` — build it with `createHyperdrive` + `fromPostgresJs`/`fromNodePg`/`fromMysql2`.";
2764
+ readonly method: "hyperdrive";
2765
+ };
2766
+ readonly contextProperty: "sql";
2767
+ readonly key: "hyperdrive";
2768
+ readonly moduleSpecifier: "@lunora/hyperdrive";
2769
+ readonly serverCtxField: {
2770
+ readonly field: "\n /**\n * External database access via Hyperdrive. Non-deterministic — available only in actions. Writes here are NOT tracked by Lunora live queries; subscriptions will not re-run on external DB changes.\n */\n readonly sql: import(\"@lunora/hyperdrive\").SqlClient;";
2771
+ readonly tier: "action";
2772
+ };
2773
+ }, {
2774
+ readonly appMethod: {
2775
+ readonly configKey: "images";
2776
+ readonly doc: "Override the Images binding backing `ctx.images` (defaults to `env.IMAGES`).";
2777
+ readonly method: "images";
2778
+ };
2779
+ readonly contextProperty: "images";
2780
+ readonly key: "images";
2781
+ readonly moduleSpecifier: "@lunora/bindings/images";
2782
+ readonly serverCtxField: {
2783
+ readonly field: "\n /** Cloudflare Images transforms (resize/format/optimize). Non-deterministic — available only in actions. */\n readonly images: import(\"@lunora/bindings/images\").Images;";
2784
+ readonly tier: "action";
2785
+ };
2786
+ }, {
2787
+ readonly appMethod: {
2788
+ readonly configKey: "kv";
2789
+ readonly doc: "Override the Workers KV binding backing `ctx.kv` (defaults to `env.KV`).";
2790
+ readonly method: "kv";
2791
+ };
2792
+ readonly contextProperty: "kv";
2793
+ readonly key: "kv";
2794
+ readonly moduleSpecifier: "@lunora/bindings/kv";
2795
+ readonly serverCtxField: {
2796
+ readonly field: "\n readonly kv: import(\"@lunora/bindings/kv\").Kv;";
2797
+ readonly tier: "every";
2798
+ };
2799
+ }, {
2800
+ readonly key: "mail";
2801
+ readonly moduleSpecifier: "@lunora/mail";
2802
+ }, {
2803
+ readonly contextProperty: "notify";
2804
+ readonly key: "notify";
2805
+ readonly moduleSpecifier: "@lunora/notify";
2806
+ }, {
2807
+ readonly appMethod: {
2808
+ readonly configKey: "payment";
2809
+ readonly doc: "Wire the payment options backing `ctx.payments`.";
2810
+ readonly method: "payment";
2811
+ };
2812
+ readonly contextProperty: "payments";
2813
+ readonly key: "payments";
2814
+ readonly moduleSpecifier: "@lunora/payment";
2815
+ }, {
2816
+ readonly appMethod: {
2817
+ readonly configKey: "x402";
2818
+ readonly doc: "Wire the x402 agent-wallet pay rail backing `ctx.x402` — a payment-enabled `fetch` that answers `402` challenges under a mandatory spend policy (ActionCtx-only; spends real funds).";
2819
+ readonly method: "x402";
2820
+ };
2821
+ readonly contextProperty: "x402";
2822
+ readonly key: "x402";
2823
+ readonly moduleSpecifier: "@lunora/x402/pay";
2824
+ }, {
2825
+ readonly contextProperty: "pipelines";
2826
+ readonly key: "pipelines";
2827
+ readonly moduleSpecifier: "@lunora/bindings/pipelines";
2828
+ readonly serverCtxField: {
2829
+ readonly field: "\n /** Pipelines ingestion sink (durable, R2-backed). Fire-and-forget and batched; do not read it back in-handler. */\n readonly pipelines: import(\"@lunora/bindings/pipelines\").PipelineClient;";
2830
+ readonly tier: "action";
2831
+ };
2832
+ }, {
2833
+ readonly appMethod: {
2834
+ readonly configKey: "r2sql";
2835
+ readonly doc: "Wire the R2 SQL client backing `ctx.r2sql` — build it with `createR2Sql({ accountId, apiToken, bucket })` (defaults to env `R2_SQL_TOKEN` / `R2_SQL_ACCOUNT_ID` / `R2_SQL_BUCKET`).";
2836
+ readonly method: "r2sql";
2837
+ };
2838
+ readonly contextProperty: "r2sql";
2839
+ readonly key: "r2sql";
2840
+ readonly moduleSpecifier: "@lunora/bindings/r2sql";
2841
+ readonly serverCtxField: {
2842
+ readonly field: "\n /**\n * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.\n */\n readonly r2sql: import(\"@lunora/bindings/r2sql\").R2SqlClient;";
2843
+ readonly tier: "action";
2844
+ };
2845
+ }, {
2846
+ readonly contextProperty: "scheduler";
2847
+ readonly key: "scheduler";
2848
+ readonly moduleSpecifier: "@lunora/scheduler";
2849
+ }, {
2850
+ readonly contextProperty: "storage";
2851
+ readonly key: "storage";
2852
+ readonly moduleSpecifier: "@lunora/storage";
2853
+ }, {
2854
+ readonly appMethod: {
2855
+ readonly configKey: "vectors";
2856
+ readonly doc: "Wire the Vectorize index map backing `ctx.vectors`.";
2857
+ readonly method: "vectors";
2858
+ };
2859
+ readonly contextProperty: "vectors";
2860
+ readonly key: "vectors";
2861
+ readonly moduleSpecifier: "@lunora/bindings/vectors";
2862
+ }, {
2863
+ readonly contextProperty: "workflows";
2864
+ readonly key: "workflows";
2865
+ readonly moduleSpecifier: "@lunora/workflow";
2866
+ }];
2867
+ /** The literal union of every capability id — the single source of truth for `FeatureUsage`'s keys (so they cannot drift). */
2868
+ type CapabilityKey = (typeof CAPABILITY_ROWS)[number]["key"];
2869
+ /** The default codegen target — today's behavior, byte-identical goldens. */
2870
+ declare const DEFAULT_TARGET = "cloudflare";
2871
+ /**
2872
+ * Read `target` from `&lt;projectRoot>/lunora.json`.
2873
+ *
2874
+ * This lives in `@lunora/codegen` rather than `@lunora/config` — where the rest
2875
+ * of the `lunora.json` reading lives — because `@lunora/config` depends on
2876
+ * `@lunora/codegen`, not the reverse. Putting it there and importing it here
2877
+ * would invert that edge, so config delegates to this instead and there is
2878
+ * still exactly one parser for the key.
2879
+ *
2880
+ * Best-effort and deliberately unvalidated: a missing file, malformed JSONC, or
2881
+ * a non-string value all collapse to `undefined`, because those are shape
2882
+ * errors rather than a name the user meant. An unrecognized *name* is returned
2883
+ * as-is so the caller's registry lookup rejects it — swallowing a typo into the
2884
+ * default would ship an app to the wrong provider.
2885
+ * @param projectRoot Directory containing `lunora.json`.
2886
+ * @returns the declared target, or `undefined` when none is usable.
2887
+ */
2888
+ declare const readProjectTarget: (projectRoot: string) => string | undefined;
2889
+ /**
2890
+ * The target codegen should emit for: an explicit option wins, then
2891
+ * `lunora.json`, then the default.
2892
+ *
2893
+ * `runCodegen` applies this itself so a caller that forgets to pass a target
2894
+ * still emits the surface the project declared. That default matters more than
2895
+ * it looks: a call site that silently omits the target emits the *default*
2896
+ * surface with no diagnostic to notice, and the mismatch only shows up at
2897
+ * runtime on the deployed app.
2898
+ * @param projectRoot Directory containing `lunora.json`.
2899
+ * @param explicit A caller-supplied target, if any.
2900
+ * @returns the resolved target id — not guaranteed to be registered.
2901
+ */
2902
+ declare const resolveCodegenTarget: (projectRoot: string, explicit?: string) => string;
2903
+ /**
2904
+ * The target ids codegen can gate against.
2905
+ *
2906
+ * Exported so `@lunora/config` can assert that its driver registry and this
2907
+ * capability-matrix registry name the same targets. They are two id spaces for one
2908
+ * concept: a target that ships a driver but no matrix passes the CLI's
2909
+ * validation and then emits an un-gated surface, and one with a matrix but no
2910
+ * driver gates a surface nothing can deploy. Today both hold exactly
2911
+ * `cloudflare`, which is why nothing has noticed.
2912
+ * @returns the registered matrix ids, sorted.
2913
+ */
2914
+ declare const platformMatrixIds: () => ReadonlyArray<string>;
2915
+ /** An advisor-style diagnostic about a target's platform capabilities. */
2916
+ interface PlatformDiagnostic {
2917
+ /** The codegen capability this concerns, when it is feature-specific. */
2918
+ feature?: CapabilityKey;
2919
+ /** Severity. `platform_unsupported_feature` and `platform_unknown_target` are both errors — each drops or misdirects an emitted surface. */
2920
+ level: "error" | "warn";
2921
+ /** Human-readable explanation of the gap. */
2922
+ message: string;
2923
+ /** The lint id: `platform_unsupported_feature` or `platform_unknown_target`. */
2924
+ name: "platform_unknown_target" | "platform_unsupported_feature";
2925
+ /** How to resolve it. */
2926
+ remediation: string;
2927
+ /** The requested deploy target. */
2928
+ target: string;
2929
+ }
2704
2930
  /**
2705
2931
  * Committed, tracked baseline file holding the blessed structural schema
2706
2932
  * snapshot the pre-deploy drift gate diffs against. Lives in `lunora/` (NOT the
@@ -2784,6 +3010,17 @@ interface CodegenOptions {
2784
3010
  project?: Project;
2785
3011
  /** Project root containing the `lunora/` directory. */
2786
3012
  projectRoot: string;
3013
+ /**
3014
+ * The deploy target codegen tailors the emitted `ctx.*` surface to.
3015
+ * Defaults to `"cloudflare"` — whose capability matrix marks every feature
3016
+ * native or emulated, so the default output is unchanged (byte-identical
3017
+ * goldens). A target that marks a used feature unsupported omits its
3018
+ * `ctx.*` surface and reports it in {@link CodegenResult.platformDiagnostics}.
3019
+ * Only `"cloudflare"` is registered until other per-target `@lunora/platform`
3020
+ * matrices land; an unknown target emits the full surface un-gated and a
3021
+ * `platform_unknown_target` diagnostic.
3022
+ */
3023
+ target?: string;
2787
3024
  /**
2788
3025
  * Re-bless the committed schema-drift baseline (`lunora/.lunora-schema.json`)
2789
3026
  * with the current structural snapshot. The baseline is ALWAYS written on
@@ -2884,6 +3121,14 @@ interface CodegenResult {
2884
3121
  workflows: string;
2885
3122
  };
2886
3123
  outputDirectory: string;
3124
+ /**
3125
+ * Portability diagnostics for the requested {@link CodegenOptions.target}:
3126
+ * `ctx.*` features the app uses that the target does not support (omitted
3127
+ * from the emitted surface), or an unknown target. Empty for a
3128
+ * fully-supported app on the default Cloudflare target. Presentation is the
3129
+ * caller's job, like {@link CodegenResult.advisories}.
3130
+ */
3131
+ platformDiagnostics: ReadonlyArray<PlatformDiagnostic>;
2887
3132
  /**
2888
3133
  * Queues discovered from `defineQueue` exports in `lunora/queues.ts` — the
2889
3134
  * list the config layer reconciles into wrangler's `queues.producers[]` /
@@ -2998,4 +3243,4 @@ declare const secretKindOf: (value: string) => string | undefined;
2998
3243
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
2999
3244
  declare const redact: (value: string) => string;
3000
3245
  declare const VERSION = "0.0.0";
3001
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, 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 OpenRpcEmitInput, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, 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, 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, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, redact, refreshCodegenProject, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3246
+ 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 OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, 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, 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, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -3,7 +3,8 @@ export type { Finding } from '@lunora/advisor';
3
3
  import { LunoraError } from '@lunora/errors';
4
4
  export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, type Solution as LunoraSolution, type SolutionRule as LunoraSolutionRule, findSolutionByMessage as findLunoraSolution } from '@lunora/errors';
5
5
  import { Node, Project } from 'ts-morph';
6
- import { StudioFeaturesResult } from '@lunora/do';
6
+ import { StudioFeaturesResult } from '@lunora/shard-engine';
7
+ import '@lunora/platform';
7
8
  import { Schema } from '@lunora/server';
8
9
  import { JsonSchema } from '@lunora/values';
9
10
  /**
@@ -2701,6 +2702,231 @@ declare const emitOpenRpc: (input: OpenRpcEmitInput) => string;
2701
2702
  * the object returned by {@link buildOpenRpcDocument} (reused, never recomputed).
2702
2703
  */
2703
2704
  declare const emitOpenRpcModule: (document_: Record<string, unknown>) => string;
2705
+ /**
2706
+ * The canonical capability list. **Order is load-bearing** for the `emit-app.ts`
2707
+ * long-tail: the fluent methods are emitted in the order the `appMethod`-bearing
2708
+ * rows appear here, so this array is ordered to reproduce the original
2709
+ * `LONG_TAIL` sequence (ai, analytics, browser, hyperdrive, images, kv, payment,
2710
+ * r2sql, vectors). The `serverCtxField` rows are referenced by name in the ctx
2711
+ * interface templates, so their order here is not output-affecting.
2712
+ */
2713
+ declare const CAPABILITY_ROWS: readonly [{
2714
+ readonly contextProperty: "access";
2715
+ readonly key: "access";
2716
+ readonly moduleSpecifier: "@lunora/cloudflare-access";
2717
+ }, {
2718
+ readonly appMethod: {
2719
+ readonly configKey: "ai";
2720
+ readonly doc: "Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).";
2721
+ readonly method: "ai";
2722
+ };
2723
+ readonly contextProperty: "ai";
2724
+ readonly key: "ai";
2725
+ readonly moduleSpecifier: "@lunora/ai";
2726
+ }, {
2727
+ readonly appMethod: {
2728
+ readonly configKey: "analytics";
2729
+ readonly doc: "Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).";
2730
+ readonly method: "analytics";
2731
+ };
2732
+ readonly contextProperty: "analytics";
2733
+ readonly key: "analytics";
2734
+ readonly moduleSpecifier: "@lunora/bindings/analytics";
2735
+ readonly serverCtxField: {
2736
+ readonly field: "\n /** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */\n readonly analytics: import(\"@lunora/bindings/analytics\").AnalyticsClient;";
2737
+ readonly tier: "every";
2738
+ };
2739
+ }, {
2740
+ readonly appMethod: {
2741
+ readonly configKey: "browser";
2742
+ readonly doc: "Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).";
2743
+ readonly method: "browser";
2744
+ };
2745
+ readonly contextProperty: "browser";
2746
+ readonly key: "browser";
2747
+ readonly moduleSpecifier: "@lunora/browser";
2748
+ readonly serverCtxField: {
2749
+ readonly field: "\n /** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */\n readonly browser: import(\"@lunora/browser\").Browser;";
2750
+ readonly tier: "action";
2751
+ };
2752
+ }, {
2753
+ readonly contextProperty: "containers";
2754
+ readonly key: "container";
2755
+ readonly moduleSpecifier: "@lunora/container";
2756
+ }, {
2757
+ readonly contextProperty: "flags";
2758
+ readonly key: "flags";
2759
+ readonly moduleSpecifier: "@lunora/flags";
2760
+ }, {
2761
+ readonly appMethod: {
2762
+ readonly configKey: "sql";
2763
+ readonly doc: "Wire the Hyperdrive SQL client backing `ctx.sql` — build it with `createHyperdrive` + `fromPostgresJs`/`fromNodePg`/`fromMysql2`.";
2764
+ readonly method: "hyperdrive";
2765
+ };
2766
+ readonly contextProperty: "sql";
2767
+ readonly key: "hyperdrive";
2768
+ readonly moduleSpecifier: "@lunora/hyperdrive";
2769
+ readonly serverCtxField: {
2770
+ readonly field: "\n /**\n * External database access via Hyperdrive. Non-deterministic — available only in actions. Writes here are NOT tracked by Lunora live queries; subscriptions will not re-run on external DB changes.\n */\n readonly sql: import(\"@lunora/hyperdrive\").SqlClient;";
2771
+ readonly tier: "action";
2772
+ };
2773
+ }, {
2774
+ readonly appMethod: {
2775
+ readonly configKey: "images";
2776
+ readonly doc: "Override the Images binding backing `ctx.images` (defaults to `env.IMAGES`).";
2777
+ readonly method: "images";
2778
+ };
2779
+ readonly contextProperty: "images";
2780
+ readonly key: "images";
2781
+ readonly moduleSpecifier: "@lunora/bindings/images";
2782
+ readonly serverCtxField: {
2783
+ readonly field: "\n /** Cloudflare Images transforms (resize/format/optimize). Non-deterministic — available only in actions. */\n readonly images: import(\"@lunora/bindings/images\").Images;";
2784
+ readonly tier: "action";
2785
+ };
2786
+ }, {
2787
+ readonly appMethod: {
2788
+ readonly configKey: "kv";
2789
+ readonly doc: "Override the Workers KV binding backing `ctx.kv` (defaults to `env.KV`).";
2790
+ readonly method: "kv";
2791
+ };
2792
+ readonly contextProperty: "kv";
2793
+ readonly key: "kv";
2794
+ readonly moduleSpecifier: "@lunora/bindings/kv";
2795
+ readonly serverCtxField: {
2796
+ readonly field: "\n readonly kv: import(\"@lunora/bindings/kv\").Kv;";
2797
+ readonly tier: "every";
2798
+ };
2799
+ }, {
2800
+ readonly key: "mail";
2801
+ readonly moduleSpecifier: "@lunora/mail";
2802
+ }, {
2803
+ readonly contextProperty: "notify";
2804
+ readonly key: "notify";
2805
+ readonly moduleSpecifier: "@lunora/notify";
2806
+ }, {
2807
+ readonly appMethod: {
2808
+ readonly configKey: "payment";
2809
+ readonly doc: "Wire the payment options backing `ctx.payments`.";
2810
+ readonly method: "payment";
2811
+ };
2812
+ readonly contextProperty: "payments";
2813
+ readonly key: "payments";
2814
+ readonly moduleSpecifier: "@lunora/payment";
2815
+ }, {
2816
+ readonly appMethod: {
2817
+ readonly configKey: "x402";
2818
+ readonly doc: "Wire the x402 agent-wallet pay rail backing `ctx.x402` — a payment-enabled `fetch` that answers `402` challenges under a mandatory spend policy (ActionCtx-only; spends real funds).";
2819
+ readonly method: "x402";
2820
+ };
2821
+ readonly contextProperty: "x402";
2822
+ readonly key: "x402";
2823
+ readonly moduleSpecifier: "@lunora/x402/pay";
2824
+ }, {
2825
+ readonly contextProperty: "pipelines";
2826
+ readonly key: "pipelines";
2827
+ readonly moduleSpecifier: "@lunora/bindings/pipelines";
2828
+ readonly serverCtxField: {
2829
+ readonly field: "\n /** Pipelines ingestion sink (durable, R2-backed). Fire-and-forget and batched; do not read it back in-handler. */\n readonly pipelines: import(\"@lunora/bindings/pipelines\").PipelineClient;";
2830
+ readonly tier: "action";
2831
+ };
2832
+ }, {
2833
+ readonly appMethod: {
2834
+ readonly configKey: "r2sql";
2835
+ readonly doc: "Wire the R2 SQL client backing `ctx.r2sql` — build it with `createR2Sql({ accountId, apiToken, bucket })` (defaults to env `R2_SQL_TOKEN` / `R2_SQL_ACCOUNT_ID` / `R2_SQL_BUCKET`).";
2836
+ readonly method: "r2sql";
2837
+ };
2838
+ readonly contextProperty: "r2sql";
2839
+ readonly key: "r2sql";
2840
+ readonly moduleSpecifier: "@lunora/bindings/r2sql";
2841
+ readonly serverCtxField: {
2842
+ readonly field: "\n /**\n * R2 SQL over Apache Iceberg tables (window functions, DISTINCT, set operations). Non-deterministic — available only in actions. Reads here are NOT tracked by Lunora live queries.\n */\n readonly r2sql: import(\"@lunora/bindings/r2sql\").R2SqlClient;";
2843
+ readonly tier: "action";
2844
+ };
2845
+ }, {
2846
+ readonly contextProperty: "scheduler";
2847
+ readonly key: "scheduler";
2848
+ readonly moduleSpecifier: "@lunora/scheduler";
2849
+ }, {
2850
+ readonly contextProperty: "storage";
2851
+ readonly key: "storage";
2852
+ readonly moduleSpecifier: "@lunora/storage";
2853
+ }, {
2854
+ readonly appMethod: {
2855
+ readonly configKey: "vectors";
2856
+ readonly doc: "Wire the Vectorize index map backing `ctx.vectors`.";
2857
+ readonly method: "vectors";
2858
+ };
2859
+ readonly contextProperty: "vectors";
2860
+ readonly key: "vectors";
2861
+ readonly moduleSpecifier: "@lunora/bindings/vectors";
2862
+ }, {
2863
+ readonly contextProperty: "workflows";
2864
+ readonly key: "workflows";
2865
+ readonly moduleSpecifier: "@lunora/workflow";
2866
+ }];
2867
+ /** The literal union of every capability id — the single source of truth for `FeatureUsage`'s keys (so they cannot drift). */
2868
+ type CapabilityKey = (typeof CAPABILITY_ROWS)[number]["key"];
2869
+ /** The default codegen target — today's behavior, byte-identical goldens. */
2870
+ declare const DEFAULT_TARGET = "cloudflare";
2871
+ /**
2872
+ * Read `target` from `&lt;projectRoot>/lunora.json`.
2873
+ *
2874
+ * This lives in `@lunora/codegen` rather than `@lunora/config` — where the rest
2875
+ * of the `lunora.json` reading lives — because `@lunora/config` depends on
2876
+ * `@lunora/codegen`, not the reverse. Putting it there and importing it here
2877
+ * would invert that edge, so config delegates to this instead and there is
2878
+ * still exactly one parser for the key.
2879
+ *
2880
+ * Best-effort and deliberately unvalidated: a missing file, malformed JSONC, or
2881
+ * a non-string value all collapse to `undefined`, because those are shape
2882
+ * errors rather than a name the user meant. An unrecognized *name* is returned
2883
+ * as-is so the caller's registry lookup rejects it — swallowing a typo into the
2884
+ * default would ship an app to the wrong provider.
2885
+ * @param projectRoot Directory containing `lunora.json`.
2886
+ * @returns the declared target, or `undefined` when none is usable.
2887
+ */
2888
+ declare const readProjectTarget: (projectRoot: string) => string | undefined;
2889
+ /**
2890
+ * The target codegen should emit for: an explicit option wins, then
2891
+ * `lunora.json`, then the default.
2892
+ *
2893
+ * `runCodegen` applies this itself so a caller that forgets to pass a target
2894
+ * still emits the surface the project declared. That default matters more than
2895
+ * it looks: a call site that silently omits the target emits the *default*
2896
+ * surface with no diagnostic to notice, and the mismatch only shows up at
2897
+ * runtime on the deployed app.
2898
+ * @param projectRoot Directory containing `lunora.json`.
2899
+ * @param explicit A caller-supplied target, if any.
2900
+ * @returns the resolved target id — not guaranteed to be registered.
2901
+ */
2902
+ declare const resolveCodegenTarget: (projectRoot: string, explicit?: string) => string;
2903
+ /**
2904
+ * The target ids codegen can gate against.
2905
+ *
2906
+ * Exported so `@lunora/config` can assert that its driver registry and this
2907
+ * capability-matrix registry name the same targets. They are two id spaces for one
2908
+ * concept: a target that ships a driver but no matrix passes the CLI's
2909
+ * validation and then emits an un-gated surface, and one with a matrix but no
2910
+ * driver gates a surface nothing can deploy. Today both hold exactly
2911
+ * `cloudflare`, which is why nothing has noticed.
2912
+ * @returns the registered matrix ids, sorted.
2913
+ */
2914
+ declare const platformMatrixIds: () => ReadonlyArray<string>;
2915
+ /** An advisor-style diagnostic about a target's platform capabilities. */
2916
+ interface PlatformDiagnostic {
2917
+ /** The codegen capability this concerns, when it is feature-specific. */
2918
+ feature?: CapabilityKey;
2919
+ /** Severity. `platform_unsupported_feature` and `platform_unknown_target` are both errors — each drops or misdirects an emitted surface. */
2920
+ level: "error" | "warn";
2921
+ /** Human-readable explanation of the gap. */
2922
+ message: string;
2923
+ /** The lint id: `platform_unsupported_feature` or `platform_unknown_target`. */
2924
+ name: "platform_unknown_target" | "platform_unsupported_feature";
2925
+ /** How to resolve it. */
2926
+ remediation: string;
2927
+ /** The requested deploy target. */
2928
+ target: string;
2929
+ }
2704
2930
  /**
2705
2931
  * Committed, tracked baseline file holding the blessed structural schema
2706
2932
  * snapshot the pre-deploy drift gate diffs against. Lives in `lunora/` (NOT the
@@ -2784,6 +3010,17 @@ interface CodegenOptions {
2784
3010
  project?: Project;
2785
3011
  /** Project root containing the `lunora/` directory. */
2786
3012
  projectRoot: string;
3013
+ /**
3014
+ * The deploy target codegen tailors the emitted `ctx.*` surface to.
3015
+ * Defaults to `"cloudflare"` — whose capability matrix marks every feature
3016
+ * native or emulated, so the default output is unchanged (byte-identical
3017
+ * goldens). A target that marks a used feature unsupported omits its
3018
+ * `ctx.*` surface and reports it in {@link CodegenResult.platformDiagnostics}.
3019
+ * Only `"cloudflare"` is registered until other per-target `@lunora/platform`
3020
+ * matrices land; an unknown target emits the full surface un-gated and a
3021
+ * `platform_unknown_target` diagnostic.
3022
+ */
3023
+ target?: string;
2787
3024
  /**
2788
3025
  * Re-bless the committed schema-drift baseline (`lunora/.lunora-schema.json`)
2789
3026
  * with the current structural snapshot. The baseline is ALWAYS written on
@@ -2884,6 +3121,14 @@ interface CodegenResult {
2884
3121
  workflows: string;
2885
3122
  };
2886
3123
  outputDirectory: string;
3124
+ /**
3125
+ * Portability diagnostics for the requested {@link CodegenOptions.target}:
3126
+ * `ctx.*` features the app uses that the target does not support (omitted
3127
+ * from the emitted surface), or an unknown target. Empty for a
3128
+ * fully-supported app on the default Cloudflare target. Presentation is the
3129
+ * caller's job, like {@link CodegenResult.advisories}.
3130
+ */
3131
+ platformDiagnostics: ReadonlyArray<PlatformDiagnostic>;
2887
3132
  /**
2888
3133
  * Queues discovered from `defineQueue` exports in `lunora/queues.ts` — the
2889
3134
  * list the config layer reconciles into wrangler's `queues.producers[]` /
@@ -2998,4 +3243,4 @@ declare const secretKindOf: (value: string) => string | undefined;
2998
3243
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
2999
3244
  declare const redact: (value: string) => string;
3000
3245
  declare const VERSION = "0.0.0";
3001
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, 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 OpenRpcEmitInput, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, 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, 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, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, redact, refreshCodegenProject, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
3246
+ 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 OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, 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, 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, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, 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-BCEfzLT0.mjs";import{CodegenDiagnosticError as c,diagnosticAt as n}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as l,discoverAgents as E}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as u}from"./packem_shared/discoverAuthApiCalls-CEk3J0kc.mjs";import{CONTAINERS_FILENAME as v,discoverContainers as N}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as R}from"./packem_shared/discoverCrons-kIgM9ZJC.mjs";import{FLAGS_FILENAME as h,discoverFlags as C}from"./packem_shared/FLAGS_FILENAME-CQDN7BKc.mjs";import{discoverFunctions as _}from"./packem_shared/discoverFunctions-DnqHgv0t.mjs";import{default as L}from"./packem_shared/discoverHttpRoutes-CLn3VDRI.mjs";import{default as T}from"./packem_shared/discoverInserts-Cn-CLKET.mjs";import{default as D}from"./packem_shared/discoverMaskProcedures-fZtvsy8v.mjs";import{default as H}from"./packem_shared/discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as W,discoverMutators as G}from"./packem_shared/MUTATORS_FILENAME-3Akvs4aT.mjs";import{default as V}from"./packem_shared/discoverNondeterministicCalls-Cl7qNL0J.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as y,discoverNotifyConfig as z}from"./packem_shared/NOTIFY_FILENAME-B2lXWa7r.mjs";import{E as j}from"./packem_shared/discover-queries-LfER8HbK.mjs";import{QUEUES_FILENAME as B,discoverQueues as J}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as $}from"./packem_shared/discoverR2sqlCalls-CMNfDWlq.mjs";import{discoverRlsMetadata as Z,default as ee}from"./packem_shared/discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as re}from"./packem_shared/discoverSandboxUsage-Bn1X9COt.mjs";import{default as se}from"./packem_shared/discoverSchema-Cy4OQ0Cu.mjs";import{SHAPES_FILENAME as ie,discoverShapes as me}from"./packem_shared/SHAPES_FILENAME-maut3z1K.mjs";import{default as pe}from"./packem_shared/discoverStorageRulesMetadata-CL8J41rX.mjs";import{WORKFLOWS_FILENAME as ce,discoverWorkflows as ne}from"./packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{w as le,H as Ee,h as xe,b as ue,Q as Ae,c as ve,t as Ne,l as Oe,$ as Re,v as Me,r as he,d as Ce,K as Ie,u as _e}from"./packem_shared/emit-BtiV37rG.mjs";import{emitApp as Le}from"./packem_shared/emitApp-Bc3G4eki.mjs";import{buildOpenApiDocument as Te,emitOpenApi as Pe,emitOpenApiModule as De}from"./packem_shared/buildOpenApiDocument-D6xm3JqM.mjs";import{OPENRPC_VERSION as He,buildOpenRpcDocument as be,emitOpenRpc as We,emitOpenRpcModule as Ge}from"./packem_shared/OPENRPC_VERSION-BPT6vyLU.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Ve,createCodegenProject as ke,refreshCodegenProject as we,runCodegen as ye}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-3_Zzh73G.mjs";import{SchemaSnapshotParseError as Ke,buildSchemaSnapshot as je,evaluateSchemaDrift as qe,parseSchemaSnapshot as Be}from"./packem_shared/SchemaSnapshotParseError-0KRzSjo4.mjs";import{schemaFromIr as Ye}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as Xe,validatorIrToJsonSchema as Ze}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as oo,secretKindOf as ro}from"./packem_shared/redact-CQ8-to6l.mjs";import{MESSAGE_SOLUTIONS as so,findSolutionByMessage as ao}from"@lunora/errors";const e="0.0.0";export{l as AGENTS_FILENAME,v as CONTAINERS_FILENAME,c as CodegenDiagnosticError,h as FLAGS_FILENAME,le as GENERATED_HEADER,Xe as LUNORA_ERROR_CODES,so as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,w as NOTIFY_FILENAME,He as OPENRPC_VERSION,B as QUEUES_FILENAME,Ve as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ie as SHAPES_FILENAME,Ke as SchemaSnapshotParseError,e as VERSION,ce as WORKFLOWS_FILENAME,Te as buildOpenApiDocument,be as buildOpenRpcDocument,je as buildSchemaSnapshot,ke as createCodegenProject,n as diagnosticAt,s as diffSchemaSnapshots,E as discoverAgents,u as discoverAuthApiCalls,N as discoverContainers,R as discoverCrons,C as discoverFlags,_ as discoverFunctions,L as discoverHttpRoutes,T as discoverInserts,D as discoverMaskProcedures,H as discoverMigrations,G as discoverMutators,V as discoverNondeterministicCalls,y as discoverNotifyCalls,z as discoverNotifyConfig,j as discoverQueries,J as discoverQueues,$ as discoverR2sqlCalls,Z as discoverRlsMetadata,ee as discoverRlsProcedures,re as discoverSandboxUsage,se as discoverSchema,me as discoverShapes,pe as discoverStorageRulesMetadata,ne as discoverWorkflows,Ee as emitAgents,xe as emitApi,Le as emitApp,ue as emitCollections,Ae as emitContainers,ve as emitCrons,Ne as emitDataModel,Oe as emitDrizzleSchema,Re as emitFunctions,Pe as emitOpenApi,De as emitOpenApiModule,We as emitOpenRpc,Ge as emitOpenRpcModule,Me as emitServer,he as emitShard,Ce as emitVectors,Ie as emitWorkflows,_e as emitWranglerCronTriggers,qe as evaluateSchemaDrift,ao as findLunoraSolution,m as formatAdvisories,d as lintSchema,Be as parseSchemaSnapshot,oo as redact,we as refreshCodegenProject,ye as runCodegen,Ye as schemaFromIr,ro as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,Ze 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 p}from"./packem_shared/formatAdvisories-BCEfzLT0.mjs";import{CodegenDiagnosticError as c,diagnosticAt as n}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as l,discoverAgents as E}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as A}from"./packem_shared/discoverAuthApiCalls-CEk3J0kc.mjs";import{CONTAINERS_FILENAME as v,discoverContainers as N}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as R}from"./packem_shared/discoverCrons-kIgM9ZJC.mjs";import{FLAGS_FILENAME as C,discoverFlags as h}from"./packem_shared/FLAGS_FILENAME-CQDN7BKc.mjs";import{discoverFunctions as I}from"./packem_shared/discoverFunctions-DnqHgv0t.mjs";import{default as L}from"./packem_shared/discoverHttpRoutes-CLn3VDRI.mjs";import{default as T}from"./packem_shared/discoverInserts-Cn-CLKET.mjs";import{default as D}from"./packem_shared/discoverMaskProcedures-fZtvsy8v.mjs";import{default as H}from"./packem_shared/discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as G,discoverMutators as W}from"./packem_shared/MUTATORS_FILENAME-3Akvs4aT.mjs";import{default as V}from"./packem_shared/discoverNondeterministicCalls-Cl7qNL0J.mjs";import{NOTIFY_FILENAME as k,discoverNotifyCalls as w,discoverNotifyConfig as y}from"./packem_shared/NOTIFY_FILENAME-B2lXWa7r.mjs";import{E as K}from"./packem_shared/discover-queries-LfER8HbK.mjs";import{QUEUES_FILENAME as B,discoverQueues as J}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as $}from"./packem_shared/discoverR2sqlCalls-CMNfDWlq.mjs";import{discoverRlsMetadata as Z,default as ee}from"./packem_shared/discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as re}from"./packem_shared/discoverSandboxUsage-Bn1X9COt.mjs";import{default as se}from"./packem_shared/discoverSchema-Cy4OQ0Cu.mjs";import{SHAPES_FILENAME as ie,discoverShapes as me}from"./packem_shared/SHAPES_FILENAME-maut3z1K.mjs";import{default as pe}from"./packem_shared/discoverStorageRulesMetadata-CL8J41rX.mjs";import{WORKFLOWS_FILENAME as ce,discoverWorkflows as ne}from"./packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{w as le,H as Ee,h as xe,b as Ae,Q as ue,c as ve,t as Ne,l as Oe,$ as Re,v as Me,r as Ce,d as he,K as ge,u as Ie}from"./packem_shared/emit-BtiV37rG.mjs";import{emitApp as Le}from"./packem_shared/emitApp-Bc3G4eki.mjs";import{buildOpenApiDocument as Te,emitOpenApi as Pe,emitOpenApiModule as De}from"./packem_shared/buildOpenApiDocument-D6xm3JqM.mjs";import{OPENRPC_VERSION as He,buildOpenRpcDocument as be,emitOpenRpc as Ge,emitOpenRpcModule as We}from"./packem_shared/OPENRPC_VERSION-BPT6vyLU.mjs";import{DEFAULT_TARGET as Ve,platformMatrixIds as je,readProjectTarget as ke,resolveCodegenTarget as we}from"./packem_shared/DEFAULT_TARGET-BYPEwgZu.mjs";import{SCHEMA_SNAPSHOT_FILENAME as ze,createCodegenProject as Ke,refreshCodegenProject as qe,runCodegen as Be}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-FjKlVIV5.mjs";import{SchemaSnapshotParseError as Ye,buildSchemaSnapshot as $e,evaluateSchemaDrift as Xe,parseSchemaSnapshot as Ze}from"./packem_shared/SchemaSnapshotParseError-0KRzSjo4.mjs";import{schemaFromIr as oo}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as to,validatorIrToJsonSchema as so}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as io,secretKindOf as mo}from"./packem_shared/redact-CQ8-to6l.mjs";import{MESSAGE_SOLUTIONS as fo,findSolutionByMessage as co}from"@lunora/errors";const e="0.0.0";export{l as AGENTS_FILENAME,v as CONTAINERS_FILENAME,c as CodegenDiagnosticError,Ve as DEFAULT_TARGET,C as FLAGS_FILENAME,le as GENERATED_HEADER,to as LUNORA_ERROR_CODES,fo as LUNORA_SOLUTION_RULES,G as MUTATORS_FILENAME,k as NOTIFY_FILENAME,He as OPENRPC_VERSION,B as QUEUES_FILENAME,ze as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ie as SHAPES_FILENAME,Ye as SchemaSnapshotParseError,e as VERSION,ce as WORKFLOWS_FILENAME,Te as buildOpenApiDocument,be as buildOpenRpcDocument,$e as buildSchemaSnapshot,Ke as createCodegenProject,n as diagnosticAt,s as diffSchemaSnapshots,E as discoverAgents,A as discoverAuthApiCalls,N as discoverContainers,R as discoverCrons,h as discoverFlags,I as discoverFunctions,L as discoverHttpRoutes,T as discoverInserts,D as discoverMaskProcedures,H as discoverMigrations,W as discoverMutators,V as discoverNondeterministicCalls,w as discoverNotifyCalls,y as discoverNotifyConfig,K as discoverQueries,J as discoverQueues,$ as discoverR2sqlCalls,Z as discoverRlsMetadata,ee as discoverRlsProcedures,re as discoverSandboxUsage,se as discoverSchema,me as discoverShapes,pe as discoverStorageRulesMetadata,ne as discoverWorkflows,Ee as emitAgents,xe as emitApi,Le as emitApp,Ae as emitCollections,ue as emitContainers,ve as emitCrons,Ne as emitDataModel,Oe as emitDrizzleSchema,Re as emitFunctions,Pe as emitOpenApi,De as emitOpenApiModule,Ge as emitOpenRpc,We as emitOpenRpcModule,Me as emitServer,Ce as emitShard,he as emitVectors,ge as emitWorkflows,Ie as emitWranglerCronTriggers,Xe as evaluateSchemaDrift,co as findLunoraSolution,m as formatAdvisories,d as lintSchema,Ze as parseSchemaSnapshot,je as platformMatrixIds,ke as readProjectTarget,io as redact,qe as refreshCodegenProject,we as resolveCodegenTarget,Be as runCodegen,oo as schemaFromIr,mo as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,so as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import{existsSync as l,readFileSync as c}from"node:fs";import{join as u}from"node:path";import{CLOUDFLARE_CAPABILITIES as g}from"@lunora/platform";import{parse as m}from"jsonc-parser";const f="cloudflare",p="lunora.json",d=t=>{const e=u(t,p);if(!l(e))return;let a;try{a=c(e,"utf8")}catch{return}const s=[],o=m(a,s,{allowTrailingComma:!0});if(s.length>0||o===null||typeof o!="object")return;const{target:r}=o;return typeof r=="string"&&r.length>0?r:void 0},C=(t,e)=>e??d(t)??f,n={cloudflare:g},j=()=>Object.keys(n).toSorted((t,e)=>t.localeCompare(e)),y={ai:"ai",analytics:"analytics",browser:"browser",container:"containers",hyperdrive:"hyperdrive",kv:"keyValueStore",mail:"mail",pipelines:"pipelines",scheduler:"scheduler",storage:"objectStorage",vectors:"vectorStore",workflows:"workflows"},h=(t,e,a)=>{const s={...t},o=[];for(const[r,i]of Object.entries(y))t[r]&&e.features[i]?.level==="unsupported"&&(s[r]=!1,o.push({feature:r,level:"error",message:`${e.name} does not support "${r}" (ctx.${r}). Its surface was omitted from the generated types.`,name:"platform_unsupported_feature",remediation:`Remove the ctx.${r} usage, or deploy to a target whose capability matrix marks "${i}" as native or emulated.`,target:a}));return{diagnostics:o,usage:s}},x=(t,e)=>{const a=n[e];return a===void 0?{diagnostics:[{level:"error",message:`Unknown deploy target "${e}" — no capability matrix is registered for it. Codegen emitted the full Cloudflare surface un-gated.`,name:"platform_unknown_target",remediation:`Use a registered target (${Object.keys(n).join(", ")}) or install the target's @lunora/platform-${e} package.`,target:e}],usage:{...t}}:h(t,a,e)};export{f as DEFAULT_TARGET,p as PROJECT_CONFIG_FILE,h as gateAgainstMatrix,x as gatePlatformFeatures,j as platformMatrixIds,d as readProjectTarget,C as resolveCodegenTarget};
@@ -0,0 +1,5 @@
1
+ import{existsSync as E,readFileSync as $e,mkdirSync as Bt,writeFileSync as Vt,rmSync as Ut}from"node:fs";import{join as g,dirname as pe}from"node:path";import{performance as me}from"node:perf_hooks";import{runAdvisor as Wt}from"@lunora/advisor";import{LunoraError as B}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as Ze}from"ts-morph";import{serializeSchemaSnapshot as Gt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as Ht}from"./formatAdvisories-BCEfzLT0.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as f,classifyProcedureCall as K,inlineHandler as _t,procedureHandler as pt,chainUsesWrappedCall as mt,isDatabaseAccessor as C,chainHasStep as Qt,discoverFunctions as Jt}from"./discoverFunctions-DnqHgv0t.mjs";import{discoverAgents as Xt}from"./AGENTS_FILENAME-BesaDYkL.mjs";import{i as w,a as F,e as h,c as S,r as Zt,s as H,b as Yt,d as es,E as ts}from"./discover-queries-LfER8HbK.mjs";import ss from"./discoverAuthApiCalls-CEk3J0kc.mjs";import{discoverContainers as rs}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import ns from"./discoverCrons-kIgM9ZJC.mjs";import{diagnosticAt as _}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Q}from"./module-specifiers-8FEEiUcv.mjs";import{a as xe,n as is,t as os,h as as,v as cs,$ as us,r as ls,b as ds,Q as gs,K as fs,H as ps,G as ms,c as xs,d as hs,l as Es,f as ys,u as $s}from"./emit-BtiV37rG.mjs";import{discoverFlagKeys as As}from"./FLAGS_FILENAME-CQDN7BKc.mjs";import Ss from"./discoverHttpRoutes-CLn3VDRI.mjs";import Ns from"./discoverInserts-Cn-CLKET.mjs";import vs,{discoverMaskStrategies as bs,discoverMaskMetadata as Ps}from"./discoverMaskProcedures-fZtvsy8v.mjs";import ws from"./discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as Is,isDefineMutatorCallee as Ls,discoverMutators as Os}from"./MUTATORS_FILENAME-3Akvs4aT.mjs";import Fs from"./discoverNondeterministicCalls-Cl7qNL0J.mjs";import{discoverNotifyConfig as Ts,discoverNotifyCalls as Ds}from"./NOTIFY_FILENAME-B2lXWa7r.mjs";import{discoverQueues as Cs}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Ks from"./discoverR2sqlCalls-CMNfDWlq.mjs";import ks,{discoverRlsMetadata as Rs}from"./discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as js}from"./discoverSandboxUsage-Bn1X9COt.mjs";import Ms from"./discoverSchema-Cy4OQ0Cu.mjs";import{secretKindOf as zs,redact as qs}from"./redact-CQ8-to6l.mjs";import{discoverShapes as Bs}from"./SHAPES_FILENAME-maut3z1K.mjs";import Vs from"./discoverStorageRulesMetadata-CL8J41rX.mjs";import{e as Us}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as Ws}from"./WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{emitApp as Gs}from"./emitApp-Bc3G4eki.mjs";import{buildOpenApiDocument as Hs,emitOpenApiModule as _s}from"./buildOpenApiDocument-D6xm3JqM.mjs";import{buildOpenRpcDocument as Qs,emitOpenRpcModule as Js}from"./OPENRPC_VERSION-BPT6vyLU.mjs";import{gatePlatformFeatures as Xs,resolveCodegenTarget as Zs}from"./DEFAULT_TARGET-BYPEwgZu.mjs";import{buildSchemaSnapshot as Ys}from"./SchemaSnapshotParseError-0KRzSjo4.mjs";const xt=new Set(["delete","get","head","options","patch","post","put"]),er=new Set(["handler","stream"]),tr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ye=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),sr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!xt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},rr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||xt.has(r.getName()))break;s=r.getExpression()}return sr(s)},nr=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(Ye.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Ye.has(s.getText()))return!0}return!1},ir=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!er.has(r.getName()))return;const n=rr(s);if(!n||!tr.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&nr(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},or=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=ir(n,t);o&&s.push(o)}return s},ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...or(n,f(t,r)))}return s},cr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",ur=(e,t)=>{if(!cr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)||F(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},lr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ur(r,t);n&&s.push(n)}return s},dr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...lr(n,f(t,r)))}return s},gr=new Set(["generateText","streamText"]),fr=new Set(["messages","prompt","system"]),pr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],mr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of pr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},xr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=mr(t);if(s!==void 0)return s}},hr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Er=e=>{if(Zt(e))return!0;const t=hr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},yr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!fr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Er(s))return!0}return!1},$r=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!gr.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(S(c.getExpression())==="tool"&&(a=xr(c),a!==void 0))break;a!==void 0&&s.push({exportName:h(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:yr(o)})}return s},Ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...$r(n,f(t,r)))}return s},Sr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Nr=(e,t)=>{if(!Sr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},vr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Nr(r,t);n&&s.push(n)}return s},br=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...vr(n,f(t,r)))}return s},ht=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Pr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:ht(r)}},wr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const n=r.getExpression();if(!i.isPropertyAccessExpression(n))break;if(n.getName()==="input"){const o=r.getArguments()[0];o&&i.isObjectLiteralExpression(o)?(t.push(o),s||=ht(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},Et=(e,t)=>t?wr(t):Pr(e),Ir=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),Lr=/\.check\(|\.meta\(|length|max/iu,Or=/\bv\.any\s*\(/u,Fr=/\bv\.string\s*\(/u,Tr=e=>Or.test(e),Dr=e=>Fr.test(e)&&!Lr.test(e),Cr=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();Tr(a)?t.push(c):Dr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Kr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const{objects:n}=Et(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=Cr(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},kr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Kr(n,t);o&&s.push(o)}return s},Rr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...kr(n,f(t,r)))}return s},N=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},he=e=>e?.getKind()===u.TrueKeyword,jr=e=>e?.getKind()===u.FalseKeyword,Mr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,zr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),qr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),Br=e=>e!==void 0&&i.isCallExpression(e)&&zr.has(S(e.getExpression())??""),Vr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Ur=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),r=N(e,"session");return{analyzable:!0,disableCsrfCheck:he(N(t,"disableCSRFCheck")),emailPasswordEnabled:he(N(s,"enabled")),requireEmailVerification:he(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:qr(N(e,"plugins"))&&Br(N(e,"database")),secureCookiesDisabled:jr(N(t,"useSecureCookies")),sessionFreshAgeZero:Mr(N(r,"freshAge")),trustedOriginsWildcard:Vr(N(e,"trustedOrigins"))}},Wr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Gr=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?Ur(s):Wr();return{exportName:h(e),file:t,line:e.getStartLineNumber(),...n}},Hr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Gr(r,t);n&&s.push(n)}return s},_r=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Hr(n,f(t,r)))}return s},Qr=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Jr=(e,t,s)=>{const r=Qr(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:r}},Xr=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=Jr(n,t,s);o&&r.push(o)}return r},J=(e,t,s)=>{const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...Xr(o,f(t,n),s))}return r},Zr=new Set(["content","pdf","scrape","screenshot"]),Yr=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Zr}),en=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),tn=new Set(["RateLimiter"]),sn=new Set(["extend"]),yt=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},et=e=>e&&i.isObjectLiteralExpression(e)?yt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},rn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},nn=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?rn(e):void 0},on=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&nn(t.getBody());return s?yt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},an=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());n!==void 0&&(en.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...et(r.getArguments()[0])}):sn.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...on(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=S(r.getExpression());n===void 0||!tn.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...et(r.getArguments()[0])})}return s},cn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...an(n,f(t,r)))}return s},tt="ctx.containers.",un=e=>{if(!e.startsWith(tt))return!1;const t=e.slice(tt.length);return t.length>0&&!t.includes(".")},ln=(e,t)=>J(e,t,{argIndex:0,matchReceiver:un,methods:new Set(["get"])}),dn=new Set(["allow","deny","setAllowed"]),gn=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},fn=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!gn(e)))return{detail:"enableInternet: true",exportName:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},pn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!dn.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},mn=(e,t)=>fn(e,t)??pn(e,t),xn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=mn(r,t);n&&s.push(n)}return s},hn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xn(n,f(t,r)))}return s},En="env.ts",yn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},$n=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},An=e=>{if(i.isIdentifier(e))return yn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&$n(t)}return!1},Sn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!An(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},Nn=(e,t)=>{const s=g(t,En);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=Sn(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},vn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),bn=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return vn.has(s)?s:void 0},Pn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},wn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=bn(a);if(c===void 0)continue;const l=a.getArguments()[0],p=l&&i.isObjectLiteralExpression(l)?Pn(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:p.analyzable,emptyKeys:p.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:p.presentKeys})}}return s},In=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Ln=new Set(["dbRateLimit","rateLimit"]),On=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},Fn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Tn=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=In.get(s);if(r!==void 0)return{callee:s,exportName:h(e),failOpen:On(e.getArguments()[r]),file:t,limitName:Ln.has(s)?Fn(e):"",line:e.getStartLineNumber()}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Tn(r,t);n&&s.push(n)}return s},Cn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(n,f(t,r)))}return s},Kn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},kn=(e,t)=>{const s=Object.fromEntries(xe.map(r=>[r.key,!1]));for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Kn(n);for(const c of xe)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(xe.every(c=>s[c.key]))break}return s},Rn=["providerSubscriptionId","state"],jn=["providerEventId","processedAt"],st=(e,t)=>t.every(s=>s in e.shape),Mn=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&st(t,Rn)&&st(s,jn)},zn=(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")}),qn=e=>i.isIdentifier(e)&&e.getText()==="ctx",Bn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&qn(t.getExpression())},Vn=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},Un=(e,t)=>{if(!Bn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=Vn(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:h(e),file:t,key:n,line:e.getStartLineNumber()}},Wn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Un(r,t);n&&s.push(n)}return s},Gn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Wn(n,f(t,r)))}return s},Hn=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},_n=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Qn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))Hn(a)&&s.push({file:o,indexName:_n(a),line:a.getStartLineNumber()})}return s},Jn=new Set(["delete","get","head","options","patch","post","put"]),Xn=new Set(["handler","stream"]),Zn=new Set(["runAction","runMutation"]),Yn=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),U=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,rt=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,nt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},it=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(Zn.has(a)&&U(c,t))return a;if(Yn.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&U(c.getExpression(),t))return`db.${a}`}},ot=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&U(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!U(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},ei=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Xn.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(Jn.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},ti=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=rt(e.getArguments()[0]),l=c&&nt(c,!0);if(!c||l===void 0)return;const p=it(c,l);return p===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ot(c,l),sideEffect:p}}const r=ei(e);if(r===void 0)return;const n=rt(e.getArguments()[0]),o=n&&nt(n,!1);if(!n||o===void 0)return;const a=it(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:ot(n,o),sideEffect:a}},si=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ti(r,t);n&&s.push(n)}return s},ri=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...si(n,f(t,r)))}return s},ni=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ii=new Set(["append","set"]),Ae=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",$t=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",at=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>ni.has(Ae(s.getExpression()))&&es(s,t)),oi=(e,t)=>{if(at(e,t))return!0;const s=H(e);return s!==void 0&&at(s,t)},ye=(e,t)=>Yt(e,t)&&!oi(e,t),ai=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=H(e);return t!==void 0&&i.isNewExpression(t)&&Ae(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=H(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Se=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:$t(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=W(r.getExpression());n!==void 0&&Se(n,t,s)}},At=(e,t)=>{const s=W(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=W(r.getInitializer());n!==void 0&&Se(n,"response-init",t)},ci=(e,t)=>{const s=Ae(e.getExpression());if(s==="Response")At(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&Se(r,"headers-ctor",t)}},ui=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){At(e.getArguments()[1],t);return}if(ii.has(r)&&ai(n)){const o=e.getArguments()[1];o!==void 0&&ye(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:$t(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},li=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))ci(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))ui(s,t)},di=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=_t(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return li(r,{exportName:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},gi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...di(r,t));return s},fi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...gi(n,f(t,r)))}return s},St="identity.ts",pi=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},mi=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},xi=e=>{if(i.isIdentifier(e))return pi(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&mi(t)}return!1},hi=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!xi(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},Ei=(e,t)=>{const s=g(t,St);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=hi(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},yi=new Set(["auth","context.auth","ctx.auth"]),$i="userId",Ai=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Si=(e,t)=>{const s=g(t,St);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(S(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?Ai(o):void 0}},ct=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return yi.has(e.getExpression().getText())?e:void 0},Ni=e=>{if(i.isPropertyAccessExpression(e)&&ct(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&ct(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},vi=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=Ni(n);o!==void 0&&r.push({declared:o===$i||s.has(o),exportName:h(n),file:t,key:o,line:n.getStartLineNumber()})}return r},bi=(e,t)=>{const s=Si(e,t);if(s===void 0)return[];const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...vi(o,f(t,n),s))}return r},Pi=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},wi=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=Pi(s);if(!(!r||!w(r)||F(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},Ii=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=wi(r,t);n&&s.push(n)}return s},Li=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ii(n,f(t,r)))}return s},Oi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Fi=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Oi}),Ti=new Set(["queue","send"]),ut=new Set(["bcc","cc","to"]),Di=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ti.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Ci=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return ut.has(t.getName())&&w(r)&&!F(r)}if(!i.isPropertyAssignment(t)||!ut.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!F(s)}):!1,Ki=(e,t)=>{const s=Di(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Ci(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},ki=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ki(r,t);n&&s.push(n)}return s},Ri=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ki(n,f(t,r)))}return s},ji=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Mi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},zi=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return Ls(s.getExpression())?s:void 0},qi=e=>{const t=zi(e),s=t===void 0?void 0:Mi(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>ji(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Bi=e=>e.getVariableDeclarations().flatMap(t=>qi(t)),Vi=(e,t)=>{const s=g(t,Is);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Bi(r)},Ui=new Set(["delete","get","patch"]),Wi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Gi=new Set(["auth","identity","session","user"]),Hi=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),_i=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!C(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Qi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},Ji=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),Xi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,Zi=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>Ji(s.getExpression(),t)&&Xi(s.getThenStatement())),Yi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!Ui.has(n))continue;const o=r.getExpression();if(!(C(o)||i.isPropertyAccessExpression(o)&&C(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},eo=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},to=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>eo(s)==="ctx")),so=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Hi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),ro=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(Wi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Gi.has(t.getName()))return!0}return to(e)||so(e)},no=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=pt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&mt(r.receiver,"use","rls"),a=ro(n),c=new Set,l=[];for(const p of n.getDescendantsOfKind(u.CallExpression)){const y=_i(p);if(y===void 0)continue;const I=Qi(p);if(I===void 0||c.has(I)||!Zi(n,I))continue;const k=Yi(n,I);k!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),mentionsOwnership:a,sinkMethod:k,table:y,usesRls:o,visibility:r.visibility}))}return l},io=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...no(c,o))}return s},oo=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ao=new Set(["insert","insertManyUnsafe","patch","replace"]),co=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ao.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},uo=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},lo=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!oo.has(a))&&w(c)&&!F(c)&&n.push({exportName:h(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},go=(e,t)=>{const s=co(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?uo(r,s).flatMap(n=>lo(n,s,e,t)):[]},fo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...go(r,t));return s},po=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fo(n,f(t,r)))}return s},mo=e=>{const t=g(e,"package.json");if(!E(t))return new Set;try{const s=JSON.parse($e(t,"utf8")),r=new Set;for(const n of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const o=s[n];if(o!==null&&typeof o=="object")for(const a of Object.keys(o))r.add(a)}return r}catch{return new Set}},xo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ho=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Eo=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ho(t.getInitializer()):void 0},yo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!xo.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?Eo(o):void 0;s.push({callee:n,exportName:h(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},$o=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yo(n,f(t,r)))}return s},Ao=new Set(["defineQueue","defineWorkflow"]),So=new Set(["run","runAction","runMutation","runQuery"]),No=new Set(["api","internal"]),vo=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},bo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Nt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},vt=(e,t)=>e===t||e.startsWith(`${t}.`),bt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},lt=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},Pt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>lt(s));return i.isIdentifier(e)&&lt(e)&&t.push(e),t},Po=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},wo=e=>{const t=Nt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Io=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:wo(e),n=new Set,o=a=>bt(a).some(c=>r.some(l=>vt(c.getText(),l)))?!0:Pt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Po(a))n.add(l)}return{names:n,prefixes:r}},Lo=(e,t)=>bt(e).some(s=>t.prefixes.some(r=>vt(s.getText(),r)))?!0:Pt(e).some(s=>t.names.has(s.getText())),Oo=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!No.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},Fo=(e,t,s)=>{const r=Nt(e,0);if(r===void 0)return[];const n=Io(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!So.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!Lo(l,n))continue;const p=Oo(a.getArguments()[0]);p!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:h(a),line:a.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return o},To=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=vo(r);if(n===void 0||!Ao.has(n))continue;const o=bo(r);o!==void 0&&s.push(...Fo(o,n==="defineQueue"?"queue":"workflow",t))}return s},Do=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...To(n,f(t,r)))}return s},dt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},Co=/account|credential|member|passkey|session|user/iu,Ko=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},ko=(e,t)=>{const{objects:s,opaque:r}=Et(e,t);return Ir(s).some(n=>Ko(n))?!0:r?void 0:!1},Ne=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Ro=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},jo=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},V={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Mo=e=>{const t=jo(e),s=t?Ne(t):void 0;if(t&&s==="protectPublic"){const r=Ro(t);return{...V,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in dt?{...V,[dt[s]]:!0}:V},zo=e=>{const t={...V};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=Mo(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},qo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insert")return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!!(r&&i.isStringLiteral(r)&&Co.test(r.getLiteralText()))},Bo=new Set(["create","runAfter","runAt","send","sendBatch"]),Vo=new Set(["queues","scheduler","workflows"]),Uo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Bo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Vo.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Wo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},wt=new Set(["generateObject","generateText","streamObject","streamText"]),Go=e=>{const t=Ne(e);return t!==void 0&&wt.has(t)},Ho=e=>{const t=Ne(e);if(t===void 0||!wt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},_o=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"]),q=(e,t)=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),Zo=e=>e.getDescendantsOfKind(u.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),gt="lunora-advisor-exempt",Yo=/^[\s*/]+/u,ea=/[\w-]/u,ta=e=>{const t=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
2
+ `);for(const s of t.split(`
3
+ `)){const r=s.replace(Yo,"");if(!r.startsWith(gt))continue;const n=r.slice(gt.length);if(ea.test(n.charAt(0)))continue;const o=n.indexOf("--");return{exempt:!0,exemptReason:(o===-1?"":n.slice(o+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},sa=e=>{let t=!1,s=!1,r=!1,n=!1,o=!1;for(const a of e.getDescendantsOfKind(u.CallExpression))if(qo(a)&&(o=!0),Uo(a)&&(t=!0),Wo(a)&&(n=!0),Go(a)&&(s=!0),Ho(a)&&(r=!0),o&&t&&n&&r)break;return{callsMail:q(e,Jo),emitsEvent:q(e,_o),fanOut:t,handlesErrors:e.getDescendantsOfKind(u.TryStatement).length>0,reachesOutbound:q(e,Xo),runsAiGeneration:s||q(e,Qo),throwsBareError:Zo(e),unboundedAiGeneration:r,usesInsertManyUnsafe:n,writesUserTable:o}},ra=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?zo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1};return{...sa(e),...ta(e),...n,exportName:e.getName(),file:t,hasEmailArg:ko(s,r.receiver),kind:r.kind,visibility:r.visibility}},na=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=ra(n,t);o&&s.push(o)}return s},ia=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...na(n,f(t,r)))}return s},oa=new Set(["dbRateLimit","rateLimit"]),aa=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},ca=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},ua=e=>i.isArrowFunction(e)?e.getBody():e,la=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!oa.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=aa(r);if(!n)return;const o=ua(n);if(!(!w(o)||F(o)))return{callee:s,exportName:h(e),file:t,limitName:ca(e),line:e.getStartLineNumber()}},da=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=la(r,t);n&&s.push(n)}return s},ga=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...da(n,f(t,r)))}return s},fa=new Set(["findFirst","findFirstOrThrow","findMany","get"]),pa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!fa.has(t.getName()))return;const s=t.getExpression();if(C(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&C(s.getExpression()))return s.getName()},ma=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&C(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},xa=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},It=(e,t=!1)=>{const s=xa(e);if(i.isIdentifier(s)){if(t)return;const r=H(s);return r===void 0?void 0:It(r,!0)}if(i.isCallExpression(s))return pa(s)??ma(s)},ha=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},Ea=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=pt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Qt(r.receiver,"output"),a=r.receiver!==void 0&&mt(r.receiver,"use","mask"),c=new Set,l=[];for(const p of ha(n)){const y=It(p);y===void 0||c.has(y)||(c.add(y),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),table:y,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},ya=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ea(c,o))}return s},$a=new Set(["findFirst","findFirstOrThrow","findMany"]),Aa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!$a.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Sa=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Na=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},va=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Aa(o);if(a===void 0)continue;const c=Sa(Na(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},ba=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...va(c,o))}return s},G=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=G(e.getLeft()),s=G(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Pa=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&G(t)!==void 0},wa=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(Pa(o))continue;const a=G(o);if(a===void 0)continue;const c=zs(a);if(c===void 0)continue;const l=o.getStartLineNumber(),p=`${String(l)}:${c}`;n.has(p)||(n.add(p),s.push({file:t,kind:c,line:l,preview:qs(a)}))}return s},Ia=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...wa(n,f(t,r)))}return s},La=new Set(["findFirst","findFirstOrThrow","findMany"]),Oa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!La.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Fa=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},Ta=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Oa(o);if(a===void 0)continue;const c=Fa(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),p=!l&&w(c);!l&&!p||n.push({exportName:e.getName(),file:t,fromArgs:p,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},Da=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ta(c,o))}return s},Ca=new Set(["query","unsafe"]),Ka=e=>{if(!i.isPropertyAccessExpression(e)||!Ca.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},ka=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Ra=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",ja=(e,t)=>{if(!Ka(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!ka(s)))return{exportName:Ra(e),file:t,line:s.getStartLineNumber()}},Ma=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ja(r,t);n&&s.push(n)}return s},za=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ma(n,f(t,r)))}return s},qa=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Ba=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:qa}),Va=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Ua=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Wa=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=Ua(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Ga=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Va.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},Ha=(e,t)=>{const s=Ga(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...Wa(e.getArguments()[s.optionsIndex])}},_a=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ha(r,t);n&&s.push(n)}return s},Qa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(..._a(n,f(t,r)))}return s},Ja=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),Xa=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return Ee.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return Ee.has(n)?n:void 0}const s=t.getText();return Ee.has(s)?s:void 0},Za=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Lt=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Za(e))return"empty-object";if(i.isParenthesizedExpression(e))return Lt(e.getExpression())}},Ot=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Ft=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>Ot(t)===e),Tt=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>Ot(t)===e),Ya=e=>{const t=Ft(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Tt(e).length>0},ec=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Ft(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Tt(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},tc=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},sc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!Ja.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Ya(a))for(const c of ec(a)){const l=Lt(c);l!==void 0&&n.push({exportName:tc(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},rc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Xa(r);n!==void 0&&s.push(...sc(r,n,t))}return s},nc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...rc(n,f(t,r)))}return s},ic=new Set(["query","upsert","upsertMany"]),oc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(ic.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},ac=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},cc=(e,t)=>{const s=oc(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=ac(r);if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},uc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=cc(r,t);n&&s.push(n)}return s},lc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...uc(n,f(t,r)))}return s},dc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},gc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},fc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!dc(a))continue;const c=Us(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:gc(a)})}}return s},pc=".lunora-schema.json",A=(e,t)=>{E(e)&&$e(e,"utf8")===t||Vt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}A(e,t)},mc=e=>{const t=g(e,"package.json");if(E(t))try{const s=JSON.parse($e(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},xc=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},hc=e=>{let t=E(e)?e:pe(e);for(;t&&t!==pe(t);){const s=g(t,"tsconfig.json");if(E(s))return s;t=pe(t)}},ft=e=>e.replaceAll("\\","/"),Ec=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new B("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new B("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new B("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},yc=e=>{const t=hc(e);return t?new Ze({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ze({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},ou=(e,t)=>{const s=d(t),r=g(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>ft(c))),o=ft(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},au=e=>{const t=xc(),s=t?me.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),n=g(r,"schema.ts");if(!E(n))throw new B("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??yc(r),a=Ms(o,n,e.projectRoot),c=Jt(o,r),l=Ss(o,r),p=ws(o,r),y=Bs(o,r),I=Os(o,r),k=Ei(o,r),ve=Nn(o,r),v=Ws(o,r),T=Cs(o,r),b=Xt(o,r);Ec(v,b);const X=ns(o,r,v,b),D=rs(o,r),R=e.lint===!1?void 0:Ht({adminRoutes:ar(o,r),aiRawRuns:dr(o,r),aiToolSideEffects:Ar(o,r),argumentDerivedFetches:br(o,r),argumentValidators:Rr(o,r),authApiCalls:ss(o,r),authConfigs:_r(o,r),browserUrlAccesses:Yr(o,r),configCalls:cn(o,r),containerKeyAccesses:ln(o,r),containerOverrides:hn(o,r),containers:D,exportSinks:wn(o,r),failOpenGuards:Cn(o,r),flagSecurityDefaults:Gn(o,r),geoIndexUsages:Qn(o,r),httpActionGuards:ri(o,r),httpHeaderWrites:fi(o,r),identityClaimReads:bi(o,r),imageDeliveryUrlAccesses:Li(o,r),inserts:Ns(o,r),kvKeyAccesses:Fi(o,r),mailRecipientAccesses:Ri(o,r),maskProcedures:vs(o,r),maskStrategies:bs(o,r),mutatorWrites:Vi(o,r),nondeterministicCalls:Fs(o,r),normalizeIdAuthorizations:io(o,r),notifyCalls:Ds(o,r),notifyConfig:Ts(o,r),ownerFieldWrites:po(o,r),unrestrictedWhereBranches:nc(o,r),paymentWebhooks:$o(o,r),privilegedDispatches:Do(o,r),procedureProtections:ia(o,r),queries:ts(o,r),queues:T,r2sqlCalls:Ks(o,r),ratelimitKeySelectors:ga(o,r),rawRowReturns:ya(o,r),relationLoads:ba(o,r),rlsProcedures:ks(o,r),schema:a,secretLiterals:Ia(o,r),shapes:y,softDeleteReads:Da(o,r),sqlInterpolations:za(o,r),storageKeyAccesses:Ba(o,r),storageUploads:Qa(o,r),vectorNamespaceAccesses:lc(o,r),workflowCalls:fc(o,r),workflows:v,wranglerVariables:e.wranglerVariables}),be=R===void 0?[]:Wt(R,{source:"static"}),Dt=Rs(o,r),Ct=Ps(o,r),Z=Vs(o,r),Kt=kn(o,r),Pe=Xs(Kt,Zs(e.projectRoot,e.target)),$=Pe.usage,Y=$.ai,ee=$.payments,we=$.kv,Ie=$.access,te=E(g(r,"flags.ts")),kt=te?As(o,r):[],se=E(g(r,"notify.ts")),re=$.hyperdrive,ne=js(o,r),Rt=ne.usesSandboxBrowser||ne.usesSandboxContainer,ie=$.browser||ne.usesSandboxBrowser,oe=$.images,ae=$.analytics,Le=$.pipelines,ce=$.r2sql,ue=$.x402,L=mo(e.projectRoot),j=zn($,{containerCount:D.length,cronCount:X.length,dependencies:L,hasPaymentTables:Mn(a.tables),queueCount:T.length,storageColumnCount:Object.keys(is(a)).length,storageRuleCount:Z.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:v.length}),O=L.has("lunorash"),Oe=t?me.now():0,Fe=os(a,O),Te=as({agents:b,functions:c,httpRoutes:l,mutators:I,useUmbrella:O,workflows:v}),De=cs({agents:b,containers:D,env:ve,hasAccessFacade:Ie,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:we,hasNotify:se,hasPayments:ee,hasPipelines:Le,hasR2sql:ce,hasX402:ue,identity:k,queues:T,schema:a,storageRuleBuckets:Z.rules.map(m=>m.bucket),useUmbrella:O,workflows:v}),Ce=us({agents:b,functions:c,migrations:p,mutators:I,shapes:y,useUmbrella:O,usesSandbox:Rt}),le=Ys(a,p.map(m=>m.id)),Ke=ls({advisories:be,advisorProcedures:R?.procedureProtections??[],agents:b,containers:D,env:ve,flagKeys:kt,hasAccessFacade:Ie,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:we,hasNotify:se,hasPayments:ee,hasPipelines:Le,hasR2sql:ce,hasX402:ue,maskMetadata:Ct,mutators:I,queues:T,rlsMetadata:Dt,schema:a,schemaSnapshot:le,shapes:y,storageRules:Z,studioFeatures:j,useUmbrella:O,workflows:v}),ke=ds(y,L.has("@lunora/db"),O),Re=gs(D,a.jurisdiction),je=fs(v),Me=ps(b),ze=ms(T),qe=xs(X),Be=hs(a.vectorIndexes),M=Es(a,O),Ve=ys(L.has("@lunora/seed")),z=e.apiSpec??"openapi",de=z==="openapi"||z==="both",ge=z==="openrpc"||z==="both",Ue=Gs({emailAgents:b.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:L.has("@lunora/cloudflare-access"),hasAi:Y,hasAnalytics:ae,hasAuth:L.has("@lunora/auth"),hasBrowser:ie,hasFramework:L.has("@lunora/astro")||L.has("@lunora/svelte")||L.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:re,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:oe,hasKv:j.kv,hasNotify:se,hasPayments:ee,hasR2sql:ce,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:j.scheduler,hasStorage:j.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:v.length>0,hasX402:ue,identity:k,jurisdiction:a.jurisdiction,useUmbrella:O,voiceAgents:b.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:de,wantsOpenRpc:ge}),We=mc(e.projectRoot),Ge=Hs({functions:c,httpRoutes:l,version:We}),He=Qs({functions:c,version:We}),_e=`${JSON.stringify(Ge,void 0,2)}
4
+ `,Qe=`${JSON.stringify(He,void 0,2)}
5
+ `,Je=_s(Ge),Xe=Js(He),fe=g(r,pc),jt=E(fe),x=g(r,"_generated");if(e.dryRun||(E(x)||Bt(x,{recursive:!0}),A(g(x,"app.ts"),Ue),A(g(x,"dataModel.ts"),Fe),A(g(x,"api.ts"),Te),A(g(x,"server.ts"),De),A(g(x,"functions.ts"),Ce),A(g(x,"shard.ts"),Ke),A(g(x,"crons.ts"),qe),A(g(x,"vectors.ts"),Be),A(g(x,"drizzle.global.ts"),M.global),A(g(x,"drizzle.shard.ts"),M.shard),P(g(x,"containers.ts"),Re),P(g(x,"workflows.ts"),je),P(g(x,"agents.ts"),Me),P(g(x,"queues.ts"),ze),P(g(x,"seed.ts"),Ve),P(g(x,"collections.ts"),ke),P(g(x,"openapi.json"),de?_e:""),P(g(x,"openapi.ts"),de?Je:""),P(g(x,"openrpc.json"),ge?Qe:""),P(g(x,"openrpc.ts"),ge?Xe:""),(!jt||e.updateSchemaBaseline===!0)&&A(fe,Gt(le))),t){const m=me.now(),Mt=Math.round(m-s),zt=Math.round(Oe-s),qt=Math.round(m-Oe);console.error(`@lunora/codegen: codegen took ${Mt.toString()}ms (discovery ${zt.toString()}ms, emit ${qt.toString()}ms)`)}return{advisories:be,advisorContext:R,agents:b,containers:D,cronTriggers:$s(X),generated:{agents:Me,api:Te,app:Ue,collections:ke,containers:Re,crons:qe,dataModel:Fe,drizzleGlobal:M.global,drizzleShard:M.shard,functions:Ce,openApi:_e,openApiModule:Je,openRpc:Qe,openRpcModule:Xe,queues:ze,seed:Ve,server:De,shard:Ke,vectors:Be,workflows:je},outputDirectory:x,platformDiagnostics:Pe.diagnostics,queues:T,schemaSnapshot:le,schemaSnapshotPath:fe,workflows:v}};export{pc as SCHEMA_SNAPSHOT_FILENAME,yc as createCodegenProject,ou as refreshCodegenProject,au as runCodegen};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/codegen",
3
- "version": "1.0.0-alpha.78",
3
+ "version": "1.0.0-alpha.79",
4
4
  "description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -46,14 +46,16 @@
46
46
  "access": "public"
47
47
  },
48
48
  "dependencies": {
49
- "@lunora/advisor": "1.0.0-alpha.56",
50
- "@lunora/agent": "1.0.0-alpha.31",
49
+ "@lunora/advisor": "1.0.0-alpha.57",
50
+ "@lunora/agent": "1.0.0-alpha.32",
51
51
  "@lunora/container": "1.0.0-alpha.17",
52
52
  "@lunora/errors": "1.0.0-alpha.9",
53
- "@lunora/queue": "1.0.0-alpha.11",
54
- "@lunora/scheduler": "1.0.0-alpha.13",
53
+ "@lunora/platform": "1.0.0-alpha.1",
54
+ "@lunora/queue": "1.0.0-alpha.12",
55
+ "@lunora/scheduler": "1.0.0-alpha.14",
55
56
  "@lunora/values": "1.0.0-alpha.12",
56
57
  "@lunora/workflow": "1.0.0-alpha.14",
58
+ "jsonc-parser": "^3.3.1",
57
59
  "ts-morph": "^28.0.0"
58
60
  },
59
61
  "engines": {
@@ -1,5 +0,0 @@
1
- import{existsSync as E,readFileSync as $e,mkdirSync as zt,writeFileSync as qt,rmSync as Bt}from"node:fs";import{join as g,dirname as pe}from"node:path";import{performance as me}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as B}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as Xe}from"ts-morph";import{serializeSchemaSnapshot as Ut}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as Wt}from"./formatAdvisories-BCEfzLT0.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as f,classifyProcedureCall as K,inlineHandler as Gt,procedureHandler as ft,chainUsesWrappedCall as pt,isDatabaseAccessor as C,chainHasStep as Ht,discoverFunctions as _t}from"./discoverFunctions-DnqHgv0t.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-BesaDYkL.mjs";import{i as w,a as F,e as h,c as S,r as Jt,s as H,b as Xt,d as Zt,E as Yt}from"./discover-queries-LfER8HbK.mjs";import es from"./discoverAuthApiCalls-CEk3J0kc.mjs";import{discoverContainers as ts}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import ss from"./discoverCrons-kIgM9ZJC.mjs";import{diagnosticAt as _}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Q}from"./module-specifiers-8FEEiUcv.mjs";import{a as xe,n as rs,t as ns,h as is,v as os,$ as as,r as cs,b as us,Q as ls,K as ds,H as gs,G as fs,c as ps,d as ms,l as xs,f as hs,u as Es}from"./emit-BtiV37rG.mjs";import{discoverFlagKeys as ys}from"./FLAGS_FILENAME-CQDN7BKc.mjs";import $s from"./discoverHttpRoutes-CLn3VDRI.mjs";import As from"./discoverInserts-Cn-CLKET.mjs";import Ss,{discoverMaskStrategies as Ns,discoverMaskMetadata as vs}from"./discoverMaskProcedures-fZtvsy8v.mjs";import bs from"./discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as Ps,isDefineMutatorCallee as ws,discoverMutators as Is}from"./MUTATORS_FILENAME-3Akvs4aT.mjs";import Ls from"./discoverNondeterministicCalls-Cl7qNL0J.mjs";import{discoverNotifyConfig as Os,discoverNotifyCalls as Fs}from"./NOTIFY_FILENAME-B2lXWa7r.mjs";import{discoverQueues as Ts}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Ds from"./discoverR2sqlCalls-CMNfDWlq.mjs";import Cs,{discoverRlsMetadata as Ks}from"./discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as ks}from"./discoverSandboxUsage-Bn1X9COt.mjs";import Rs from"./discoverSchema-Cy4OQ0Cu.mjs";import{secretKindOf as js,redact as Ms}from"./redact-CQ8-to6l.mjs";import{discoverShapes as zs}from"./SHAPES_FILENAME-maut3z1K.mjs";import qs from"./discoverStorageRulesMetadata-CL8J41rX.mjs";import{e as Bs}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as Vs}from"./WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{emitApp as Us}from"./emitApp-Bc3G4eki.mjs";import{buildOpenApiDocument as Ws,emitOpenApiModule as Gs}from"./buildOpenApiDocument-D6xm3JqM.mjs";import{buildOpenRpcDocument as Hs,emitOpenRpcModule as _s}from"./OPENRPC_VERSION-BPT6vyLU.mjs";import{buildSchemaSnapshot as Qs}from"./SchemaSnapshotParseError-0KRzSjo4.mjs";const mt=new Set(["delete","get","head","options","patch","post","put"]),Js=new Set(["handler","stream"]),Xs=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ze=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Zs=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!mt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},Ys=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||mt.has(r.getName()))break;s=r.getExpression()}return Zs(s)},er=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(Ze.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Ze.has(s.getText()))return!0}return!1},tr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!Js.has(r.getName()))return;const n=Ys(s);if(!n||!Xs.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&er(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},sr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=tr(n,t);o&&s.push(o)}return s},rr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...sr(n,f(t,r)))}return s},nr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",ir=(e,t)=>{if(!nr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)||F(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},or=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ir(r,t);n&&s.push(n)}return s},ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...or(n,f(t,r)))}return s},cr=new Set(["generateText","streamText"]),ur=new Set(["messages","prompt","system"]),lr=[{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"]}],dr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of lr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},gr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=dr(t);if(s!==void 0)return s}},fr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},pr=e=>{if(Jt(e))return!0;const t=fr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},mr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!ur.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&pr(s))return!0}return!1},xr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!cr.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(S(c.getExpression())==="tool"&&(a=gr(c),a!==void 0))break;a!==void 0&&s.push({exportName:h(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:mr(o)})}return s},hr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xr(n,f(t,r)))}return s},Er=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},yr=(e,t)=>{if(!Er(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},$r=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=yr(r,t);n&&s.push(n)}return s},Ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...$r(n,f(t,r)))}return s},xt=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Sr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:xt(r)}},Nr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const n=r.getExpression();if(!i.isPropertyAccessExpression(n))break;if(n.getName()==="input"){const o=r.getArguments()[0];o&&i.isObjectLiteralExpression(o)?(t.push(o),s||=xt(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},ht=(e,t)=>t?Nr(t):Sr(e),vr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),br=/\.check\(|\.meta\(|length|max/iu,Pr=/\bv\.any\s*\(/u,wr=/\bv\.string\s*\(/u,Ir=e=>Pr.test(e),Lr=e=>wr.test(e)&&!br.test(e),Or=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();Ir(a)?t.push(c):Lr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Fr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const{objects:n}=ht(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=Or(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Tr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Fr(n,t);o&&s.push(o)}return s},Dr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Tr(n,f(t,r)))}return s},N=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},he=e=>e?.getKind()===u.TrueKeyword,Cr=e=>e?.getKind()===u.FalseKeyword,Kr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,kr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Rr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),jr=e=>e!==void 0&&i.isCallExpression(e)&&kr.has(S(e.getExpression())??""),Mr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),zr=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),r=N(e,"session");return{analyzable:!0,disableCsrfCheck:he(N(t,"disableCSRFCheck")),emailPasswordEnabled:he(N(s,"enabled")),requireEmailVerification:he(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Rr(N(e,"plugins"))&&jr(N(e,"database")),secureCookiesDisabled:Cr(N(t,"useSecureCookies")),sessionFreshAgeZero:Kr(N(r,"freshAge")),trustedOriginsWildcard:Mr(N(e,"trustedOrigins"))}},qr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Br=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?zr(s):qr();return{exportName:h(e),file:t,line:e.getStartLineNumber(),...n}},Vr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Br(r,t);n&&s.push(n)}return s},Ur=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Vr(n,f(t,r)))}return s},Wr=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Gr=(e,t,s)=>{const r=Wr(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:r}},Hr=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=Gr(n,t,s);o&&r.push(o)}return r},J=(e,t,s)=>{const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...Hr(o,f(t,n),s))}return r},_r=new Set(["content","pdf","scrape","screenshot"]),Qr=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:_r}),Jr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Xr=new Set(["RateLimiter"]),Zr=new Set(["extend"]),Et=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},Ye=e=>e&&i.isObjectLiteralExpression(e)?Et(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Yr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},en=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?Yr(e):void 0},tn=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&en(t.getBody());return s?Et(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},sn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());n!==void 0&&(Jr.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...Ye(r.getArguments()[0])}):Zr.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...tn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=S(r.getExpression());n===void 0||!Xr.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...Ye(r.getArguments()[0])})}return s},rn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...sn(n,f(t,r)))}return s},et="ctx.containers.",nn=e=>{if(!e.startsWith(et))return!1;const t=e.slice(et.length);return t.length>0&&!t.includes(".")},on=(e,t)=>J(e,t,{argIndex:0,matchReceiver:nn,methods:new Set(["get"])}),an=new Set(["allow","deny","setAllowed"]),cn=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},un=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!cn(e)))return{detail:"enableInternet: true",exportName:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},ln=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!an.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},dn=(e,t)=>un(e,t)??ln(e,t),gn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=dn(r,t);n&&s.push(n)}return s},fn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...gn(n,f(t,r)))}return s},pn="env.ts",mn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},xn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},hn=e=>{if(i.isIdentifier(e))return mn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&xn(t)}return!1},En=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!hn(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},yn=(e,t)=>{const s=g(t,pn);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=En(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},$n=new Set(["defineExportSink","r2Sink","webhookExportSink"]),An=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return $n.has(s)?s:void 0},Sn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Nn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=An(a);if(c===void 0)continue;const l=a.getArguments()[0],p=l&&i.isObjectLiteralExpression(l)?Sn(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:p.analyzable,emptyKeys:p.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:p.presentKeys})}}return s},vn=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),bn=new Set(["dbRateLimit","rateLimit"]),Pn=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},wn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},In=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=vn.get(s);if(r!==void 0)return{callee:s,exportName:h(e),failOpen:Pn(e.getArguments()[r]),file:t,limitName:bn.has(s)?wn(e):"",line:e.getStartLineNumber()}},Ln=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=In(r,t);n&&s.push(n)}return s},On=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ln(n,f(t,r)))}return s},Fn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Tn=(e,t)=>{const s=Object.fromEntries(xe.map(r=>[r.key,!1]));for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Fn(n);for(const c of xe)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(xe.every(c=>s[c.key]))break}return s},Dn=["providerSubscriptionId","state"],Cn=["providerEventId","processedAt"],tt=(e,t)=>t.every(s=>s in e.shape),Kn=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&tt(t,Dn)&&tt(s,Cn)},kn=(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")}),Rn=e=>i.isIdentifier(e)&&e.getText()==="ctx",jn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Rn(t.getExpression())},Mn=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},zn=(e,t)=>{if(!jn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=Mn(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:h(e),file:t,key:n,line:e.getStartLineNumber()}},qn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=zn(r,t);n&&s.push(n)}return s},Bn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...qn(n,f(t,r)))}return s},Vn=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Un=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Wn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))Vn(a)&&s.push({file:o,indexName:Un(a),line:a.getStartLineNumber()})}return s},Gn=new Set(["delete","get","head","options","patch","post","put"]),Hn=new Set(["handler","stream"]),_n=new Set(["runAction","runMutation"]),Qn=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),U=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,st=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,rt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},nt=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(_n.has(a)&&U(c,t))return a;if(Qn.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&U(c.getExpression(),t))return`db.${a}`}},it=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&U(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!U(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},Jn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Hn.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(Gn.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},Xn=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=st(e.getArguments()[0]),l=c&&rt(c,!0);if(!c||l===void 0)return;const p=nt(c,l);return p===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:it(c,l),sideEffect:p}}const r=Jn(e);if(r===void 0)return;const n=st(e.getArguments()[0]),o=n&&rt(n,!1);if(!n||o===void 0)return;const a=nt(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:it(n,o),sideEffect:a}},Zn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Xn(r,t);n&&s.push(n)}return s},Yn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Zn(n,f(t,r)))}return s},ei=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ti=new Set(["append","set"]),Ae=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",yt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ot=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>ei.has(Ae(s.getExpression()))&&Zt(s,t)),si=(e,t)=>{if(ot(e,t))return!0;const s=H(e);return s!==void 0&&ot(s,t)},ye=(e,t)=>Xt(e,t)&&!si(e,t),ri=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=H(e);return t!==void 0&&i.isNewExpression(t)&&Ae(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=H(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Se=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:yt(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=W(r.getExpression());n!==void 0&&Se(n,t,s)}},$t=(e,t)=>{const s=W(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=W(r.getInitializer());n!==void 0&&Se(n,"response-init",t)},ni=(e,t)=>{const s=Ae(e.getExpression());if(s==="Response")$t(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&Se(r,"headers-ctor",t)}},ii=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){$t(e.getArguments()[1],t);return}if(ti.has(r)&&ri(n)){const o=e.getArguments()[1];o!==void 0&&ye(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:yt(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},oi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))ni(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))ii(s,t)},ai=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=Gt(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return oi(r,{exportName:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},ci=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...ai(r,t));return s},ui=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ci(n,f(t,r)))}return s},At="identity.ts",li=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},di=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},gi=e=>{if(i.isIdentifier(e))return li(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&di(t)}return!1},fi=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!gi(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},pi=(e,t)=>{const s=g(t,At);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=fi(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},mi=new Set(["auth","context.auth","ctx.auth"]),xi="userId",hi=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Ei=(e,t)=>{const s=g(t,At);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(S(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?hi(o):void 0}},at=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return mi.has(e.getExpression().getText())?e:void 0},yi=e=>{if(i.isPropertyAccessExpression(e)&&at(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&at(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},$i=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=yi(n);o!==void 0&&r.push({declared:o===xi||s.has(o),exportName:h(n),file:t,key:o,line:n.getStartLineNumber()})}return r},Ai=(e,t)=>{const s=Ei(e,t);if(s===void 0)return[];const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...$i(o,f(t,n),s))}return r},Si=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Ni=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=Si(s);if(!(!r||!w(r)||F(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},vi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ni(r,t);n&&s.push(n)}return s},bi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...vi(n,f(t,r)))}return s},Pi=new Set(["delete","get","getRaw","getWithMetadata","put"]),wi=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Pi}),Ii=new Set(["queue","send"]),ct=new Set(["bcc","cc","to"]),Li=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ii.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Oi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return ct.has(t.getName())&&w(r)&&!F(r)}if(!i.isPropertyAssignment(t)||!ct.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!F(s)}):!1,Fi=(e,t)=>{const s=Li(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Oi(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},Ti=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Fi(r,t);n&&s.push(n)}return s},Di=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ti(n,f(t,r)))}return s},Ci=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Ki=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ki=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return ws(s.getExpression())?s:void 0},Ri=e=>{const t=ki(e),s=t===void 0?void 0:Ki(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>Ci(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},ji=e=>e.getVariableDeclarations().flatMap(t=>Ri(t)),Mi=(e,t)=>{const s=g(t,Ps);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ji(r)},zi=new Set(["delete","get","patch"]),qi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Bi=new Set(["auth","identity","session","user"]),Vi=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),Ui=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!C(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Wi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},Gi=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),Hi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,_i=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>Gi(s.getExpression(),t)&&Hi(s.getThenStatement())),Qi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!zi.has(n))continue;const o=r.getExpression();if(!(C(o)||i.isPropertyAccessExpression(o)&&C(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},Ji=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},Xi=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>Ji(s)==="ctx")),Zi=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Vi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Yi=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(qi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Bi.has(t.getName()))return!0}return Xi(e)||Zi(e)},eo=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=ft(s);if(n===void 0)return[];const o=r.receiver!==void 0&&pt(r.receiver,"use","rls"),a=Yi(n),c=new Set,l=[];for(const p of n.getDescendantsOfKind(u.CallExpression)){const y=Ui(p);if(y===void 0)continue;const I=Wi(p);if(I===void 0||c.has(I)||!_i(n,I))continue;const k=Qi(n,I);k!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),mentionsOwnership:a,sinkMethod:k,table:y,usesRls:o,visibility:r.visibility}))}return l},to=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...eo(c,o))}return s},so=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ro=new Set(["insert","insertManyUnsafe","patch","replace"]),no=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ro.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},io=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},oo=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!so.has(a))&&w(c)&&!F(c)&&n.push({exportName:h(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},ao=(e,t)=>{const s=no(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?io(r,s).flatMap(n=>oo(n,s,e,t)):[]},co=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...ao(r,t));return s},uo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...co(n,f(t,r)))}return s},lo=e=>{const t=g(e,"package.json");if(!E(t))return new Set;try{const s=JSON.parse($e(t,"utf8")),r=new Set;for(const n of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const o=s[n];if(o!==null&&typeof o=="object")for(const a of Object.keys(o))r.add(a)}return r}catch{return new Set}},go=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),fo=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,po=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?fo(t.getInitializer()):void 0},mo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!go.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?po(o):void 0;s.push({callee:n,exportName:h(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},xo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...mo(n,f(t,r)))}return s},ho=new Set(["defineQueue","defineWorkflow"]),Eo=new Set(["run","runAction","runMutation","runQuery"]),yo=new Set(["api","internal"]),$o=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Ao=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},St=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Nt=(e,t)=>e===t||e.startsWith(`${t}.`),vt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},ut=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},bt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>ut(s));return i.isIdentifier(e)&&ut(e)&&t.push(e),t},So=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},No=e=>{const t=St(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},vo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:No(e),n=new Set,o=a=>vt(a).some(c=>r.some(l=>Nt(c.getText(),l)))?!0:bt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of So(a))n.add(l)}return{names:n,prefixes:r}},bo=(e,t)=>vt(e).some(s=>t.prefixes.some(r=>Nt(s.getText(),r)))?!0:bt(e).some(s=>t.names.has(s.getText())),Po=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!yo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},wo=(e,t,s)=>{const r=St(e,0);if(r===void 0)return[];const n=vo(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Eo.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!bo(l,n))continue;const p=Po(a.getArguments()[0]);p!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:h(a),line:a.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return o},Io=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=$o(r);if(n===void 0||!ho.has(n))continue;const o=Ao(r);o!==void 0&&s.push(...wo(o,n==="defineQueue"?"queue":"workflow",t))}return s},Lo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Io(n,f(t,r)))}return s},lt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},Oo=/account|credential|member|passkey|session|user/iu,Fo=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},To=(e,t)=>{const{objects:s,opaque:r}=ht(e,t);return vr(s).some(n=>Fo(n))?!0:r?void 0:!1},Ne=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Do=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Co=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},V={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Ko=e=>{const t=Co(e),s=t?Ne(t):void 0;if(t&&s==="protectPublic"){const r=Do(t);return{...V,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in lt?{...V,[lt[s]]:!0}:V},ko=e=>{const t={...V};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=Ko(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},Ro=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insert")return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!!(r&&i.isStringLiteral(r)&&Oo.test(r.getLiteralText()))},jo=new Set(["create","runAfter","runAt","send","sendBatch"]),Mo=new Set(["queues","scheduler","workflows"]),zo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!jo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Mo.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},qo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Pt=new Set(["generateObject","generateText","streamObject","streamText"]),Bo=e=>{const t=Ne(e);return t!==void 0&&Pt.has(t)},Vo=e=>{const t=Ne(e);if(t===void 0||!Pt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Uo=new Set(["log","span","trace"]),Wo=new Set(["ai"]),Go=new Set(["email","mail"]),Ho=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),q=(e,t)=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),_o=e=>e.getDescendantsOfKind(u.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),dt="lunora-advisor-exempt",Qo=/^[\s*/]+/u,Jo=/[\w-]/u,Xo=e=>{const t=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
2
- `);for(const s of t.split(`
3
- `)){const r=s.replace(Qo,"");if(!r.startsWith(dt))continue;const n=r.slice(dt.length);if(Jo.test(n.charAt(0)))continue;const o=n.indexOf("--");return{exempt:!0,exemptReason:(o===-1?"":n.slice(o+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Zo=e=>{let t=!1,s=!1,r=!1,n=!1,o=!1;for(const a of e.getDescendantsOfKind(u.CallExpression))if(Ro(a)&&(o=!0),zo(a)&&(t=!0),qo(a)&&(n=!0),Bo(a)&&(s=!0),Vo(a)&&(r=!0),o&&t&&n&&r)break;return{callsMail:q(e,Go),emitsEvent:q(e,Uo),fanOut:t,handlesErrors:e.getDescendantsOfKind(u.TryStatement).length>0,reachesOutbound:q(e,Ho),runsAiGeneration:s||q(e,Wo),throwsBareError:_o(e),unboundedAiGeneration:r,usesInsertManyUnsafe:n,writesUserTable:o}},Yo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?ko(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1};return{...Zo(e),...Xo(e),...n,exportName:e.getName(),file:t,hasEmailArg:To(s,r.receiver),kind:r.kind,visibility:r.visibility}},ea=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Yo(n,t);o&&s.push(o)}return s},ta=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ea(n,f(t,r)))}return s},sa=new Set(["dbRateLimit","rateLimit"]),ra=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},na=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},ia=e=>i.isArrowFunction(e)?e.getBody():e,oa=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!sa.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=ra(r);if(!n)return;const o=ia(n);if(!(!w(o)||F(o)))return{callee:s,exportName:h(e),file:t,limitName:na(e),line:e.getStartLineNumber()}},aa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=oa(r,t);n&&s.push(n)}return s},ca=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...aa(n,f(t,r)))}return s},ua=new Set(["findFirst","findFirstOrThrow","findMany","get"]),la=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ua.has(t.getName()))return;const s=t.getExpression();if(C(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&C(s.getExpression()))return s.getName()},da=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&C(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},ga=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},wt=(e,t=!1)=>{const s=ga(e);if(i.isIdentifier(s)){if(t)return;const r=H(s);return r===void 0?void 0:wt(r,!0)}if(i.isCallExpression(s))return la(s)??da(s)},fa=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},pa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=ft(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Ht(r.receiver,"output"),a=r.receiver!==void 0&&pt(r.receiver,"use","mask"),c=new Set,l=[];for(const p of fa(n)){const y=wt(p);y===void 0||c.has(y)||(c.add(y),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),table:y,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},ma=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...pa(c,o))}return s},xa=new Set(["findFirst","findFirstOrThrow","findMany"]),ha=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!xa.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Ea=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},ya=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},$a=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=ha(o);if(a===void 0)continue;const c=Ea(ya(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},Aa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...$a(c,o))}return s},G=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=G(e.getLeft()),s=G(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Sa=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&G(t)!==void 0},Na=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(Sa(o))continue;const a=G(o);if(a===void 0)continue;const c=js(a);if(c===void 0)continue;const l=o.getStartLineNumber(),p=`${String(l)}:${c}`;n.has(p)||(n.add(p),s.push({file:t,kind:c,line:l,preview:Ms(a)}))}return s},va=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Na(n,f(t,r)))}return s},ba=new Set(["findFirst","findFirstOrThrow","findMany"]),Pa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ba.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},wa=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},Ia=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Pa(o);if(a===void 0)continue;const c=wa(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),p=!l&&w(c);!l&&!p||n.push({exportName:e.getName(),file:t,fromArgs:p,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},La=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,o))}return s},Oa=new Set(["query","unsafe"]),Fa=e=>{if(!i.isPropertyAccessExpression(e)||!Oa.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},Ta=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Da=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",Ca=(e,t)=>{if(!Fa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ta(s)))return{exportName:Da(e),file:t,line:s.getStartLineNumber()}},Ka=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ca(r,t);n&&s.push(n)}return s},ka=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ka(n,f(t,r)))}return s},Ra=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ja=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:Ra}),Ma=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),za=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,qa=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=za(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Ba=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ma.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},Va=(e,t)=>{const s=Ba(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...qa(e.getArguments()[s.optionsIndex])}},Ua=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Va(r,t);n&&s.push(n)}return s},Wa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ua(n,f(t,r)))}return s},Ga=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),Ha=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return Ee.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return Ee.has(n)?n:void 0}const s=t.getText();return Ee.has(s)?s:void 0},_a=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,It=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(_a(e))return"empty-object";if(i.isParenthesizedExpression(e))return It(e.getExpression())}},Lt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Ot=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>Lt(t)===e),Ft=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>Lt(t)===e),Qa=e=>{const t=Ot(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Ft(e).length>0},Ja=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Ot(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Ft(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},Xa=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Za=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!Ga.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Qa(a))for(const c of Ja(a)){const l=It(c);l!==void 0&&n.push({exportName:Xa(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},Ya=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ha(r);n!==void 0&&s.push(...Za(r,n,t))}return s},ec=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ya(n,f(t,r)))}return s},tc=new Set(["query","upsert","upsertMany"]),sc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(tc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},rc=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},nc=(e,t)=>{const s=sc(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=rc(r);if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},ic=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=nc(r,t);n&&s.push(n)}return s},oc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ic(n,f(t,r)))}return s},ac=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},cc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},uc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!ac(a))continue;const c=Bs(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:cc(a)})}}return s},lc=".lunora-schema.json",A=(e,t)=>{E(e)&&$e(e,"utf8")===t||qt(e,t,"utf8")},P=(e,t)=>{if(t===""){Bt(e,{force:!0});return}A(e,t)},dc=e=>{const t=g(e,"package.json");if(E(t))try{const s=JSON.parse($e(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},gc=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},fc=e=>{let t=E(e)?e:pe(e);for(;t&&t!==pe(t);){const s=g(t,"tsconfig.json");if(E(s))return s;t=pe(t)}},gt=e=>e.replaceAll("\\","/"),pc=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new B("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new B("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new B("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},mc=e=>{const t=fc(e);return t?new Xe({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xe({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},tu=(e,t)=>{const s=d(t),r=g(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>gt(c))),o=gt(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},su=e=>{const t=gc(),s=t?me.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),n=g(r,"schema.ts");if(!E(n))throw new B("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??mc(r),a=Rs(o,n,e.projectRoot),c=_t(o,r),l=$s(o,r),p=bs(o,r),y=zs(o,r),I=Is(o,r),k=pi(o,r),ve=yn(o,r),v=Vs(o,r),T=Ts(o,r),b=Qt(o,r);pc(v,b);const X=ss(o,r,v,b),D=ts(o,r),R=e.lint===!1?void 0:Wt({adminRoutes:rr(o,r),aiRawRuns:ar(o,r),aiToolSideEffects:hr(o,r),argumentDerivedFetches:Ar(o,r),argumentValidators:Dr(o,r),authApiCalls:es(o,r),authConfigs:Ur(o,r),browserUrlAccesses:Qr(o,r),configCalls:rn(o,r),containerKeyAccesses:on(o,r),containerOverrides:fn(o,r),containers:D,exportSinks:Nn(o,r),failOpenGuards:On(o,r),flagSecurityDefaults:Bn(o,r),geoIndexUsages:Wn(o,r),httpActionGuards:Yn(o,r),httpHeaderWrites:ui(o,r),identityClaimReads:Ai(o,r),imageDeliveryUrlAccesses:bi(o,r),inserts:As(o,r),kvKeyAccesses:wi(o,r),mailRecipientAccesses:Di(o,r),maskProcedures:Ss(o,r),maskStrategies:Ns(o,r),mutatorWrites:Mi(o,r),nondeterministicCalls:Ls(o,r),normalizeIdAuthorizations:to(o,r),notifyCalls:Fs(o,r),notifyConfig:Os(o,r),ownerFieldWrites:uo(o,r),unrestrictedWhereBranches:ec(o,r),paymentWebhooks:xo(o,r),privilegedDispatches:Lo(o,r),procedureProtections:ta(o,r),queries:Yt(o,r),queues:T,r2sqlCalls:Ds(o,r),ratelimitKeySelectors:ca(o,r),rawRowReturns:ma(o,r),relationLoads:Aa(o,r),rlsProcedures:Cs(o,r),schema:a,secretLiterals:va(o,r),shapes:y,softDeleteReads:La(o,r),sqlInterpolations:ka(o,r),storageKeyAccesses:ja(o,r),storageUploads:Wa(o,r),vectorNamespaceAccesses:oc(o,r),workflowCalls:uc(o,r),workflows:v,wranglerVariables:e.wranglerVariables}),be=R===void 0?[]:Vt(R,{source:"static"}),Tt=Ks(o,r),Dt=vs(o,r),Z=qs(o,r),$=Tn(o,r),Y=$.ai,ee=$.payments,Pe=$.kv,we=$.access,te=E(g(r,"flags.ts")),Ct=te?ys(o,r):[],se=E(g(r,"notify.ts")),re=$.hyperdrive,ne=ks(o,r),Kt=ne.usesSandboxBrowser||ne.usesSandboxContainer,ie=$.browser||ne.usesSandboxBrowser,oe=$.images,ae=$.analytics,Ie=$.pipelines,ce=$.r2sql,ue=$.x402,L=lo(e.projectRoot),j=kn($,{containerCount:D.length,cronCount:X.length,dependencies:L,hasPaymentTables:Kn(a.tables),queueCount:T.length,storageColumnCount:Object.keys(rs(a)).length,storageRuleCount:Z.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:v.length}),O=L.has("lunorash"),Le=t?me.now():0,Oe=ns(a,O),Fe=is({agents:b,functions:c,httpRoutes:l,mutators:I,useUmbrella:O,workflows:v}),Te=os({agents:b,containers:D,env:ve,hasAccessFacade:we,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:Pe,hasNotify:se,hasPayments:ee,hasPipelines:Ie,hasR2sql:ce,hasX402:ue,identity:k,queues:T,schema:a,storageRuleBuckets:Z.rules.map(m=>m.bucket),useUmbrella:O,workflows:v}),De=as({agents:b,functions:c,migrations:p,mutators:I,shapes:y,useUmbrella:O,usesSandbox:Kt}),le=Qs(a,p.map(m=>m.id)),Ce=cs({advisories:be,advisorProcedures:R?.procedureProtections??[],agents:b,containers:D,env:ve,flagKeys:Ct,hasAccessFacade:we,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:Pe,hasNotify:se,hasPayments:ee,hasPipelines:Ie,hasR2sql:ce,hasX402:ue,maskMetadata:Dt,mutators:I,queues:T,rlsMetadata:Tt,schema:a,schemaSnapshot:le,shapes:y,storageRules:Z,studioFeatures:j,useUmbrella:O,workflows:v}),Ke=us(y,L.has("@lunora/db"),O),ke=ls(D,a.jurisdiction),Re=ds(v),je=gs(b),Me=fs(T),ze=ps(X),qe=ms(a.vectorIndexes),M=xs(a,O),Be=hs(L.has("@lunora/seed")),z=e.apiSpec??"openapi",de=z==="openapi"||z==="both",ge=z==="openrpc"||z==="both",Ve=Us({emailAgents:b.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:L.has("@lunora/cloudflare-access"),hasAi:Y,hasAnalytics:ae,hasAuth:L.has("@lunora/auth"),hasBrowser:ie,hasFramework:L.has("@lunora/astro")||L.has("@lunora/svelte")||L.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:re,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:oe,hasKv:j.kv,hasNotify:se,hasPayments:ee,hasR2sql:ce,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:j.scheduler,hasStorage:j.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:v.length>0,hasX402:ue,identity:k,jurisdiction:a.jurisdiction,useUmbrella:O,voiceAgents:b.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:de,wantsOpenRpc:ge}),Ue=dc(e.projectRoot),We=Ws({functions:c,httpRoutes:l,version:Ue}),Ge=Hs({functions:c,version:Ue}),He=`${JSON.stringify(We,void 0,2)}
4
- `,_e=`${JSON.stringify(Ge,void 0,2)}
5
- `,Qe=Gs(We),Je=_s(Ge),fe=g(r,lc),kt=E(fe),x=g(r,"_generated");if(e.dryRun||(E(x)||zt(x,{recursive:!0}),A(g(x,"app.ts"),Ve),A(g(x,"dataModel.ts"),Oe),A(g(x,"api.ts"),Fe),A(g(x,"server.ts"),Te),A(g(x,"functions.ts"),De),A(g(x,"shard.ts"),Ce),A(g(x,"crons.ts"),ze),A(g(x,"vectors.ts"),qe),A(g(x,"drizzle.global.ts"),M.global),A(g(x,"drizzle.shard.ts"),M.shard),P(g(x,"containers.ts"),ke),P(g(x,"workflows.ts"),Re),P(g(x,"agents.ts"),je),P(g(x,"queues.ts"),Me),P(g(x,"seed.ts"),Be),P(g(x,"collections.ts"),Ke),P(g(x,"openapi.json"),de?He:""),P(g(x,"openapi.ts"),de?Qe:""),P(g(x,"openrpc.json"),ge?_e:""),P(g(x,"openrpc.ts"),ge?Je:""),(!kt||e.updateSchemaBaseline===!0)&&A(fe,Ut(le))),t){const m=me.now(),Rt=Math.round(m-s),jt=Math.round(Le-s),Mt=Math.round(m-Le);console.error(`@lunora/codegen: codegen took ${Rt.toString()}ms (discovery ${jt.toString()}ms, emit ${Mt.toString()}ms)`)}return{advisories:be,advisorContext:R,agents:b,containers:D,cronTriggers:Es(X),generated:{agents:je,api:Fe,app:Ve,collections:Ke,containers:ke,crons:ze,dataModel:Oe,drizzleGlobal:M.global,drizzleShard:M.shard,functions:De,openApi:He,openApiModule:Qe,openRpc:_e,openRpcModule:Je,queues:Me,seed:Be,server:Te,shard:Ce,vectors:qe,workflows:Re},outputDirectory:x,queues:T,schemaSnapshot:le,schemaSnapshotPath:fe,workflows:v}};export{lc as SCHEMA_SNAPSHOT_FILENAME,mc as createCodegenProject,tu as refreshCodegenProject,su as runCodegen};