@lunora/codegen 1.0.0-alpha.74 → 1.0.0-alpha.76

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.ts CHANGED
@@ -6,6 +6,126 @@ import { Node, Project } from 'ts-morph';
6
6
  import { StudioFeaturesResult } from '@lunora/do';
7
7
  import { Schema } from '@lunora/server';
8
8
  import { JsonSchema } from '@lunora/values';
9
+ /**
10
+ * The structural schema-snapshot format and its diff, shared by `@lunora/codegen`
11
+ * (which builds snapshots from the parsed schema IR and gates deploys on the
12
+ * diff) and `@lunora/studio` (which renders the same diff as a visual migration
13
+ * history).
14
+ *
15
+ * Having ONE diff is the point: the Studio's schema-history view and the
16
+ * pre-deploy drift gate must classify a change identically, or the UI will say a
17
+ * change is safe while `lunora deploy` refuses it. `@lunora/codegen` is a
18
+ * build-time package the browser bundle cannot import, and neither package sits
19
+ * below the other, so — like `shared/quote-identifier.ts` — this lives outside
20
+ * both and is bundler-inlined into each. Keep it genuinely zero-dependency
21
+ * (relative/built-in imports only) or inlining breaks. Consumers must drop
22
+ * `outDir`/`rootDir` from their `tsconfig.json` (a set `rootDir` raises TS6059
23
+ * for this out-of-package file under `tsc --noEmit`).
24
+ *
25
+ * What stays in `@lunora/codegen`: building a snapshot from `SchemaIR`, the
26
+ * `SchemaSnapshotParseError` class (it extends `LunoraError`), and the deploy
27
+ * gate's policy (`evaluateSchemaDrift`). What lives here: the format, the diff,
28
+ * the severity classification, and the content hash.
29
+ */
30
+ /** Current snapshot format version. Bumped if the structural shape below changes. */
31
+ declare const SCHEMA_SNAPSHOT_VERSION: 1;
32
+ /** A single field's structural shape: its value kind and whether it is optional. */
33
+ interface FieldSnapshot {
34
+ /** The validator kind (`string`, `number`, `id`, `object`, …) after unwrapping `v.optional`. */
35
+ kind: string;
36
+ /** True when declared `v.optional(...)` — accepts `undefined` / absent on insert. */
37
+ optional: boolean;
38
+ }
39
+ /** A single secondary index's structural shape. */
40
+ interface IndexSnapshot {
41
+ fields: ReadonlyArray<string>;
42
+ unique: boolean;
43
+ }
44
+ /** A single relation's structural shape. */
45
+ interface RelationSnapshot {
46
+ field: string;
47
+ kind: "many" | "one";
48
+ table: string;
49
+ }
50
+ /** Structural snapshot of one table. */
51
+ interface TableSnapshot {
52
+ /** Field name → {@link FieldSnapshot}, in declared order. */
53
+ fields: Record<string, FieldSnapshot>;
54
+ /** Index name → {@link IndexSnapshot}. */
55
+ indexes: Record<string, IndexSnapshot>;
56
+ /** Relation accessor name → {@link RelationSnapshot}. */
57
+ relations: Record<string, RelationSnapshot>;
58
+ /**
59
+ * `"root"` (default single-DO), `"global"` (D1-replicated), or
60
+ * `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
61
+ * stays a plain JSON-stable value.
62
+ */
63
+ shardMode: string;
64
+ }
65
+ /** A deterministic structural view of the whole schema at one point in time. */
66
+ interface SchemaSnapshot {
67
+ /**
68
+ * Cloudflare DO data-residency jurisdiction declared via `.jurisdiction("…")`,
69
+ * or absent. Tracked because changing it strands all existing Durable Object
70
+ * data (a DO name maps to a different ID per jurisdiction). Optional, so old
71
+ * baselines written before this field parse cleanly (absent ⇒ undefined).
72
+ *
73
+ * Typed as a plain `string` (not the authoring union) on purpose: this is
74
+ * STORED data that a newer Lunora may have written with a jurisdiction this
75
+ * version doesn't yet know. Preserving the raw value keeps the breaking
76
+ * `changedJurisdiction` diff correct under a downgrade — coercing an unknown
77
+ * value to `undefined` would fail OPEN and hide the most destructive change.
78
+ */
79
+ jurisdiction?: string;
80
+ /** Sorted list of every declared `defineMigration` id at capture time. */
81
+ migrationIds: ReadonlyArray<string>;
82
+ /** Table name → {@link TableSnapshot}, keys sorted for stable serialization. */
83
+ tables: Record<string, TableSnapshot>;
84
+ version: typeof SCHEMA_SNAPSHOT_VERSION;
85
+ }
86
+ /**
87
+ * Whether a change is anchored to one table's own shape, or to the schema as a
88
+ * whole.
89
+ *
90
+ * This is the signal a UI needs to decide which tables to mark as changed, and
91
+ * it lives HERE — next to the change union it classifies — rather than as a
92
+ * hand-maintained set of type names in the consumer. A set in the consumer gives
93
+ * zero compile-time pressure: adding a variant to `DriftChange["type"]` would
94
+ * silently render an affected table as untouched, which is exactly the
95
+ * UI-disagrees-with-the-deploy-gate divergence this module exists to prevent.
96
+ */
97
+ type DriftScope = "schema" | "table";
98
+ /** One classified structural change between two snapshots. */
99
+ interface DriftChange {
100
+ /**
101
+ * `"table"` means this table's own DDL moved (fields, indexes, shard mode) —
102
+ * a relation whose foreign key lives on the OTHER table stays `"schema"`, so
103
+ * the "changed" signal keeps meaning "this table's shape moved".
104
+ */
105
+ scope: DriftScope;
106
+ /** `"breaking"` changes need a data migration; `"safe"` changes are additive. */
107
+ severity: "breaking" | "safe";
108
+ /** Human-readable, actionable description (used in the gate message). */
109
+ summary: string;
110
+ /** The table this change belongs to. Always set when `scope` is `"table"`. */
111
+ table?: string;
112
+ /** A machine-readable change discriminator. */
113
+ type: "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedFieldKind" | "changedIndex" | "changedJurisdiction" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "removedField" | "removedIndex" | "removedRelation" | "removedTable";
114
+ }
115
+ /** The result of diffing two snapshots: every classified change. */
116
+ interface SchemaDrift {
117
+ /** Every classified change, in a stable order (added/changed per table, then removals). */
118
+ changes: ReadonlyArray<DriftChange>;
119
+ }
120
+ /** Serialize a snapshot to the exact bytes written to `lunora/.lunora-schema.json` (trailing newline). */
121
+ declare const serializeSchemaSnapshot: (snapshot: SchemaSnapshot) => string;
122
+ /**
123
+ * Diff the current snapshot against a baseline and classify every structural
124
+ * change. Pure — no I/O. When `baseline` is `undefined` (no snapshot yet) there
125
+ * is no drift to report: every table is treated as a fresh additive
126
+ * `addedTable`, so a first deploy is never blocked.
127
+ */
128
+ declare const diffSchemaSnapshots: (baseline: SchemaSnapshot | undefined, current: SchemaSnapshot) => SchemaDrift;
9
129
  /**
10
130
  * AST-observable subset of a column's modifier chain (`.unique()`, `.default()`,
11
131
  * …). Function-valued modifiers (`.$defaultFn`/`.$onUpdateFn`) can't be
@@ -2300,6 +2420,14 @@ interface EmitShardOptions {
2300
2420
  queues?: ReadonlyArray<QueueIR>;
2301
2421
  rlsMetadata?: RlsMetadataIR;
2302
2422
  schema: SchemaIR;
2423
+ /**
2424
+ * The structural snapshot the pre-deploy drift gate diffs against, threaded
2425
+ * in so the emitted DO records it in `__lunora_schema_history` on cold start
2426
+ * (plan 200 — the Studio's schema-version timeline). Optional so an emitter
2427
+ * caller that has no snapshot (tests, fixtures) emits the pre-ledger shape
2428
+ * unchanged.
2429
+ */
2430
+ schemaSnapshot?: SchemaSnapshot;
2303
2431
  /** Replication shapes declared via `defineShape` in `lunora/shapes.ts` — wires the `resolveShape` subscription override. */
2304
2432
  shapes?: ReadonlyArray<ShapeIR>;
2305
2433
  storageRules?: StorageRulesMetadataIR;
@@ -2308,7 +2436,7 @@ interface EmitShardOptions {
2308
2436
  useUmbrella?: boolean;
2309
2437
  workflows?: ReadonlyArray<WorkflowIR>;
2310
2438
  }
2311
- declare const emitShard: ({ advisories, agents, containers, env, flagKeys, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasX402, maskMetadata, mutators, queues, rlsMetadata, schema, shapes, storageRules, studioFeatures, useUmbrella, workflows }: EmitShardOptions) => string;
2439
+ declare const emitShard: ({ advisories, agents, containers, env, flagKeys, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasX402, maskMetadata, mutators, queues, rlsMetadata, schema, schemaSnapshot, shapes, storageRules, studioFeatures, useUmbrella, workflows }: EmitShardOptions) => string;
2312
2440
  /**
2313
2441
  * Emit drizzle `sqliteTable` definitions for the project schema, split into
2314
2442
  * `global` (D1-backed) and `shard` (DO-SQLite-backed) buckets. Tables marked
@@ -2540,140 +2668,6 @@ declare const emitOpenRpc: (input: OpenRpcEmitInput) => string;
2540
2668
  * the object returned by {@link buildOpenRpcDocument} (reused, never recomputed).
2541
2669
  */
2542
2670
  declare const emitOpenRpcModule: (document_: Record<string, unknown>) => string;
2543
- /** Current snapshot format version. Bumped if the structural shape below changes. */
2544
- declare const SCHEMA_SNAPSHOT_VERSION: 1;
2545
- /** A single field's structural shape: its value kind and whether it is optional. */
2546
- interface FieldSnapshot {
2547
- /** The validator kind (`string`, `number`, `id`, `object`, …) after unwrapping `v.optional`. */
2548
- kind: string;
2549
- /** True when declared `v.optional(...)` — accepts `undefined` / absent on insert. */
2550
- optional: boolean;
2551
- }
2552
- /** A single secondary index's structural shape. */
2553
- interface IndexSnapshot {
2554
- fields: ReadonlyArray<string>;
2555
- unique: boolean;
2556
- }
2557
- /** A single relation's structural shape. */
2558
- interface RelationSnapshot {
2559
- field: string;
2560
- kind: "many" | "one";
2561
- table: string;
2562
- }
2563
- /** Structural snapshot of one table. */
2564
- interface TableSnapshot {
2565
- /** Field name → {@link FieldSnapshot}, in declared order. */
2566
- fields: Record<string, FieldSnapshot>;
2567
- /** Index name → {@link IndexSnapshot}. */
2568
- indexes: Record<string, IndexSnapshot>;
2569
- /** Relation accessor name → {@link RelationSnapshot}. */
2570
- relations: Record<string, RelationSnapshot>;
2571
- /**
2572
- * `"root"` (default single-DO), `"global"` (D1-replicated), or
2573
- * `"shardBy:&lt;field>"` (partitioned). Encoded as a string so the snapshot
2574
- * stays a plain JSON-stable value.
2575
- */
2576
- shardMode: string;
2577
- }
2578
- /** The committed baseline — a deterministic structural view of the whole schema. */
2579
- interface SchemaSnapshot {
2580
- /**
2581
- * Cloudflare DO data-residency jurisdiction declared via `.jurisdiction("…")`,
2582
- * or absent. Tracked because changing it strands all existing Durable Object
2583
- * data (a DO name maps to a different ID per jurisdiction). Optional, so old
2584
- * baselines written before this field parse cleanly (absent ⇒ undefined).
2585
- *
2586
- * Typed as a plain `string` (not the authoring union) on purpose: this is
2587
- * STORED data that a newer Lunora may have written with a jurisdiction this
2588
- * version doesn't yet know. Preserving the raw value keeps the breaking
2589
- * `changedJurisdiction` diff correct under a downgrade — coercing an unknown
2590
- * value to `undefined` would fail OPEN and hide the most destructive change.
2591
- */
2592
- jurisdiction?: string;
2593
- /** Sorted list of every declared `defineMigration` id at capture time. */
2594
- migrationIds: ReadonlyArray<string>;
2595
- /** Table name → {@link TableSnapshot}, keys sorted for stable serialization. */
2596
- tables: Record<string, TableSnapshot>;
2597
- version: typeof SCHEMA_SNAPSHOT_VERSION;
2598
- }
2599
- /** One classified structural change between the baseline and the current schema. */
2600
- interface DriftChange {
2601
- /** `"breaking"` changes need a data migration; `"safe"` changes are additive. */
2602
- severity: "breaking" | "safe";
2603
- /** Human-readable, actionable description (used in the gate message). */
2604
- summary: string;
2605
- /** A machine-readable change discriminator. */
2606
- type: "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedJurisdiction" | "changedFieldKind" | "changedIndex" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "removedField" | "removedIndex" | "removedRelation" | "removedTable";
2607
- }
2608
- /** The result of diffing two snapshots: every classified change. */
2609
- interface SchemaDrift {
2610
- /** Every classified change, in a stable order (added/changed per table, then removals). */
2611
- changes: ReadonlyArray<DriftChange>;
2612
- }
2613
- /**
2614
- * Build a {@link SchemaSnapshot} from a parsed {@link SchemaIR} and the set of
2615
- * declared migration ids. Tables and migration ids are sorted so the emitted
2616
- * JSON is byte-stable across runs AND across machines (no spurious diffs /
2617
- * churn) — see {@link sortKeys} for why that ordering must not be locale-aware.
2618
- *
2619
- * Field / index / relation keys are deliberately NOT sorted: they are emitted in
2620
- * declaration order from the schema source, which is already deterministic for a
2621
- * given source file and keeps the snapshot readable next to the schema it mirrors.
2622
- */
2623
- declare const buildSchemaSnapshot: (schema: SchemaIR, migrationIds: ReadonlyArray<string>) => SchemaSnapshot;
2624
- /** Serialize a snapshot to the exact bytes written to `lunora/.lunora-schema.json` (trailing newline). */
2625
- declare const serializeSchemaSnapshot: (snapshot: SchemaSnapshot) => string;
2626
- /**
2627
- * Thrown by {@link parseSchemaSnapshot} when the baseline file exists but is
2628
- * malformed (bad JSON / wrong version / invalid table shape). Lets the CLI gate
2629
- * treat a corrupt baseline as a hard error rather than silently degrading to a
2630
- * "first capture" that would mask drift and then overwrite the bad file.
2631
- */
2632
- declare class SchemaSnapshotParseError extends LunoraError {
2633
- constructor(message: string);
2634
- }
2635
- /**
2636
- * Parse a committed snapshot file. Returns `undefined` ONLY when the content is
2637
- * absent/empty; throws {@link SchemaSnapshotParseError} when content is present
2638
- * but malformed (bad JSON, wrong version, or structurally-invalid tables) so the
2639
- * caller can distinguish "no baseline yet" (a legitimate first capture) from "a
2640
- * corrupt baseline" (which must not be silently treated as a first capture).
2641
- */
2642
- declare const parseSchemaSnapshot: (content: string | undefined) => SchemaSnapshot | undefined;
2643
- /**
2644
- * Diff the current snapshot against a committed baseline and classify every
2645
- * structural change. Pure — no I/O. When `baseline` is `undefined` (no committed
2646
- * snapshot yet) there is no drift to report: every table is treated as a fresh
2647
- * additive `addedTable`, so a first deploy is never blocked.
2648
- */
2649
- declare const diffSchemaSnapshots: (baseline: SchemaSnapshot | undefined, current: SchemaSnapshot) => SchemaDrift;
2650
- /** The decision the pre-deploy gate returns. */
2651
- interface SchemaDriftDecision {
2652
- /** True when the deploy must be blocked (breaking drift with no new migration, and no override). */
2653
- blocked: boolean;
2654
- /** Every classified change (both severities), for reporting. */
2655
- changes: ReadonlyArray<DriftChange>;
2656
- /** Migration ids declared now but absent from the baseline — proof a migration was added. */
2657
- newMigrationIds: ReadonlyArray<string>;
2658
- /**
2659
- * A multi-line, actionable explanation. Always present; empty string when
2660
- * there is no drift at all. Mirrors the D1-placeholder guard's message style.
2661
- */
2662
- reason: string;
2663
- }
2664
- /**
2665
- * Decide whether breaking schema drift should block a deploy.
2666
- *
2667
- * Blocks only when the baseline exists (a first-ever capture is never blocking),
2668
- * there is at least one `breaking` change, no NEW migration id was added since
2669
- * the baseline, and the `allowDrift` override is not set. Safe-only drift (or
2670
- * breaking drift accompanied by a new migration id) passes.
2671
- */
2672
- declare const evaluateSchemaDrift: (options: {
2673
- allowDrift?: boolean;
2674
- baseline: SchemaSnapshot | undefined;
2675
- current: SchemaSnapshot;
2676
- }) => SchemaDriftDecision;
2677
2671
  /**
2678
2672
  * Committed, tracked baseline file holding the blessed structural schema
2679
2673
  * snapshot the pre-deploy drift gate diffs against. Lives in `lunora/` (NOT the
@@ -2873,6 +2867,66 @@ interface CodegenResult {
2873
2867
  */
2874
2868
  workflows: ReadonlyArray<WorkflowIR>;
2875
2869
  }
2870
+ /**
2871
+ * Build a {@link SchemaSnapshot} from a parsed {@link SchemaIR} and the set of
2872
+ * declared migration ids. Tables and migration ids are sorted so the emitted
2873
+ * JSON is byte-stable across runs AND across machines (no spurious diffs /
2874
+ * churn) — see `sortKeys` in `shared/schema-snapshot.ts` for why that ordering
2875
+ * must not be locale-aware.
2876
+ *
2877
+ * Field / index / relation keys are deliberately NOT sorted: they are emitted in
2878
+ * declaration order from the schema source, which is already deterministic for a
2879
+ * given source file and keeps the snapshot readable next to the schema it mirrors.
2880
+ */
2881
+ declare const buildSchemaSnapshot: (schema: SchemaIR, migrationIds: ReadonlyArray<string>) => SchemaSnapshot;
2882
+ /**
2883
+ * Thrown by {@link parseSchemaSnapshot} when the baseline file exists but is
2884
+ * malformed (bad JSON / wrong version / invalid table shape). Lets the CLI gate
2885
+ * treat a corrupt baseline as a hard error rather than silently degrading to a
2886
+ * "first capture" that would mask drift and then overwrite the bad file.
2887
+ */
2888
+ declare class SchemaSnapshotParseError extends LunoraError {
2889
+ constructor(message: string);
2890
+ }
2891
+ /**
2892
+ * Parse a committed snapshot file. Returns `undefined` ONLY when the content is
2893
+ * absent/empty; throws {@link SchemaSnapshotParseError} when content is present
2894
+ * but malformed (bad JSON, wrong version, or structurally-invalid tables) so the
2895
+ * caller can distinguish "no baseline yet" (a legitimate first capture) from "a
2896
+ * corrupt baseline" (which must not be silently treated as a first capture).
2897
+ *
2898
+ * The parsing itself lives in `shared/schema-snapshot.ts` (the Studio reads the
2899
+ * same JSON out of the DO ledger); this wrapper only applies the CLI's policy of
2900
+ * treating a malformed baseline as fatal.
2901
+ */
2902
+ declare const parseSchemaSnapshot: (content: string | undefined) => SchemaSnapshot | undefined;
2903
+ /** The decision the pre-deploy gate returns. */
2904
+ interface SchemaDriftDecision {
2905
+ /** True when the deploy must be blocked (breaking drift with no new migration, and no override). */
2906
+ blocked: boolean;
2907
+ /** Every classified change (both severities), for reporting. */
2908
+ changes: ReadonlyArray<DriftChange>;
2909
+ /** Migration ids declared now but absent from the baseline — proof a migration was added. */
2910
+ newMigrationIds: ReadonlyArray<string>;
2911
+ /**
2912
+ * A multi-line, actionable explanation. Always present; empty string when
2913
+ * there is no drift at all. Mirrors the D1-placeholder guard's message style.
2914
+ */
2915
+ reason: string;
2916
+ }
2917
+ /**
2918
+ * Decide whether breaking schema drift should block a deploy.
2919
+ *
2920
+ * Blocks only when the baseline exists (a first-ever capture is never blocking),
2921
+ * there is at least one `breaking` change, no NEW migration id was added since
2922
+ * the baseline, and the `allowDrift` override is not set. Safe-only drift (or
2923
+ * breaking drift accompanied by a new migration id) passes.
2924
+ */
2925
+ declare const evaluateSchemaDrift: (options: {
2926
+ allowDrift?: boolean;
2927
+ baseline: SchemaSnapshot | undefined;
2928
+ current: SchemaSnapshot;
2929
+ }) => SchemaDriftDecision;
2876
2930
  /**
2877
2931
  * Convert a {@link SchemaIR} into a synthetic runtime {@link Schema} carrying just
2878
2932
  * the `tables[name].shape` surface `@lunora/seed` introspects. System columns
@@ -2902,4 +2956,4 @@ declare const secretKindOf: (value: string) => string | undefined;
2902
2956
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
2903
2957
  declare const redact: (value: string) => string;
2904
2958
  declare const VERSION = "0.0.0";
2905
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, type DriftChange, 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, validatorIrToJsonSchema };
2959
+ 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, validatorIrToJsonSchema };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{formatAdvisories as t,lintSchema as s}from"./packem_shared/formatAdvisories-DZvv-0MG.mjs";import{CodegenDiagnosticError as i,diagnosticAt as m}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as f,discoverAgents as p}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as n}from"./packem_shared/discoverAuthApiCalls-CEk3J0kc.mjs";import{CONTAINERS_FILENAME as l,discoverContainers as E}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as u}from"./packem_shared/discoverCrons-kIgM9ZJC.mjs";import{FLAGS_FILENAME as v,discoverFlags as N}from"./packem_shared/FLAGS_FILENAME-CQDN7BKc.mjs";import{discoverFunctions as M}from"./packem_shared/discoverFunctions-DnqHgv0t.mjs";import{default as h}from"./packem_shared/discoverHttpRoutes-CLn3VDRI.mjs";import{default as _}from"./packem_shared/discoverInserts-Cn-CLKET.mjs";import{default as g}from"./packem_shared/discoverMaskProcedures-fZtvsy8v.mjs";import{default as F}from"./packem_shared/discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as P,discoverMutators as D}from"./packem_shared/MUTATORS_FILENAME-3Akvs4aT.mjs";import{default as H}from"./packem_shared/discoverNondeterministicCalls-Cl7qNL0J.mjs";import{NOTIFY_FILENAME as G,discoverNotifyCalls as W,discoverNotifyConfig as V}from"./packem_shared/NOTIFY_FILENAME-B2lXWa7r.mjs";import{default as w}from"./packem_shared/discoverQueries-DENx_T6c.mjs";import{QUEUES_FILENAME as z,discoverQueues as Q}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as B}from"./packem_shared/discoverR2sqlCalls-CMNfDWlq.mjs";import{discoverRlsMetadata as K,default as q}from"./packem_shared/discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as X}from"./packem_shared/discoverSandboxUsage-Bn1X9COt.mjs";import{default as $}from"./packem_shared/discoverSchema-Cy4OQ0Cu.mjs";import{SHAPES_FILENAME as oe,discoverShapes as re}from"./packem_shared/SHAPES_FILENAME-maut3z1K.mjs";import{default as se}from"./packem_shared/discoverStorageRulesMetadata-CL8J41rX.mjs";import{WORKFLOWS_FILENAME as ie,discoverWorkflows as me}from"./packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{w as fe,B as pe,s as ce,c as ne,_ as Se,t as le,G as Ee,e as xe,b as ue,h as Ae,J as ve,n as Ne,M as Oe,r as Me}from"./packem_shared/emit-D7VIjvlm.mjs";import{emitApp as he}from"./packem_shared/emitApp-CAeIj6e_.mjs";import{buildOpenApiDocument as _e,emitOpenApi as Ie,emitOpenApiModule as ge}from"./packem_shared/buildOpenApiDocument-xYxqrlj1.mjs";import{OPENRPC_VERSION as Fe,buildOpenRpcDocument as Te,emitOpenRpc as Pe,emitOpenRpcModule as De}from"./packem_shared/OPENRPC_VERSION-CvVFqUlq.mjs";import{SCHEMA_SNAPSHOT_FILENAME as He,createCodegenProject as be,refreshCodegenProject as Ge,runCodegen as We}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-Bj7EusPY.mjs";import{SCHEMA_SNAPSHOT_VERSION as ke,SchemaSnapshotParseError as we,buildSchemaSnapshot as ye,diffSchemaSnapshots as ze,evaluateSchemaDrift as Qe,parseSchemaSnapshot as je,serializeSchemaSnapshot as Be}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-Bpf1FGMG.mjs";import{schemaFromIr as Ke}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as Ye,validatorIrToJsonSchema as Xe}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as $e,secretKindOf as eo}from"./packem_shared/redact-CQ8-to6l.mjs";import{MESSAGE_SOLUTIONS as ro,findSolutionByMessage as to}from"@lunora/errors";const e="0.0.0";export{f as AGENTS_FILENAME,l as CONTAINERS_FILENAME,i as CodegenDiagnosticError,v as FLAGS_FILENAME,fe as GENERATED_HEADER,Ye as LUNORA_ERROR_CODES,ro as LUNORA_SOLUTION_RULES,P as MUTATORS_FILENAME,G as NOTIFY_FILENAME,Fe as OPENRPC_VERSION,z as QUEUES_FILENAME,He as SCHEMA_SNAPSHOT_FILENAME,ke as SCHEMA_SNAPSHOT_VERSION,oe as SHAPES_FILENAME,we as SchemaSnapshotParseError,e as VERSION,ie as WORKFLOWS_FILENAME,_e as buildOpenApiDocument,Te as buildOpenRpcDocument,ye as buildSchemaSnapshot,be as createCodegenProject,m as diagnosticAt,ze as diffSchemaSnapshots,p as discoverAgents,n as discoverAuthApiCalls,E as discoverContainers,u as discoverCrons,N as discoverFlags,M as discoverFunctions,h as discoverHttpRoutes,_ as discoverInserts,g as discoverMaskProcedures,F as discoverMigrations,D as discoverMutators,H as discoverNondeterministicCalls,W as discoverNotifyCalls,V as discoverNotifyConfig,w as discoverQueries,Q as discoverQueues,B as discoverR2sqlCalls,K as discoverRlsMetadata,q as discoverRlsProcedures,X as discoverSandboxUsage,$ as discoverSchema,re as discoverShapes,se as discoverStorageRulesMetadata,me as discoverWorkflows,pe as emitAgents,ce as emitApi,he as emitApp,ne as emitCollections,Se as emitContainers,le as emitCrons,Ee as emitDataModel,xe as emitDrizzleSchema,ue as emitFunctions,Ie as emitOpenApi,ge as emitOpenApiModule,Pe as emitOpenRpc,De as emitOpenRpcModule,Ae as emitServer,ve as emitShard,Ne as emitVectors,Oe as emitWorkflows,Me as emitWranglerCronTriggers,Qe as evaluateSchemaDrift,to as findLunoraSolution,t as formatAdvisories,s as lintSchema,je as parseSchemaSnapshot,$e as redact,Ge as refreshCodegenProject,We as runCodegen,Ke as schemaFromIr,eo as secretKindOf,Be as serializeSchemaSnapshot,Xe 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}from"./packem_shared/formatAdvisories-DZvv-0MG.mjs";import{CodegenDiagnosticError as p,diagnosticAt as c}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as S,discoverAgents as l}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as x}from"./packem_shared/discoverAuthApiCalls-CEk3J0kc.mjs";import{CONTAINERS_FILENAME as A,discoverContainers as v}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as O}from"./packem_shared/discoverCrons-kIgM9ZJC.mjs";import{FLAGS_FILENAME as M,discoverFlags as h}from"./packem_shared/FLAGS_FILENAME-CQDN7BKc.mjs";import{discoverFunctions as I}from"./packem_shared/discoverFunctions-DnqHgv0t.mjs";import{default as g}from"./packem_shared/discoverHttpRoutes-CLn3VDRI.mjs";import{default as F}from"./packem_shared/discoverInserts-Cn-CLKET.mjs";import{default as P}from"./packem_shared/discoverMaskProcedures-fZtvsy8v.mjs";import{default as U}from"./packem_shared/discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as W,discoverMutators as b}from"./packem_shared/MUTATORS_FILENAME-3Akvs4aT.mjs";import{default as G}from"./packem_shared/discoverNondeterministicCalls-Cl7qNL0J.mjs";import{NOTIFY_FILENAME as V,discoverNotifyCalls as w,discoverNotifyConfig as y}from"./packem_shared/NOTIFY_FILENAME-B2lXWa7r.mjs";import{default as K}from"./packem_shared/discoverQueries-DENx_T6c.mjs";import{QUEUES_FILENAME as q,discoverQueues as B}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as Y}from"./packem_shared/discoverR2sqlCalls-CMNfDWlq.mjs";import{discoverRlsMetadata as X,default as $}from"./packem_shared/discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as oe}from"./packem_shared/discoverSandboxUsage-Bn1X9COt.mjs";import{default as te}from"./packem_shared/discoverSchema-Cy4OQ0Cu.mjs";import{SHAPES_FILENAME as ae,discoverShapes as ie}from"./packem_shared/SHAPES_FILENAME-maut3z1K.mjs";import{default as de}from"./packem_shared/discoverStorageRulesMetadata-CL8J41rX.mjs";import{WORKFLOWS_FILENAME as pe,discoverWorkflows as ce}from"./packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{w as Se,K as le,g as Ee,h as xe,W as ue,i as Ae,Z as ve,s as Ne,v as Oe,k as Re,t as Me,l as he,Q as Ce,c as Ie}from"./packem_shared/emit-sQzv_a8t.mjs";import{emitApp as ge}from"./packem_shared/emitApp-D5X1S54W.mjs";import{buildOpenApiDocument as Fe,emitOpenApi as Te,emitOpenApiModule as Pe}from"./packem_shared/buildOpenApiDocument-DeMEuKaw.mjs";import{OPENRPC_VERSION as Ue,buildOpenRpcDocument as He,emitOpenRpc as We,emitOpenRpcModule as be}from"./packem_shared/OPENRPC_VERSION-67sJ7JrS.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Ge,createCodegenProject as Qe,refreshCodegenProject as Ve,runCodegen as we}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-x_pw6Agi.mjs";import{SchemaSnapshotParseError as ze,buildSchemaSnapshot as Ke,evaluateSchemaDrift as je,parseSchemaSnapshot as qe}from"./packem_shared/SchemaSnapshotParseError-0KRzSjo4.mjs";import{schemaFromIr as Je}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as Ze,validatorIrToJsonSchema as Xe}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as eo,secretKindOf as oo}from"./packem_shared/redact-CQ8-to6l.mjs";import{MESSAGE_SOLUTIONS as to,findSolutionByMessage as so}from"@lunora/errors";const e="0.0.0";export{S as AGENTS_FILENAME,A as CONTAINERS_FILENAME,p as CodegenDiagnosticError,M as FLAGS_FILENAME,Se as GENERATED_HEADER,Ze as LUNORA_ERROR_CODES,to as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,V as NOTIFY_FILENAME,Ue as OPENRPC_VERSION,q as QUEUES_FILENAME,Ge as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ae as SHAPES_FILENAME,ze as SchemaSnapshotParseError,e as VERSION,pe as WORKFLOWS_FILENAME,Fe as buildOpenApiDocument,He as buildOpenRpcDocument,Ke as buildSchemaSnapshot,Qe as createCodegenProject,c as diagnosticAt,s as diffSchemaSnapshots,l as discoverAgents,x as discoverAuthApiCalls,v as discoverContainers,O as discoverCrons,h as discoverFlags,I as discoverFunctions,g as discoverHttpRoutes,F as discoverInserts,P as discoverMaskProcedures,U as discoverMigrations,b as discoverMutators,G as discoverNondeterministicCalls,w as discoverNotifyCalls,y as discoverNotifyConfig,K as discoverQueries,B as discoverQueues,Y as discoverR2sqlCalls,X as discoverRlsMetadata,$ as discoverRlsProcedures,oe as discoverSandboxUsage,te as discoverSchema,ie as discoverShapes,de as discoverStorageRulesMetadata,ce as discoverWorkflows,le as emitAgents,Ee as emitApi,ge as emitApp,xe as emitCollections,ue as emitContainers,Ae as emitCrons,ve as emitDataModel,Ne as emitDrizzleSchema,Oe as emitFunctions,Te as emitOpenApi,Pe as emitOpenApiModule,We as emitOpenRpc,be as emitOpenRpcModule,Re as emitServer,Me as emitShard,he as emitVectors,Ce as emitWorkflows,Ie as emitWranglerCronTriggers,je as evaluateSchemaDrift,so as findLunoraSolution,m as formatAdvisories,d as lintSchema,qe as parseSchemaSnapshot,eo as redact,Ve as refreshCodegenProject,we as runCodegen,Je as schemaFromIr,oo as secretKindOf,a as serializeSchemaSnapshot,Xe as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{w as r,n as o,K as n,g as l,h as g,W as p,i as c,Z as u,s as C,v as E,V as S,m as d,k as A,t as D,l as h,Q as W,c as f}from"./emit-sQzv_a8t.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as buildStorageColumns,n as emitAgents,l as emitApi,g as emitCollections,p as emitContainers,c as emitCrons,u as emitDataModel,C as emitDrizzleSchema,E as emitFunctions,S as emitQueues,d as emitSeed,A as emitServer,D as emitShard,h as emitVectors,W as emitWorkflows,f as emitWranglerCronTriggers};
@@ -1,3 +1,3 @@
1
- import{w as a}from"./emit-D7VIjvlm.mjs";import{n as s}from"./paths-BmX5O1sG.mjs";import{argsObjectSchema as i,LUNORA_ERROR_CODES as c}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const m="1.3.2",p=()=>({description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."}),u=e=>{const n=s(e.filePath),t=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:c.map((r,o)=>({code:-32e3-o,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:i(e.args)}],result:{name:"result",schema:p()},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},d=e=>{const n=e.version??"0.0.0",t=e.functions.filter(r=>r.visibility!=="internal"&&r.kind!=="stream").map(r=>u(r)).toSorted((r,o)=>r.name.localeCompare(o.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:t,openrpc:m}},R=e=>`${JSON.stringify(d(e),void 0,2)}
1
+ import{w as a}from"./emit-sQzv_a8t.mjs";import{n as s}from"./paths-BmX5O1sG.mjs";import{argsObjectSchema as i,LUNORA_ERROR_CODES as c}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const m="1.3.2",p=()=>({description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."}),u=e=>{const n=s(e.filePath),t=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:c.map((r,o)=>({code:-32e3-o,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:i(e.args)}],result:{name:"result",schema:p()},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},d=e=>{const n=e.version??"0.0.0",t=e.functions.filter(r=>r.visibility!=="internal"&&r.kind!=="stream").map(r=>u(r)).toSorted((r,o)=>r.name.localeCompare(o.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:t,openrpc:m}},R=e=>`${JSON.stringify(d(e),void 0,2)}
2
2
  `,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{m as OPENRPC_VERSION,d as buildOpenRpcDocument,R as emitOpenRpc,O as emitOpenRpcModule};
@@ -0,0 +1,3 @@
1
+ import{existsSync as E,readFileSync as $e,mkdirSync as Vt,writeFileSync as Bt,rmSync as Ut}from"node:fs";import{join as g,dirname as fe}from"node:path";import{performance as pe}from"node:perf_hooks";import{LunoraError as q}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as Ze}from"ts-morph";import{serializeSchemaSnapshot as Wt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{lintSchema as Gt}from"./formatAdvisories-DZvv-0MG.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as f,classifyProcedureCall as K,inlineHandler as Ht,procedureHandler as mt,chainUsesWrappedCall as xt,isDatabaseAccessor as k,chainHasStep as _t,discoverFunctions as Qt}from"./discoverFunctions-DnqHgv0t.mjs";import{discoverAgents as Jt}from"./AGENTS_FILENAME-BesaDYkL.mjs";import Zt from"./discoverAuthApiCalls-CEk3J0kc.mjs";import{discoverContainers as Xt}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import Yt from"./discoverCrons-kIgM9ZJC.mjs";import{diagnosticAt as H}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as _}from"./module-specifiers-8FEEiUcv.mjs";import{r as me,n as es,Z as ts,g as ss,k as rs,v as ns,t as is,h as os,W as as,Q as cs,K as us,V as ls,i as ds,l as gs,s as fs,m as ps,c as ms}from"./emit-sQzv_a8t.mjs";import{discoverFlagKeys as xs}from"./FLAGS_FILENAME-CQDN7BKc.mjs";import hs from"./discoverHttpRoutes-CLn3VDRI.mjs";import Es from"./discoverInserts-Cn-CLKET.mjs";import ys,{discoverMaskStrategies as As,discoverMaskMetadata as $s}from"./discoverMaskProcedures-fZtvsy8v.mjs";import Ss from"./discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as Ns,isDefineMutatorCallee as vs,discoverMutators as bs}from"./MUTATORS_FILENAME-3Akvs4aT.mjs";import Ps from"./discoverNondeterministicCalls-Cl7qNL0J.mjs";import{discoverNotifyConfig as ws,discoverNotifyCalls as Is}from"./NOTIFY_FILENAME-B2lXWa7r.mjs";import Os from"./discoverQueries-DENx_T6c.mjs";import{discoverQueues as Ls}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Fs from"./discoverR2sqlCalls-CMNfDWlq.mjs";import Ts,{discoverRlsMetadata as Ds}from"./discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as Cs}from"./discoverSandboxUsage-Bn1X9COt.mjs";import ks from"./discoverSchema-Cy4OQ0Cu.mjs";import{secretKindOf as Ks,redact as Rs}from"./redact-CQ8-to6l.mjs";import{discoverShapes as Ms}from"./SHAPES_FILENAME-maut3z1K.mjs";import js from"./discoverStorageRulesMetadata-CL8J41rX.mjs";import{e as zs}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as qs}from"./WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{emitApp as Vs}from"./emitApp-D5X1S54W.mjs";import{buildOpenApiDocument as Bs,emitOpenApiModule as Us}from"./buildOpenApiDocument-DeMEuKaw.mjs";import{buildOpenRpcDocument as Ws,emitOpenRpcModule as Gs}from"./OPENRPC_VERSION-67sJ7JrS.mjs";import{buildSchemaSnapshot as Hs}from"./SchemaSnapshotParseError-0KRzSjo4.mjs";const ht=new Set(["delete","get","head","options","patch","post","put"]),_s=new Set(["handler","stream"]),Qs=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Xe=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Js=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ht.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()}},Zs=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)||ht.has(r.getName()))break;s=r.getExpression()}return Js(s)},Xs=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(Xe.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Xe.has(s.getText()))return!0}return!1},Ys=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!_s.has(r.getName()))return;const n=Zs(s);if(!n||!Qs.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&Xs(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},er=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Ys(n,t);o&&s.push(o)}return s},tr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...er(n,f(t,r)))}return s},Ye=e=>{if(e.getText()!=="args")return!1;const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(i.isPropertyAssignment(t)&&t.getNameNode()===e)},et=e=>{if(e.getText()!=="ctx")return!1;const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(i.isPropertyAssignment(t)&&t.getNameNode()===e)},xe=e=>i.isIdentifier(e)?et(e):e.getDescendantsOfKind(u.Identifier).some(t=>et(t)),tt=(e,t)=>{if(e.getText()!==t)return!1;const s=e.getParent();return i.isPropertyAccessExpression(s)&&s.getNameNode()===e?!1:!(i.isPropertyAssignment(s)&&s.getNameNode()===e)},sr=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},S=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e))return e.getName()},ye=e=>i.isIdentifier(e)?Ye(e):e.getDescendantsOfKind(u.Identifier).some(t=>Ye(t)),L=e=>{if(!i.isIdentifier(e))return;const t=e.getText(),s=e.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a));if(s===void 0)return;const r=e.getStart();let n,o=-1;for(const a of s.getDescendantsOfKind(u.VariableDeclaration)){if(a.getName()!==t)continue;const c=a.getInitializer(),l=a.getStart();c!==void 0&&l<r&&l>o&&(n=c,o=l)}return n},w=e=>{if(ye(e))return!0;const t=L(e);return t!==void 0&&ye(t)},T=e=>{if(xe(e))return!0;const t=L(e);if(t!==void 0&&xe(t))return!0;const s=t??e;return(i.isIdentifier(s)?[s]:s.getDescendantsOfKind(u.Identifier)).some(r=>{const n=L(r);return n!==void 0&&xe(n)})},V=(e,t)=>i.isIdentifier(e)?tt(e,t):e.getDescendantsOfKind(u.Identifier).some(s=>tt(s,t)),rr=(e,t)=>{if(V(e,t))return!0;const s=L(e);if(s!==void 0&&V(s,t))return!0;const r=sr(e);if(r!==void 0){const n=L(r);return n!==void 0&&V(n,t)}return!1},h=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},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)||T(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(ye(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()}},Ar=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=yr(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(...Ar(n,f(t,r)))}return s},Et=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:Et(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||=Et(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},yt=(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),Or=e=>wr.test(e)&&!br.test(e),Lr=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):Or(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}=yt(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=Lr(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"),Mr=e=>e!==void 0&&i.isCallExpression(e)&&Kr.has(S(e.getExpression())??""),jr=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"))&&Mr(N(e,"database")),secureCookiesDisabled:Cr(N(t,"useSecureCookies")),sessionFreshAgeZero:kr(N(r,"freshAge")),trustedOriginsWildcard:jr(N(e,"trustedOrigins"))}},qr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Vr=(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}},Br=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Vr(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(...Br(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)||T(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},Q=(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)=>Q(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:_r}),Jr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Zr=new Set(["RateLimiter"]),Xr=new Set(["extend"]),At=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}},st=e=>e&&i.isObjectLiteralExpression(e)?At(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?At(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(),...st(r.getArguments()[0])}):Xr.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||!Zr.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...st(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},rt="ctx.containers.",nn=e=>{if(!e.startsWith(rt))return!1;const t=e.slice(rt.length);return t.length>0&&!t.includes(".")},on=(e,t)=>Q(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 _(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&&_(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 H(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 H(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},An=new Set(["defineExportSink","r2Sink","webhookExportSink"]),$n=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return An.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=$n(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()}},On=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=In(r,t);n&&s.push(n)}return s},Ln=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...On(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(me.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 me)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(me.every(c=>s[c.key]))break}return s},Dn=["providerSubscriptionId","state"],Cn=["providerEventId","processedAt"],nt=(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&&nt(t,Dn)&&nt(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",Mn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Rn(t.getExpression())},jn=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},zn=(e,t)=>{if(!Mn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=jn(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},Vn=(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},Bn=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))Bn(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,it=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,ot=(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}}},at=(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}`}},ct=(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()}},Zn=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=it(e.getArguments()[0]),l=c&&ot(c,!0);if(!c||l===void 0)return;const p=at(c,l);return p===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ct(c,l),sideEffect:p}}const r=Jn(e);if(r===void 0)return;const n=it(e.getArguments()[0]),o=n&&ot(n,!1);if(!n||o===void 0)return;const a=at(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:ct(n,o),sideEffect:a}},Xn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Zn(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(...Xn(n,f(t,r)))}return s},ei=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ti=new Set(["append","set"]),Se=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",$t=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ut=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>ei.has(Se(s.getExpression()))&&V(s,t)),si=(e,t)=>{if(ut(e,t))return!0;const s=L(e);return s!==void 0&&ut(s,t)},Ae=(e,t)=>rr(e,t)&&!si(e,t),ri=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=L(e);return t!==void 0&&i.isNewExpression(t)&&Se(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=L(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Ne=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&Ae(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();Ae(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&&Ne(n,t,s)}},St=(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&&Ne(n,"response-init",t)},ni=(e,t)=>{const s=Se(e.getExpression());if(s==="Response")St(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&Ne(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"){St(e.getArguments()[1],t);return}if(ti.has(r)&&ri(n)){const o=e.getArguments()[1];o!==void 0&&Ae(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"})}},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=Ht(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},Nt="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 _(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&&_(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 H(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},pi=(e,t)=>{const s=g(t,Nt);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=fi(r);if(n.length!==0){if(n.length>1)throw H(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,Nt);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}},lt=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)&&lt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&lt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Ai=(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},$i=(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(...Ai(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)||T(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)=>Q(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Pi}),Ii=new Set(["queue","send"]),dt=new Set(["bcc","cc","to"]),Oi=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},Li=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return dt.has(t.getName())&&w(r)&&!T(r)}if(!i.isPropertyAssignment(t)||!dt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!T(s)}):!1,Fi=(e,t)=>{const s=Oi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Li(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 vs(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()}))},Mi=e=>e.getVariableDeclarations().flatMap(t=>Ri(t)),ji=(e,t)=>{const s=g(t,Ns);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Mi(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"]),Vi=new Set(["auth","identity","session","user"]),Bi=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),Ui=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!k(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},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(!(k(o)||i.isPropertyAccessExpression(o)&&k(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},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},Zi=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>Ji(s)==="ctx")),Xi=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Bi.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"&&Vi.has(t.getName()))return!0}return Zi(e)||Xi(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=mt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&xt(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 R=Qi(n,I);R!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,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)&&!T(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"]),Ao=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},$o=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},vt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},bt=(e,t)=>e===t||e.startsWith(`${t}.`),Pt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},gt=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)},wt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>gt(s));return i.isIdentifier(e)&&gt(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=vt(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=>Pt(a).some(c=>r.some(l=>bt(c.getText(),l)))?!0:wt(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)=>Pt(e).some(s=>t.prefixes.some(r=>bt(s.getText(),r)))?!0:wt(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=vt(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=Ao(r);if(n===void 0||!ho.has(n))continue;const o=$o(r);o!==void 0&&s.push(...wo(o,n==="defineQueue"?"queue":"workflow",t))}return s},Oo=(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},ft={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},Lo=/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}=yt(e,t);return vr(s).some(n=>Fo(n))?!0:r?void 0:!1},It=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},B={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},ko=e=>{const t=Co(e),s=t?It(t):void 0;if(t&&s==="protectPublic"){const r=Do(t);return{...B,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in ft?{...B,[ft[s]]:!0}:B},Ko=e=>{const t={...B};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)&&Lo.test(r.getLiteralText()))},Mo=new Set(["create","runAfter","runAt","send","sendBatch"]),jo=new Set(["queues","scheduler","workflows"]),zo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Mo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&jo.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"},Vo=new Set(["generateObject","generateText","streamObject","streamText"]),Bo=e=>{const t=It(e);if(t===void 0||!Vo.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=e=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(t=>{const s=t.getName();if(s!=="mail"&&s!=="email")return!1;const r=t.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),Wo=e=>{let t=!1,s=!1,r=!1,n=!1;for(const o of e.getDescendantsOfKind(u.CallExpression))if(Ro(o)&&(n=!0),zo(o)&&(t=!0),qo(o)&&(r=!0),Bo(o)&&(s=!0),n&&t&&r&&s)break;return{callsMail:Uo(e),fanOut:t,unboundedAiGeneration:s,usesInsertManyUnsafe:r,writesUserTable:n}},Go=(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},{callsMail:o,fanOut:a,unboundedAiGeneration:c,usesInsertManyUnsafe:l,writesUserTable:p}=Wo(e);return{callsMail:o,exportName:e.getName(),fanOut:a,file:t,hasEmailArg:To(s,r.receiver),kind:r.kind,unboundedAiGeneration:c,usesCaptcha:n.usesCaptcha,usesEmailGate:n.usesEmailGate,usesInsertManyUnsafe:l,usesMask:n.usesMask,usesRateLimit:n.usesRateLimit,usesRls:n.usesRls,visibility:r.visibility,writesUserTable:p}},Ho=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Go(n,t);o&&s.push(o)}return s},_o=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ho(n,f(t,r)))}return s},Qo=new Set(["dbRateLimit","rateLimit"]),Jo=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Zo=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Xo=e=>i.isArrowFunction(e)?e.getBody():e,Yo=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!Qo.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=Jo(r);if(!n)return;const o=Xo(n);if(!(!w(o)||T(o)))return{callee:s,exportName:h(e),file:t,limitName:Zo(e),line:e.getStartLineNumber()}},ea=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Yo(r,t);n&&s.push(n)}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(["findFirst","findFirstOrThrow","findMany","get"]),ra=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!sa.has(t.getName()))return;const s=t.getExpression();if(k(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&k(s.getExpression()))return s.getName()},na=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&k(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},ia=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},Ot=(e,t=!1)=>{const s=ia(e);if(i.isIdentifier(s)){if(t)return;const r=L(s);return r===void 0?void 0:Ot(r,!0)}if(i.isCallExpression(s))return ra(s)??na(s)},oa=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},aa=(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=mt(s);if(n===void 0)return[];const o=r.receiver!==void 0&&_t(r.receiver,"output"),a=r.receiver!==void 0&&xt(r.receiver,"use","mask"),c=new Set,l=[];for(const p of oa(n)){const y=Ot(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},ca=(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(...aa(c,o))}return s},ua=new Set(["findFirst","findFirstOrThrow","findMany"]),la=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ua.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()}}},da=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},ga=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},fa=(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=la(o);if(a===void 0)continue;const c=da(ga(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},pa=(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(...fa(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}},ma=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},xa=(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(ma(o))continue;const a=G(o);if(a===void 0)continue;const c=Ks(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:Rs(a)}))}return s},ha=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xa(n,f(t,r)))}return s},Ea=new Set(["findFirst","findFirstOrThrow","findMany"]),ya=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ea.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()}}},Aa=(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=ya(o);if(a===void 0)continue;const c=Aa(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},Sa=(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},Na=new Set(["query","unsafe"]),va=e=>{if(!i.isPropertyAccessExpression(e)||!Na.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"},ba=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Pa=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",wa=(e,t)=>{if(!va(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!ba(s)))return{exportName:Pa(e),file:t,line:s.getStartLineNumber()}},Ia=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=wa(r,t);n&&s.push(n)}return s},Oa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ia(n,f(t,r)))}return s},La=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Fa=(e,t)=>Q(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:La}),Ta=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Da=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Ca=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=Da(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},ka=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ta.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},Ka=(e,t)=>{const s=ka(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...Ca(e.getArguments()[s.optionsIndex])}},Ra=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ka(r,t);n&&s.push(n)}return s},Ma=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ra(n,f(t,r)))}return s},ja=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),za=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},qa=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(qa(e))return"empty-object";if(i.isParenthesizedExpression(e))return Lt(e.getExpression())}},Ft=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Tt=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>Ft(t)===e),Dt=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>Ft(t)===e),Va=e=>{const t=Tt(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Dt(e).length>0},Ba=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Tt(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Dt(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},Ua=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Wa=(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)))&&Va(a))for(const c of Ba(a)){const l=Lt(c);l!==void 0&&n.push({exportName:Ua(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},Ga=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=za(r);n!==void 0&&s.push(...Wa(r,n,t))}return s},Ha=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ga(n,f(t,r)))}return s},_a=new Set(["query","upsert","upsertMany"]),Qa=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(_a.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Ja=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Za=(e,t)=>{const s=Qa(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=Ja(r);if(!(!n||!w(n)||T(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},Xa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Za(r,t);n&&s.push(n)}return s},Ya=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Xa(n,f(t,r)))}return s},ec=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"},tc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},sc=(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(!ec(a))continue;const c=zs(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:tc(a)})}}return s},rc=".lunora-schema.json",$=(e,t)=>{E(e)&&$e(e,"utf8")===t||Bt(e,t,"utf8")},P=(e,t)=>{if(t===""){Ut(e,{force:!0});return}$(e,t)},nc=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}},ic=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},oc=e=>{let t=E(e)?e:fe(e);for(;t&&t!==fe(t);){const s=g(t,"tsconfig.json");if(E(s))return s;t=fe(t)}},pt=e=>e.replaceAll("\\","/"),ac=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new q("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new q("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new q("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},cc=e=>{const t=oc(e);return t?new Ze({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Ze({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Hc=(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=>pt(c))),o=pt(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},_c=e=>{const t=ic(),s=t?pe.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),n=g(r,"schema.ts");if(!E(n))throw new q("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??cc(r),a=ks(o,n,e.projectRoot),c=Qt(o,r),l=hs(o,r),p=Ss(o,r),y=Ms(o,r),I=bs(o,r),R=pi(o,r),ve=yn(o,r),v=qs(o,r),D=Ls(o,r),b=Jt(o,r);ac(v,b);const J=Yt(o,r,v,b),C=Xt(o,r),be=e.lint===!1?[]:Gt({adminRoutes:tr(o,r),aiRawRuns:ar(o,r),aiToolSideEffects:hr(o,r),argumentDerivedFetches:$r(o,r),argumentValidators:Dr(o,r),authApiCalls:Zt(o,r),authConfigs:Ur(o,r),browserUrlAccesses:Qr(o,r),configCalls:rn(o,r),containerKeyAccesses:on(o,r),containerOverrides:fn(o,r),containers:C,exportSinks:Nn(o,r),failOpenGuards:Ln(o,r),flagSecurityDefaults:Vn(o,r),geoIndexUsages:Wn(o,r),httpActionGuards:Yn(o,r),httpHeaderWrites:ui(o,r),identityClaimReads:$i(o,r),imageDeliveryUrlAccesses:bi(o,r),inserts:Es(o,r),kvKeyAccesses:wi(o,r),mailRecipientAccesses:Di(o,r),maskProcedures:ys(o,r),maskStrategies:As(o,r),mutatorWrites:ji(o,r),nondeterministicCalls:Ps(o,r),normalizeIdAuthorizations:to(o,r),notifyCalls:Is(o,r),notifyConfig:ws(o,r),ownerFieldWrites:uo(o,r),unrestrictedWhereBranches:Ha(o,r),paymentWebhooks:xo(o,r),privilegedDispatches:Oo(o,r),procedureProtections:_o(o,r),queries:Os(o,r),queues:D,r2sqlCalls:Fs(o,r),ratelimitKeySelectors:ta(o,r),rawRowReturns:ca(o,r),relationLoads:pa(o,r),rlsProcedures:Ts(o,r),schema:a,secretLiterals:ha(o,r),shapes:y,softDeleteReads:Sa(o,r),sqlInterpolations:Oa(o,r),storageKeyAccesses:Fa(o,r),storageUploads:Ma(o,r),vectorNamespaceAccesses:Ya(o,r),workflowCalls:sc(o,r),workflows:v,wranglerVariables:e.wranglerVariables}),Ct=Ds(o,r),kt=$s(o,r),Z=js(o,r),A=Tn(o,r),X=A.ai,Y=A.payments,Pe=A.kv,we=A.access,ee=E(g(r,"flags.ts")),Kt=ee?xs(o,r):[],te=E(g(r,"notify.ts")),se=A.hyperdrive,re=Cs(o,r),Rt=re.usesSandboxBrowser||re.usesSandboxContainer,ne=A.browser||re.usesSandboxBrowser,ie=A.images,oe=A.analytics,Ie=A.pipelines,ae=A.r2sql,ce=A.x402,O=lo(e.projectRoot),M=Kn(A,{containerCount:C.length,cronCount:J.length,dependencies:O,hasPaymentTables:kn(a.tables),queueCount:D.length,storageColumnCount:Object.keys(es(a)).length,storageRuleCount:Z.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:v.length}),F=O.has("lunorash"),Oe=t?pe.now():0,Le=ts(a,F),Fe=ss({agents:b,functions:c,httpRoutes:l,mutators:I,useUmbrella:F,workflows:v}),Te=rs({agents:b,containers:C,env:ve,hasAccessFacade:we,hasAi:X,hasAnalytics:oe,hasBrowser:ne,hasFlags:ee,hasHyperdrive:se,hasImages:ie,hasKv:Pe,hasNotify:te,hasPayments:Y,hasPipelines:Ie,hasR2sql:ae,hasX402:ce,identity:R,queues:D,schema:a,storageRuleBuckets:Z.rules.map(m=>m.bucket),useUmbrella:F,workflows:v}),De=ns({agents:b,functions:c,migrations:p,mutators:I,shapes:y,useUmbrella:F,usesSandbox:Rt}),ue=Hs(a,p.map(m=>m.id)),Ce=is({advisories:be,agents:b,containers:C,env:ve,flagKeys:Kt,hasAccessFacade:we,hasAi:X,hasAnalytics:oe,hasBrowser:ne,hasFlags:ee,hasHyperdrive:se,hasImages:ie,hasKv:Pe,hasNotify:te,hasPayments:Y,hasPipelines:Ie,hasR2sql:ae,hasX402:ce,maskMetadata:kt,mutators:I,queues:D,rlsMetadata:Ct,schema:a,schemaSnapshot:ue,shapes:y,storageRules:Z,studioFeatures:M,useUmbrella:F,workflows:v}),ke=os(y,O.has("@lunora/db"),F),Ke=as(C,a.jurisdiction),Re=cs(v),Me=us(b),je=ls(D),ze=ds(J),qe=gs(a.vectorIndexes),j=fs(a,F),Ve=ps(O.has("@lunora/seed")),z=e.apiSpec??"openapi",le=z==="openapi"||z==="both",de=z==="openrpc"||z==="both",Be=Vs({emailAgents:b.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:O.has("@lunora/cloudflare-access"),hasAi:X,hasAnalytics:oe,hasAuth:O.has("@lunora/auth"),hasBrowser:ne,hasFramework:O.has("@lunora/astro")||O.has("@lunora/svelte")||O.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:se,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:ie,hasKv:M.kv,hasNotify:te,hasPayments:Y,hasR2sql:ae,hasQueue:D.some(m=>m.mode==="push"),hasScheduler:M.scheduler,hasStorage:M.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:v.length>0,hasX402:ce,identity:R,jurisdiction:a.jurisdiction,useUmbrella:F,voiceAgents:b.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:le,wantsOpenRpc:de}),Ue=nc(e.projectRoot),We=Bs({functions:c,httpRoutes:l,version:Ue}),Ge=Ws({functions:c,version:Ue}),He=`${JSON.stringify(We,void 0,2)}
2
+ `,_e=`${JSON.stringify(Ge,void 0,2)}
3
+ `,Qe=Us(We),Je=Gs(Ge),ge=g(r,rc),Mt=E(ge),x=g(r,"_generated");if(e.dryRun||(E(x)||Vt(x,{recursive:!0}),$(g(x,"app.ts"),Be),$(g(x,"dataModel.ts"),Le),$(g(x,"api.ts"),Fe),$(g(x,"server.ts"),Te),$(g(x,"functions.ts"),De),$(g(x,"shard.ts"),Ce),$(g(x,"crons.ts"),ze),$(g(x,"vectors.ts"),qe),$(g(x,"drizzle.global.ts"),j.global),$(g(x,"drizzle.shard.ts"),j.shard),P(g(x,"containers.ts"),Ke),P(g(x,"workflows.ts"),Re),P(g(x,"agents.ts"),Me),P(g(x,"queues.ts"),je),P(g(x,"seed.ts"),Ve),P(g(x,"collections.ts"),ke),P(g(x,"openapi.json"),le?He:""),P(g(x,"openapi.ts"),le?Qe:""),P(g(x,"openrpc.json"),de?_e:""),P(g(x,"openrpc.ts"),de?Je:""),(!Mt||e.updateSchemaBaseline===!0)&&$(ge,Wt(ue))),t){const m=pe.now(),jt=Math.round(m-s),zt=Math.round(Oe-s),qt=Math.round(m-Oe);console.error(`@lunora/codegen: codegen took ${jt.toString()}ms (discovery ${zt.toString()}ms, emit ${qt.toString()}ms)`)}return{advisories:be,agents:b,containers:C,cronTriggers:ms(J),generated:{agents:Me,api:Fe,app:Be,collections:ke,containers:Ke,crons:ze,dataModel:Le,drizzleGlobal:j.global,drizzleShard:j.shard,functions:De,openApi:He,openApiModule:Qe,openRpc:_e,openRpcModule:Je,queues:je,seed:Ve,server:Te,shard:Ce,vectors:qe,workflows:Re},outputDirectory:x,queues:D,schemaSnapshot:ue,schemaSnapshotPath:ge,workflows:v}};export{rc as SCHEMA_SNAPSHOT_FILENAME,cc as createCodegenProject,Hc as refreshCodegenProject,_c as runCodegen};
@@ -0,0 +1,2 @@
1
+ const f=1;function v(e){const a={},t=Object.keys(e);t.sort();for(const s of t)a[s]=e[s];return a}const d=e=>`${JSON.stringify(e,void 0,2)}
2
+ `,g=e=>{const a=d(e),t=s=>{let i=s;for(let o=0;o<a.length;o+=1)i^=a.codePointAt(o)??0,i=Math.imul(i,16777619)>>>0;return i.toString(16).padStart(8,"0")};return`${t(2166136261)}${t(16777619)}`},r=e=>typeof e=="object"&&e!==null,l=e=>r(e)&&r(e.fields)&&r(e.indexes)&&r(e.relations)&&typeof e.shardMode=="string",$=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let a;try{a=JSON.parse(e)}catch(t){return{error:`baseline is not valid JSON: ${t instanceof Error?t.message:String(t)}`,status:"invalid"}}if(!r(a)||a.version!==1||!r(a.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[t,s]of Object.entries(a.tables))if(!l(s))return{error:`baseline table "${t}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof a.jurisdiction=="string"?a.jurisdiction:void 0,migrationIds:Array.isArray(a.migrationIds)?a.migrationIds:[],tables:a.tables,version:1},status:"ok"}},c=(e,a)=>e.unique===a.unique&&e.fields.length===a.fields.length&&e.fields.every((t,s)=>t===a.fields[s]),u=(e,a,t,s)=>{const i=[];return t.kind!==s.kind&&i.push({severity:"breaking",summary:`field ${e}.${a} changed type: ${t.kind} → ${s.kind} — add a data migration to convert existing values`,table:e,scope:"table",type:"changedFieldKind"}),t.optional&&!s.optional?i.push({severity:"breaking",summary:`field ${e}.${a} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&s.optional&&i.push({scope:"table",severity:"safe",summary:`field ${e}.${a} became optional`,table:e,type:"fieldRequiredToOptional"}),i},p=(e,a,t)=>t.optional?{scope:"table",severity:"safe",summary:`added optional field ${e}.${a}`,table:e,type:"addedOptionalField"}:{severity:"breaking",summary:`added required field ${e}.${a} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},b=(e,a,t,s)=>{for(const[i,o]of Object.entries(t.fields)){const n=a.fields[i];n===void 0?s.push(p(e,i,o)):s.push(...u(e,i,n,o))}for(const i of Object.keys(a.fields))t.fields[i]===void 0&&s.push({severity:"breaking",summary:`removed field ${e}.${i} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},m=(e,a,t,s)=>{for(const[i,o]of Object.entries(t.indexes)){const n=a.indexes[i];if(n===void 0){s.push({scope:"table",severity:"safe",summary:`added index ${i} on ${e}`,table:e,type:"addedIndex"});continue}c(n,o)||s.push({severity:"breaking",summary:`index ${i} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const i of Object.keys(a.indexes))t.indexes[i]===void 0&&s.push({severity:"breaking",summary:`removed index ${i} on ${e} — a query that used \`.withIndex("${i}")\` would break`,table:e,scope:"table",type:"removedIndex"})},h=(e,a,t,s)=>{for(const i of Object.keys(t.relations))a.relations[i]===void 0&&s.push({scope:"schema",severity:"safe",summary:`added relation ${e}.${i}`,table:e,type:"addedRelation"});for(const i of Object.keys(a.relations))t.relations[i]===void 0&&s.push({scope:"schema",severity:"breaking",summary:`removed relation ${e}.${i}`,table:e,type:"removedRelation"})},y=(e,a,t,s)=>{a.shardMode!==t.shardMode&&s.push({severity:"breaking",summary:`table ${e} changed shard mode: ${a.shardMode} → ${t.shardMode} — its physical storage moves; add a data migration / re-shard plan`,table:e,scope:"table",type:"changedShardMode"}),b(e,a,t,s),m(e,a,t,s),h(e,a,t,s)},k=(e,a)=>{const t=[],s=e?.tables??{};for(const[i,o]of Object.entries(a.tables)){const n=s[i];if(n===void 0){t.push({scope:"table",severity:"safe",summary:`added table ${i}`,table:i,type:"addedTable"});continue}y(i,n,o,t)}for(const i of Object.keys(s))a.tables[i]===void 0&&t.push({scope:"table",severity:"breaking",summary:`removed table ${i} — add a data migration if its data must be archived/cleaned up`,table:i,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==a.jurisdiction){const i=e.jurisdiction??"(none)",o=a.jurisdiction??"(none)";t.push({scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${i} to ${o} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{f as SCHEMA_SNAPSHOT_VERSION,k as diffSchemaSnapshots,g as hashSchemaSnapshot,l as isValidTableSnapshot,$ as parseSnapshotJson,d as serializeSchemaSnapshot,v as sortKeys};