@lunora/codegen 1.0.0-alpha.54 → 1.0.0-alpha.56

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.
Files changed (78) hide show
  1. package/dist/index.d.mts +65 -6
  2. package/dist/index.d.ts +65 -6
  3. package/dist/index.mjs +1 -38
  4. package/dist/packem_shared/AGENTS_FILENAME-BesaDYkL.mjs +1 -0
  5. package/dist/packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs +1 -0
  6. package/dist/packem_shared/CodegenDiagnosticError-DPezpZTz.mjs +1 -0
  7. package/dist/packem_shared/FLAGS_FILENAME-DW5oGq1q.mjs +1 -0
  8. package/dist/packem_shared/GENERATED_HEADER-C94PuLpQ.mjs +1 -0
  9. package/dist/packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs +1 -0
  10. package/dist/packem_shared/MUTATORS_FILENAME-BKKPROzu.mjs +1 -0
  11. package/dist/packem_shared/NOTIFY_FILENAME-C-c7Lg-U.mjs +1 -0
  12. package/dist/packem_shared/OPENRPC_VERSION-DpV3v2W8.mjs +3 -0
  13. package/dist/packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs +1 -0
  14. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DJsxljOQ.mjs +3 -0
  15. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-Bpf1FGMG.mjs +15 -0
  16. package/dist/packem_shared/SHAPES_FILENAME-DTkSJSsg.mjs +1 -0
  17. package/dist/packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs +1 -0
  18. package/dist/packem_shared/buildOpenApiDocument-DXX1G3GZ.mjs +3 -0
  19. package/dist/packem_shared/discover-ast-CezKqEhE.mjs +1 -0
  20. package/dist/packem_shared/discoverAuthApiCalls-DOfSQqVK.mjs +1 -0
  21. package/dist/packem_shared/discoverCrons-B09_uEuL.mjs +1 -0
  22. package/dist/packem_shared/discoverFunctions-BdibLQmc.mjs +1 -0
  23. package/dist/packem_shared/discoverHttpRoutes-BOWz6y_n.mjs +1 -0
  24. package/dist/packem_shared/discoverInserts-BtteTyNy.mjs +1 -0
  25. package/dist/packem_shared/discoverMaskProcedures-COPmwMBm.mjs +1 -0
  26. package/dist/packem_shared/discoverMigrations-iGMlp9YJ.mjs +1 -0
  27. package/dist/packem_shared/discoverNondeterministicCalls-Dmgc4QBx.mjs +1 -0
  28. package/dist/packem_shared/discoverQueries-CcfuGKHh.mjs +1 -0
  29. package/dist/packem_shared/discoverR2sqlCalls-CjZKvg-N.mjs +1 -0
  30. package/dist/packem_shared/discoverRlsMetadata-BXmNOgry.mjs +1 -0
  31. package/dist/packem_shared/discoverSandboxUsage-CDdBqWcM.mjs +1 -0
  32. package/dist/packem_shared/discoverSchema-m2voTncu.mjs +1 -0
  33. package/dist/packem_shared/discoverStorageRulesMetadata-b71cJJHz.mjs +1 -0
  34. package/dist/packem_shared/emit-Dr6XSLfW.mjs +2104 -0
  35. package/dist/packem_shared/emitApp-B671iU7r.mjs +413 -0
  36. package/dist/packem_shared/formatAdvisories-DZvv-0MG.mjs +2 -0
  37. package/dist/packem_shared/parse-validator-CSDlMEvE.mjs +1 -0
  38. package/dist/packem_shared/paths-BmX5O1sG.mjs +1 -0
  39. package/dist/packem_shared/redact-CQ8-to6l.mjs +1 -0
  40. package/dist/packem_shared/schemaFromIr-R1ZFzVyy.mjs +1 -0
  41. package/package.json +3 -3
  42. package/dist/packem_shared/AGENTS_FILENAME-Cxx7wiSs.mjs +0 -158
  43. package/dist/packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs +0 -224
  44. package/dist/packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs +0 -24
  45. package/dist/packem_shared/FLAGS_FILENAME-D5igzqwR.mjs +0 -139
  46. package/dist/packem_shared/GENERATED_HEADER-C8tAvxqP.mjs +0 -4
  47. package/dist/packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs +0 -68
  48. package/dist/packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs +0 -81
  49. package/dist/packem_shared/NOTIFY_FILENAME-CK2IrsrP.mjs +0 -152
  50. package/dist/packem_shared/OPENRPC_VERSION-DvDChMhC.mjs +0 -60
  51. package/dist/packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs +0 -145
  52. package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME--TKFIHmr.mjs +0 -3597
  53. package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs +0 -249
  54. package/dist/packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs +0 -94
  55. package/dist/packem_shared/WORKFLOWS_FILENAME-Dtuzvluc.mjs +0 -158
  56. package/dist/packem_shared/buildOpenApiDocument-DCQSLuFc.mjs +0 -262
  57. package/dist/packem_shared/discover-ast-CT6BgBr4.mjs +0 -13
  58. package/dist/packem_shared/discoverAuthApiCalls-Dhwgf4J4.mjs +0 -62
  59. package/dist/packem_shared/discoverCrons-UbQLLmMS.mjs +0 -286
  60. package/dist/packem_shared/discoverFunctions-COG_Xkyz.mjs +0 -544
  61. package/dist/packem_shared/discoverHttpRoutes-CVXWZkzo.mjs +0 -139
  62. package/dist/packem_shared/discoverInserts-DdWnXmLS.mjs +0 -61
  63. package/dist/packem_shared/discoverMaskProcedures-BG58_fw3.mjs +0 -273
  64. package/dist/packem_shared/discoverMigrations-Bw1U01zr.mjs +0 -97
  65. package/dist/packem_shared/discoverNondeterministicCalls-BbXEFZUT.mjs +0 -122
  66. package/dist/packem_shared/discoverQueries-CDmxu2ET.mjs +0 -62
  67. package/dist/packem_shared/discoverR2sqlCalls-Bn7QVv7J.mjs +0 -80
  68. package/dist/packem_shared/discoverRlsMetadata-D9uN35no.mjs +0 -280
  69. package/dist/packem_shared/discoverSandboxUsage-B5jDU6Bt.mjs +0 -38
  70. package/dist/packem_shared/discoverSchema-BJp5_T4o.mjs +0 -906
  71. package/dist/packem_shared/discoverStorageRulesMetadata-BqMhuEjo.mjs +0 -97
  72. package/dist/packem_shared/emit-DIbr7U31.mjs +0 -3884
  73. package/dist/packem_shared/emitApp-DbMM8iHe.mjs +0 -706
  74. package/dist/packem_shared/formatAdvisories-Cans5TWS.mjs +0 -131
  75. package/dist/packem_shared/parse-validator-BDGV8iue.mjs +0 -144
  76. package/dist/packem_shared/paths-BRd6JHuF.mjs +0 -11
  77. package/dist/packem_shared/redact-oTmsol5A.mjs +0 -33
  78. package/dist/packem_shared/schemaFromIr-DTYsLBaA.mjs +0 -57
package/dist/index.d.mts CHANGED
@@ -159,6 +159,16 @@ interface ExternalSourceIR {
159
159
  unanalyzable?: boolean;
160
160
  }
161
161
  interface TableIR {
162
+ /**
163
+ * The `defineSchemaExtension` key that contributed this table, set when it
164
+ * arrived through `defineSchema(...).extend(...)`. Absent for a table the app
165
+ * declared itself.
166
+ *
167
+ * Drives the generated `AppTableName` union: an add-on's tables
168
+ * (`ratelimit_buckets`, …) are real tables and stay in `TableName`, but an app
169
+ * enumerating "my tables" should not have to know about them.
170
+ */
171
+ extensionKey?: string;
162
172
  /**
163
173
  * `true` when the table chain carried `.externallyManaged()` — its rows are
164
174
  * written outside Lunora's discoverable insert path (adapter/migration/
@@ -293,6 +303,12 @@ interface MigrationIR {
293
303
  * because the runtime object (`columns`/`compileWhere`) carries the authority.
294
304
  */
295
305
  interface ShapeIR {
306
+ /**
307
+ * The shape's `args` validator map — its partition selector. Lifted so
308
+ * `_generated/collections.ts` can type the selector a caller passes instead of
309
+ * widening it to `Record<string, unknown>`. `{}` for a parameterless shape.
310
+ */
311
+ args: Record<string, ValidatorIR>;
296
312
  /** Export binding name — the shape's registry key and import member. */
297
313
  exportName: string;
298
314
  /** Path relative to `&lt;projectRoot>/lunora/` without extension — always `"shapes"`. */
@@ -1091,6 +1107,26 @@ interface KvKeyAccessIR {
1091
1107
  * arg-derived identity write reaches here. Structurally identical to
1092
1108
  * `AdvisorOwnerFieldWrite`.
1093
1109
  */
1110
+ /**
1111
+ * One branching `defineShape({ where })` / `definePolicy({ when })` predicate arm
1112
+ * that returns an unrestricted predicate — the `unrestricted_where_branch` lint
1113
+ * input. A denial arm must match NO rows (`deny()` / `{ OR: [] }`); `{}` matches
1114
+ * every row, so the near-miss silently replicates the whole table.
1115
+ */
1116
+ interface UnrestrictedWhereBranchIR {
1117
+ /** Export binding name of the shape / policy the predicate belongs to. */
1118
+ exportName: string;
1119
+ /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1120
+ file: string;
1121
+ /** Which unrestricted form was returned. */
1122
+ form: "empty-object" | "undefined";
1123
+ /** The config key carrying the predicate (`where` for a shape, `when` for a policy). */
1124
+ key: string;
1125
+ /** 1-based line of the offending returned expression. */
1126
+ line: number;
1127
+ /** The declaring call (`defineShape` / `definePolicy`). */
1128
+ owner: string;
1129
+ }
1094
1130
  interface OwnerFieldWriteIR {
1095
1131
  /** Export binding name of the procedure performing the write. */
1096
1132
  exportName: string;
@@ -1756,6 +1792,7 @@ interface LintSchemaOptions {
1756
1792
  sqlInterpolations?: ReadonlyArray<SqlInterpolationIR>;
1757
1793
  storageKeyAccesses?: ReadonlyArray<StorageKeyAccessIR>;
1758
1794
  storageUploads?: ReadonlyArray<StorageUploadIR>;
1795
+ unrestrictedWhereBranches?: ReadonlyArray<UnrestrictedWhereBranchIR>;
1759
1796
  vectorNamespaceAccesses?: ReadonlyArray<VectorNamespaceAccessIR>;
1760
1797
  workflowCalls?: ReadonlyArray<WorkflowCallIR>;
1761
1798
  workflows?: ReadonlyArray<WorkflowIR>;
@@ -2038,11 +2075,28 @@ interface EmitApiOptions {
2038
2075
  }
2039
2076
  declare const emitApi: (options: EmitApiOptions) => string;
2040
2077
  /**
2041
- * Emit `_generated/collections.ts` — one TanStack DB collection factory per
2042
- * `defineShape` in `lunora/shapes.ts` (the local-first partial-replication
2043
- * surface). Each factory builds a live collection that syncs its shape's rowset
2044
- * through the client's poke protocol (`subscribeShape`), so an app feeds the
2045
- * result straight to `useLiveQuery`.
2078
+ * Emit `_generated/collections.ts` — a typed TanStack DB binding per `defineShape`
2079
+ * in `lunora/shapes.ts` (the local-first partial-replication surface).
2080
+ *
2081
+ * Each shape emits **two** entry points.
2082
+ *
2083
+ * `&lt;shape>CollectionOptions(options)` is the composable form: it returns the full
2084
+ * `LunoraCollectionOptions` — `config` for `createCollection`, plus `checkpoints`
2085
+ * (which `bindMutators` gates optimistic overlays on) and `scope`. This is what an app
2086
+ * with custom mutators needs, and what the old single-factory form made impossible: it
2087
+ * built the collection internally and dropped `checkpoints` on the floor, so there was
2088
+ * no way to wire mutators to the collection codegen produced.
2089
+ *
2090
+ * `&lt;shape>Collection(options)` is the convenience form for a read-only collection: it
2091
+ * returns `{ checkpoints, collection, scope }` rather than a bare `Collection`, so the
2092
+ * sync controls stay reachable even from the short path.
2093
+ *
2094
+ * Both are typed: `args` comes from the shape's own validators (a parameterless
2095
+ * shape takes none), rows resolve to `Doc&lt;"table">` when the shape names its table
2096
+ * with a literal, and `shardKey` / `getKey` / `load` / `onError` / `checkpoints` are
2097
+ * all threadable — a sharded table needs `shardKey` for its watermark to land in the
2098
+ * right bucket, and a server-minted `_id` that differs from the app's natural key
2099
+ * needs `getKey`.
2046
2100
  *
2047
2101
  * Returns `""` (so `writeIfPresent` skips the file) unless the project both
2048
2102
  * declares shapes AND installs `@lunora/db` — the add-on that ships
@@ -2505,7 +2559,12 @@ interface SchemaDrift {
2505
2559
  /**
2506
2560
  * Build a {@link SchemaSnapshot} from a parsed {@link SchemaIR} and the set of
2507
2561
  * declared migration ids. Tables and migration ids are sorted so the emitted
2508
- * JSON is byte-stable across runs (no spurious diffs / churn).
2562
+ * JSON is byte-stable across runs AND across machines (no spurious diffs /
2563
+ * churn) — see {@link sortKeys} for why that ordering must not be locale-aware.
2564
+ *
2565
+ * Field / index / relation keys are deliberately NOT sorted: they are emitted in
2566
+ * declaration order from the schema source, which is already deterministic for a
2567
+ * given source file and keeps the snapshot readable next to the schema it mirrors.
2509
2568
  */
2510
2569
  declare const buildSchemaSnapshot: (schema: SchemaIR, migrationIds: ReadonlyArray<string>) => SchemaSnapshot;
2511
2570
  /** Serialize a snapshot to the exact bytes written to `lunora/.lunora-schema.json` (trailing newline). */
package/dist/index.d.ts CHANGED
@@ -159,6 +159,16 @@ interface ExternalSourceIR {
159
159
  unanalyzable?: boolean;
160
160
  }
161
161
  interface TableIR {
162
+ /**
163
+ * The `defineSchemaExtension` key that contributed this table, set when it
164
+ * arrived through `defineSchema(...).extend(...)`. Absent for a table the app
165
+ * declared itself.
166
+ *
167
+ * Drives the generated `AppTableName` union: an add-on's tables
168
+ * (`ratelimit_buckets`, …) are real tables and stay in `TableName`, but an app
169
+ * enumerating "my tables" should not have to know about them.
170
+ */
171
+ extensionKey?: string;
162
172
  /**
163
173
  * `true` when the table chain carried `.externallyManaged()` — its rows are
164
174
  * written outside Lunora's discoverable insert path (adapter/migration/
@@ -293,6 +303,12 @@ interface MigrationIR {
293
303
  * because the runtime object (`columns`/`compileWhere`) carries the authority.
294
304
  */
295
305
  interface ShapeIR {
306
+ /**
307
+ * The shape's `args` validator map — its partition selector. Lifted so
308
+ * `_generated/collections.ts` can type the selector a caller passes instead of
309
+ * widening it to `Record&lt;string, unknown>`. `{}` for a parameterless shape.
310
+ */
311
+ args: Record<string, ValidatorIR>;
296
312
  /** Export binding name — the shape's registry key and import member. */
297
313
  exportName: string;
298
314
  /** Path relative to `&lt;projectRoot>/lunora/` without extension — always `"shapes"`. */
@@ -1091,6 +1107,26 @@ interface KvKeyAccessIR {
1091
1107
  * arg-derived identity write reaches here. Structurally identical to
1092
1108
  * `AdvisorOwnerFieldWrite`.
1093
1109
  */
1110
+ /**
1111
+ * One branching `defineShape({ where })` / `definePolicy({ when })` predicate arm
1112
+ * that returns an unrestricted predicate — the `unrestricted_where_branch` lint
1113
+ * input. A denial arm must match NO rows (`deny()` / `{ OR: [] }`); `{}` matches
1114
+ * every row, so the near-miss silently replicates the whole table.
1115
+ */
1116
+ interface UnrestrictedWhereBranchIR {
1117
+ /** Export binding name of the shape / policy the predicate belongs to. */
1118
+ exportName: string;
1119
+ /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1120
+ file: string;
1121
+ /** Which unrestricted form was returned. */
1122
+ form: "empty-object" | "undefined";
1123
+ /** The config key carrying the predicate (`where` for a shape, `when` for a policy). */
1124
+ key: string;
1125
+ /** 1-based line of the offending returned expression. */
1126
+ line: number;
1127
+ /** The declaring call (`defineShape` / `definePolicy`). */
1128
+ owner: string;
1129
+ }
1094
1130
  interface OwnerFieldWriteIR {
1095
1131
  /** Export binding name of the procedure performing the write. */
1096
1132
  exportName: string;
@@ -1756,6 +1792,7 @@ interface LintSchemaOptions {
1756
1792
  sqlInterpolations?: ReadonlyArray<SqlInterpolationIR>;
1757
1793
  storageKeyAccesses?: ReadonlyArray<StorageKeyAccessIR>;
1758
1794
  storageUploads?: ReadonlyArray<StorageUploadIR>;
1795
+ unrestrictedWhereBranches?: ReadonlyArray<UnrestrictedWhereBranchIR>;
1759
1796
  vectorNamespaceAccesses?: ReadonlyArray<VectorNamespaceAccessIR>;
1760
1797
  workflowCalls?: ReadonlyArray<WorkflowCallIR>;
1761
1798
  workflows?: ReadonlyArray<WorkflowIR>;
@@ -2038,11 +2075,28 @@ interface EmitApiOptions {
2038
2075
  }
2039
2076
  declare const emitApi: (options: EmitApiOptions) => string;
2040
2077
  /**
2041
- * Emit `_generated/collections.ts` — one TanStack DB collection factory per
2042
- * `defineShape` in `lunora/shapes.ts` (the local-first partial-replication
2043
- * surface). Each factory builds a live collection that syncs its shape's rowset
2044
- * through the client's poke protocol (`subscribeShape`), so an app feeds the
2045
- * result straight to `useLiveQuery`.
2078
+ * Emit `_generated/collections.ts` — a typed TanStack DB binding per `defineShape`
2079
+ * in `lunora/shapes.ts` (the local-first partial-replication surface).
2080
+ *
2081
+ * Each shape emits **two** entry points.
2082
+ *
2083
+ * `&lt;shape>CollectionOptions(options)` is the composable form: it returns the full
2084
+ * `LunoraCollectionOptions` — `config` for `createCollection`, plus `checkpoints`
2085
+ * (which `bindMutators` gates optimistic overlays on) and `scope`. This is what an app
2086
+ * with custom mutators needs, and what the old single-factory form made impossible: it
2087
+ * built the collection internally and dropped `checkpoints` on the floor, so there was
2088
+ * no way to wire mutators to the collection codegen produced.
2089
+ *
2090
+ * `&lt;shape>Collection(options)` is the convenience form for a read-only collection: it
2091
+ * returns `{ checkpoints, collection, scope }` rather than a bare `Collection`, so the
2092
+ * sync controls stay reachable even from the short path.
2093
+ *
2094
+ * Both are typed: `args` comes from the shape's own validators (a parameterless
2095
+ * shape takes none), rows resolve to `Doc&lt;"table">` when the shape names its table
2096
+ * with a literal, and `shardKey` / `getKey` / `load` / `onError` / `checkpoints` are
2097
+ * all threadable — a sharded table needs `shardKey` for its watermark to land in the
2098
+ * right bucket, and a server-minted `_id` that differs from the app's natural key
2099
+ * needs `getKey`.
2046
2100
  *
2047
2101
  * Returns `""` (so `writeIfPresent` skips the file) unless the project both
2048
2102
  * declares shapes AND installs `@lunora/db` — the add-on that ships
@@ -2505,7 +2559,12 @@ interface SchemaDrift {
2505
2559
  /**
2506
2560
  * Build a {@link SchemaSnapshot} from a parsed {@link SchemaIR} and the set of
2507
2561
  * declared migration ids. Tables and migration ids are sorted so the emitted
2508
- * JSON is byte-stable across runs (no spurious diffs / churn).
2562
+ * JSON is byte-stable across runs AND across machines (no spurious diffs /
2563
+ * churn) — see {@link sortKeys} for why that ordering must not be locale-aware.
2564
+ *
2565
+ * Field / index / relation keys are deliberately NOT sorted: they are emitted in
2566
+ * declaration order from the schema source, which is already deterministic for a
2567
+ * given source file and keeps the snapshot readable next to the schema it mirrors.
2509
2568
  */
2510
2569
  declare const buildSchemaSnapshot: (schema: SchemaIR, migrationIds: ReadonlyArray<string>) => SchemaSnapshot;
2511
2570
  /** Serialize a snapshot to the exact bytes written to `lunora/.lunora-schema.json` (trailing newline). */
package/dist/index.mjs CHANGED
@@ -1,38 +1 @@
1
- export { formatAdvisories, lintSchema } from './packem_shared/formatAdvisories-Cans5TWS.mjs';
2
- export { CodegenDiagnosticError, diagnosticAt } from './packem_shared/CodegenDiagnosticError-DyQ5FwkM.mjs';
3
- export { AGENTS_FILENAME, discoverAgents } from './packem_shared/AGENTS_FILENAME-Cxx7wiSs.mjs';
4
- export { default as discoverAuthApiCalls } from './packem_shared/discoverAuthApiCalls-Dhwgf4J4.mjs';
5
- export { CONTAINERS_FILENAME, discoverContainers } from './packem_shared/CONTAINERS_FILENAME-DjpXMqhp.mjs';
6
- export { default as discoverCrons } from './packem_shared/discoverCrons-UbQLLmMS.mjs';
7
- export { FLAGS_FILENAME, discoverFlags } from './packem_shared/FLAGS_FILENAME-D5igzqwR.mjs';
8
- export { discoverFunctions } from './packem_shared/discoverFunctions-COG_Xkyz.mjs';
9
- export { default as discoverHttpRoutes } from './packem_shared/discoverHttpRoutes-CVXWZkzo.mjs';
10
- export { default as discoverInserts } from './packem_shared/discoverInserts-DdWnXmLS.mjs';
11
- export { default as discoverMaskProcedures } from './packem_shared/discoverMaskProcedures-BG58_fw3.mjs';
12
- export { default as discoverMigrations } from './packem_shared/discoverMigrations-Bw1U01zr.mjs';
13
- export { MUTATORS_FILENAME, discoverMutators } from './packem_shared/MUTATORS_FILENAME-BZOfUhlY.mjs';
14
- export { default as discoverNondeterministicCalls } from './packem_shared/discoverNondeterministicCalls-BbXEFZUT.mjs';
15
- export { NOTIFY_FILENAME, discoverNotifyCalls, discoverNotifyConfig } from './packem_shared/NOTIFY_FILENAME-CK2IrsrP.mjs';
16
- export { default as discoverQueries } from './packem_shared/discoverQueries-CDmxu2ET.mjs';
17
- export { QUEUES_FILENAME, discoverQueues } from './packem_shared/QUEUES_FILENAME-Xv6Vy-Ku.mjs';
18
- export { default as discoverR2sqlCalls } from './packem_shared/discoverR2sqlCalls-Bn7QVv7J.mjs';
19
- export { discoverRlsMetadata, default as discoverRlsProcedures } from './packem_shared/discoverRlsMetadata-D9uN35no.mjs';
20
- export { discoverSandboxUsage } from './packem_shared/discoverSandboxUsage-B5jDU6Bt.mjs';
21
- export { default as discoverSchema } from './packem_shared/discoverSchema-BJp5_T4o.mjs';
22
- export { SHAPES_FILENAME, discoverShapes } from './packem_shared/SHAPES_FILENAME-DOhPGi-6.mjs';
23
- export { default as discoverStorageRulesMetadata } from './packem_shared/discoverStorageRulesMetadata-BqMhuEjo.mjs';
24
- export { WORKFLOWS_FILENAME, discoverWorkflows } from './packem_shared/WORKFLOWS_FILENAME-Dtuzvluc.mjs';
25
- export { G as GENERATED_HEADER, e as emitAgents, a as emitApi, b as emitCollections, c as emitContainers, d as emitCrons, f as emitDataModel, g as emitDrizzleSchema, h as emitFunctions, i as emitServer, j as emitShard, k as emitVectors, l as emitWorkflows, m as emitWranglerCronTriggers } from './packem_shared/emit-DIbr7U31.mjs';
26
- export { emitApp } from './packem_shared/emitApp-DbMM8iHe.mjs';
27
- export { buildOpenApiDocument, emitOpenApi, emitOpenApiModule } from './packem_shared/buildOpenApiDocument-DCQSLuFc.mjs';
28
- export { OPENRPC_VERSION, buildOpenRpcDocument, emitOpenRpc, emitOpenRpcModule } from './packem_shared/OPENRPC_VERSION-DvDChMhC.mjs';
29
- export { SCHEMA_SNAPSHOT_FILENAME, createCodegenProject, refreshCodegenProject, runCodegen } from './packem_shared/SCHEMA_SNAPSHOT_FILENAME--TKFIHmr.mjs';
30
- export { SCHEMA_SNAPSHOT_VERSION, SchemaSnapshotParseError, buildSchemaSnapshot, diffSchemaSnapshots, evaluateSchemaDrift, parseSchemaSnapshot, serializeSchemaSnapshot } from './packem_shared/SCHEMA_SNAPSHOT_VERSION-D0ARY6rL.mjs';
31
- export { schemaFromIr } from './packem_shared/schemaFromIr-DTYsLBaA.mjs';
32
- export { LUNORA_ERROR_CODES, validatorIrToJsonSchema } from './packem_shared/LUNORA_ERROR_CODES-DvTLozCu.mjs';
33
- export { redact, secretKindOf } from './packem_shared/redact-oTmsol5A.mjs';
34
- export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, findSolutionByMessage as findLunoraSolution } from '@lunora/errors';
35
-
36
- const VERSION = "0.0.0";
37
-
38
- export { VERSION };
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-DOfSQqVK.mjs";import{CONTAINERS_FILENAME as l,discoverContainers as E}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as x}from"./packem_shared/discoverCrons-B09_uEuL.mjs";import{FLAGS_FILENAME as v,discoverFlags as N}from"./packem_shared/FLAGS_FILENAME-DW5oGq1q.mjs";import{discoverFunctions as R}from"./packem_shared/discoverFunctions-BdibLQmc.mjs";import{default as h}from"./packem_shared/discoverHttpRoutes-BOWz6y_n.mjs";import{default as I}from"./packem_shared/discoverInserts-BtteTyNy.mjs";import{default as g}from"./packem_shared/discoverMaskProcedures-COPmwMBm.mjs";import{default as F}from"./packem_shared/discoverMigrations-iGMlp9YJ.mjs";import{MUTATORS_FILENAME as D,discoverMutators as P}from"./packem_shared/MUTATORS_FILENAME-BKKPROzu.mjs";import{default as H}from"./packem_shared/discoverNondeterministicCalls-Dmgc4QBx.mjs";import{NOTIFY_FILENAME as W,discoverNotifyCalls as b,discoverNotifyConfig as z}from"./packem_shared/NOTIFY_FILENAME-C-c7Lg-U.mjs";import{default as k}from"./packem_shared/discoverQueries-CcfuGKHh.mjs";import{QUEUES_FILENAME as y,discoverQueues as K}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as j}from"./packem_shared/discoverR2sqlCalls-CjZKvg-N.mjs";import{discoverRlsMetadata as q,default as B}from"./packem_shared/discoverRlsMetadata-BXmNOgry.mjs";import{discoverSandboxUsage as X}from"./packem_shared/discoverSandboxUsage-CDdBqWcM.mjs";import{default as $}from"./packem_shared/discoverSchema-m2voTncu.mjs";import{SHAPES_FILENAME as oe,discoverShapes as re}from"./packem_shared/SHAPES_FILENAME-DTkSJSsg.mjs";import{default as se}from"./packem_shared/discoverStorageRulesMetadata-b71cJJHz.mjs";import{WORKFLOWS_FILENAME as ie,discoverWorkflows as me}from"./packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{w as fe,E as pe,n as ce,o as ne,L as Se,X as le,G as Ee,z as ue,g as xe,u as Ae,K as ve,Y as Ne,D as Oe,Z as Re}from"./packem_shared/emit-Dr6XSLfW.mjs";import{emitApp as he}from"./packem_shared/emitApp-B671iU7r.mjs";import{buildOpenApiDocument as Ie,emitOpenApi as _e,emitOpenApiModule as ge}from"./packem_shared/buildOpenApiDocument-DXX1G3GZ.mjs";import{OPENRPC_VERSION as Fe,buildOpenRpcDocument as Te,emitOpenRpc as De,emitOpenRpcModule as Pe}from"./packem_shared/OPENRPC_VERSION-DpV3v2W8.mjs";import{SCHEMA_SNAPSHOT_FILENAME as He,createCodegenProject as Ge,refreshCodegenProject as We,runCodegen as be}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-DJsxljOQ.mjs";import{SCHEMA_SNAPSHOT_VERSION as Ve,SchemaSnapshotParseError as ke,buildSchemaSnapshot as we,diffSchemaSnapshots as ye,evaluateSchemaDrift as Ke,parseSchemaSnapshot as Qe,serializeSchemaSnapshot as je}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-Bpf1FGMG.mjs";import{schemaFromIr as qe}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as Je,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,Je as LUNORA_ERROR_CODES,ro as LUNORA_SOLUTION_RULES,D as MUTATORS_FILENAME,W as NOTIFY_FILENAME,Fe as OPENRPC_VERSION,y as QUEUES_FILENAME,He as SCHEMA_SNAPSHOT_FILENAME,Ve as SCHEMA_SNAPSHOT_VERSION,oe as SHAPES_FILENAME,ke as SchemaSnapshotParseError,e as VERSION,ie as WORKFLOWS_FILENAME,Ie as buildOpenApiDocument,Te as buildOpenRpcDocument,we as buildSchemaSnapshot,Ge as createCodegenProject,m as diagnosticAt,ye as diffSchemaSnapshots,p as discoverAgents,n as discoverAuthApiCalls,E as discoverContainers,x as discoverCrons,N as discoverFlags,R as discoverFunctions,h as discoverHttpRoutes,I as discoverInserts,g as discoverMaskProcedures,F as discoverMigrations,P as discoverMutators,H as discoverNondeterministicCalls,b as discoverNotifyCalls,z as discoverNotifyConfig,k as discoverQueries,K as discoverQueues,j as discoverR2sqlCalls,q as discoverRlsMetadata,B 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,ue as emitDrizzleSchema,xe as emitFunctions,_e as emitOpenApi,ge as emitOpenApiModule,De as emitOpenRpc,Pe as emitOpenRpcModule,Ae as emitServer,ve as emitShard,Ne as emitVectors,Oe as emitWorkflows,Re as emitWranglerCronTriggers,Ke as evaluateSchemaDrift,to as findLunoraSolution,t as formatAdvisories,s as lintSchema,Qe as parseSchemaSnapshot,$e as redact,We as refreshCodegenProject,be as runCodegen,qe as schemaFromIr,eo as secretKindOf,je as serializeSchemaSnapshot,Xe as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import{existsSync as u}from"node:fs";import{join as p}from"node:path";import{agentDefaultName as d,agentClassName as f,agentBindingName as N,voiceBindingName as b,voiceClassName as x}from"@lunora/agent/naming";import{LunoraError as m}from"@lunora/errors";import{Node as o,SyntaxKind as l}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-DPezpZTz.mjs";const w="agents.ts",A=i=>{const e=i.getSymbol();if(!e)return i.getText()==="defineAgent";for(const n of e.getDeclarations())if(o.isImportSpecifier(n))return n.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/agent"?!1:n.getNameNode().getText()==="defineAgent";return!1},E=(i,e,n)=>{if(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))return i.getLiteralValue();throw g(i,`agent "${e}": \`${n}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},h=(i,e,n)=>{if(i.getKind()===l.TrueKeyword)return!0;if(i.getKind()===l.FalseKeyword)return!1;throw g(i,`agent "${e}": \`${n}\` must be a static boolean literal — it is deploy configuration codegen writes into the ctx.agents wiring spec`)},y=(i,e)=>{const n=i.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))throw g(i,`agent "${e}": defineAgent must be passed an inline object literal`);const r={bindingName:N(e),className:f(e),exportName:e,name:d(e)},t=n.getProperty("name");t&&o.isPropertyAssignment(t)&&(r.name=E(t.getInitializerOrThrow(),e,"name"));const s=n.getProperty("publicRun");s&&o.isPropertyAssignment(s)&&h(s.getInitializerOrThrow(),e,"publicRun")&&(r.publicRun=!0);const a=n.getProperty("voice");if(a&&o.isPropertyAssignment(a)){const c=a.getInitializerOrThrow();if(!o.isObjectLiteralExpression(c))throw g(c,`agent "${e}": \`voice\` must be an inline object literal — its presence tells codegen to emit the voice-session Durable Object`);r.voice=!0,r.voiceBindingName=b(e),r.voiceClassName=x(e)}return n.getProperty("onEmail")&&(r.onEmail=!0),r},I=i=>{let e=i;for(;e&&(o.isAsExpression(e)||o.isSatisfiesExpression(e)||o.isParenthesizedExpression(e));)e=e.getExpression();return e&&o.isCallExpression(e)?e:void 0},T=i=>{const e=[];for(const n of i.getVariableDeclarations()){if(!n.isExported())continue;const r=I(n.getInitializer());if(!r)continue;const t=r.getExpression();if(!o.isIdentifier(t)||!A(t))continue;const s=n.getNameNode();if(!o.isIdentifier(s))throw g(s,"defineAgent exports must be plain named exports (no destructuring)");e.push(y(r,s.getText()))}return e},$=i=>{const e=new Map,n=new Map,r=new Map;for(const t of i){const s=e.get(t.name);if(s!==void 0)throw new m("DUPLICATE_AGENT_NAME",`Duplicate agent name "${t.name}": produced by both "${s}" and "${t.exportName}". Deployed agent names must be unique across the project.`,{status:500});e.set(t.name,t.exportName);const a=n.get(t.bindingName);if(a!==void 0)throw new m("DUPLICATE_AGENT_BINDING",`Duplicate agent binding "${t.bindingName}": produced by both "${a}" and "${t.exportName}". Agent export names must yield unique binding names.`,{status:500});n.set(t.bindingName,t.exportName);const c=r.get(t.className);if(c!==void 0)throw new m("DUPLICATE_AGENT_CLASS",`Duplicate agent class "${t.className}": produced by both "${c}" and "${t.exportName}". Agent export names must yield unique generated class names.`,{status:500});r.set(t.className,t.exportName)}},j=(i,e)=>{const n=p(e,w);if(!u(n))return[];const r=i.getSourceFile(n)??i.addSourceFileAtPath(n),t=T(r);return t.sort((s,a)=>s.exportName.localeCompare(a.exportName)),$(t),t};export{w as AGENTS_FILENAME,j as discoverAgents};
@@ -0,0 +1 @@
1
+ import{existsSync as f}from"node:fs";import{join as p}from"node:path";import{containerClassName as d,containerBindingName as b,normalizeContainerImage as g}from"@lunora/container";import{SyntaxKind as y,Node as n}from"ts-morph";import{diagnosticAt as s}from"./CodegenDiagnosticError-DPezpZTz.mjs";const L="containers.ts",N=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineContainer";for(const i of t.getDeclarations())if(n.isImportSpecifier(i))return i.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/container"?!1:i.getNameNode().getText()==="defineContainer";return!1},u=(e,t,i)=>{if(n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e))return e.getLiteralValue();throw s(e,`container "${t}": \`${i}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},m=(e,t,i)=>{if(n.isNumericLiteral(e))return e.getLiteralValue();throw s(e,`container "${t}": \`${i}\` must be a static number literal — it is deploy configuration codegen writes into wrangler.jsonc`)},x=(e,t)=>{if(n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e))return g(e.getLiteralValue());if(n.isObjectLiteralExpression(e)){const i=e.getProperty("registry");if(i&&n.isPropertyAssignment(i)){const o=i.getInitializerOrThrow();return g({registry:u(o,t,"image.registry")})}const r=e.getProperty("build");if(r&&n.isPropertyAssignment(r)){const o=r.getInitializerOrThrow();return g({build:u(o,t,"image.build")})}}throw s(e,`container "${t}": \`image\` must be a static string path, { registry: "…" }, or { build: "…" } literal`)},h=e=>{if(!n.isObjectLiteralExpression(e))return;const t={};for(const i of e.getProperties()){if(!n.isPropertyAssignment(i))continue;const r=i.getInitializerOrThrow();(n.isStringLiteral(r)||n.isNoSubstitutionTemplateLiteral(r))&&(t[i.getName()]=r.getLiteralValue())}return Object.keys(t).length>0?t:void 0},w=e=>{if(!n.isObjectLiteralExpression(e))return;const t={};for(const i of e.getProperties()){if(!n.isPropertyAssignment(i))continue;const r=i.getName(),o=i.getInitializerOrThrow();n.isNumericLiteral(o)&&(r==="gracePeriodSeconds"||r==="stepPercentage")&&(t[r]=o.getLiteralValue())}return t.gracePeriodSeconds===void 0&&t.stepPercentage===void 0?void 0:t},T=e=>{if(n.isTrueLiteral(e))return!0;if(n.isFalseLiteral(e))return!1},I=e=>{if(n.isStringLiteral(e)||n.isNoSubstitutionTemplateLiteral(e)||n.isNumericLiteral(e))return e.getLiteralValue()},S=(e,t)=>{if(n.isStringLiteral(e))return e.getLiteralValue();if(n.isObjectLiteralExpression(e)){const i={};for(const r of e.getProperties()){if(!n.isPropertyAssignment(r))throw s(r,`container "${t}": \`instanceType\` must be an object of static number literals`);const o=r.getName();if(o!=="diskMb"&&o!=="memoryMib"&&o!=="vcpu")throw s(r,`container "${t}": unknown \`instanceType\` field "${o}" — expected vcpu, memoryMib, or diskMb`);i[o]=m(r.getInitializerOrThrow(),t,`instanceType.${o}`)}return i}throw s(e,`container "${t}": \`instanceType\` must be a static string or { vcpu, memoryMib, diskMb } literal`)},P=(e,t)=>{const i=e.getArguments()[0];if(!i||!n.isObjectLiteralExpression(i))throw s(e,`container "${t}": defineContainer must be passed an inline object literal`);const r={bindingName:b(t),className:d(t),exportName:t,image:{buildContext:".",dockerfilePath:"./Dockerfile",kind:"dockerfile"}};let o=!1;for(const a of i.getProperties()){if(!n.isPropertyAssignment(a))continue;const l=a.getName(),c=a.getInitializerOrThrow();switch(l){case"buildArgs":{r.buildArgs=h(c);break}case"enableInternet":{r.enableInternet=T(c);break}case"image":{r.image=x(c,t),o=!0;break}case"instanceType":{r.instanceType=S(c,t);break}case"maxInstances":{r.maxInstances=m(c,t,"maxInstances");break}case"name":{r.name=u(c,t,"name");break}case"rollout":{r.rollout=w(c);break}case"sleepAfter":{r.sleepAfter=I(c);break}}}if(!o)throw s(i,`container "${t}": defineContainer requires a static \`image\` property`);return r},k=e=>{const t=[];for(const i of e.getVariableDeclarations()){if(!i.isExported())continue;const r=i.getInitializer();if(r?.getKind()!==y.CallExpression)continue;const o=r,a=o.getExpression();if(!n.isIdentifier(a)||!N(a))continue;const l=i.getNameNode();if(!n.isIdentifier(l))throw s(l,"defineContainer exports must be plain named exports (no destructuring)");t.push(P(o,l.getText()))}return t},j=(e,t)=>{const i=p(t,L);if(!f(i))return[];const r=e.getSourceFile(i)??e.addSourceFileAtPath(i),o=k(r);return o.sort((a,l)=>a.exportName.localeCompare(l.exportName)),o};export{L as CONTAINERS_FILENAME,j as discoverContainers};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";class a extends g{column;file;line;constructor(i,e,n,t){super("CODEGEN_DIAGNOSTIC",i,{location:{column:t,file:e,line:n},name:"CodegenDiagnosticError"}),this.file=e,this.line=n,this.column=t}}const m=(o,i,e)=>{const n=o.getSourceFile(),t=n.getFilePath(),r=o.getStartLineNumber(),{column:c}=n.getLineAndColumnAtPos(o.getStart()),l=`@lunora/codegen: ${i} (${t}:${r.toString()}:${c.toString()})`,s=new a(l,t,r,c);return e?Object.assign(s,e):s};export{a as CodegenDiagnosticError,m as diagnosticAt};
@@ -0,0 +1 @@
1
+ import{existsSync as l}from"node:fs";import{join as c}from"node:path";import{SyntaxKind as p,Node as s}from"ts-morph";import{listLunoraSourceFiles as f}from"./discoverFunctions-BdibLQmc.mjs";const u="flags.ts",d=new Set(["boolean","number","object","string"]),m="@lunora/flags/providers/flagship",x=r=>{const t=r.getSymbol();if(!t)return r.getText()==="flagshipProvider";for(const e of t.getDeclarations())if(s.isImportSpecifier(e))return e.getImportDeclaration().getModuleSpecifierValue()!==m?!1:e.getNameNode().getText()==="flagshipProvider";return!1},y=(r,t)=>{const e=r.getProperty(t);if(!e||!s.isPropertyAssignment(e))return;const i=e.getInitializerOrThrow();if(s.isStringLiteral(i)||s.isNoSubstitutionTemplateLiteral(i))return i.getLiteralValue()},E=r=>{const t=r.getArguments()[0];if(t&&s.isObjectLiteralExpression(t)){const e=y(t,"binding");if(e!==void 0&&e.length>0)return{bindingName:e,mode:"binding",provider:"flagship"}}return{mode:"http",provider:"flagship"}},S=r=>{const t=r.getExportAssignment(n=>!n.isExportEquals());if(!t)return;const e=t.getExpression();if(!s.isIdentifier(e))return e;const i=e.getSymbol()?.getValueDeclaration();return i&&s.isVariableDeclaration(i)?i.getInitializer():e},b=r=>{const t=r.getArguments()[0];if(!t||!s.isObjectLiteralExpression(t))return;const e=t.getProperty("provider");return e&&s.isPropertyAssignment(e)?e.getInitializer():void 0},F=(r,t)=>{const e=c(t,u);if(!l(e))return;const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),n=S(i);if(!n||!s.isCallExpression(n))return{provider:"custom"};const a=b(n);if(a&&s.isCallExpression(a)){const o=a.getExpression();if(s.isIdentifier(o)&&x(o))return E(a)}return{provider:"custom"}},g=r=>s.isIdentifier(r)&&r.getText()==="ctx",h=r=>{const t=r.getName();if(!d.has(t))return;const e=r.getExpression();if(!s.isPropertyAccessExpression(e))return;if(e.getName()==="flags"&&g(e.getExpression()))return t;const i=e.getExpression();if(e.getName()==="details"&&s.isPropertyAccessExpression(i)&&i.getName()==="flags"&&g(i.getExpression()))return t},v=r=>{const t=r.getExpression();if(!s.isPropertyAccessExpression(t))return;const e=h(t);if(e===void 0)return;const i=r.getArguments()[0];if(!i||!(s.isStringLiteral(i)||s.isNoSubstitutionTemplateLiteral(i)))return;const n=i.getLiteralValue();return n.length>0?{key:n,type:e}:void 0},I=(r,t)=>{const e=new Map;for(const i of f(t)){const n=r.getSourceFile(i)??r.addSourceFileAtPath(i);for(const a of n.getDescendantsOfKind(p.CallExpression)){const o=v(a);o&&!e.has(o.key)&&e.set(o.key,o.type)}}return[...e.entries()].map(([i,n])=>({key:i,type:n})).toSorted((i,n)=>i.key.localeCompare(n.key))};export{u as FLAGS_FILENAME,I as discoverFlagKeys,F as discoverFlags};
@@ -0,0 +1 @@
1
+ import"@lunora/agent/component";import"@lunora/errors";import{w as m,a as r,E as o,n,o as l,L as g,X as u,G as E,z as p,g as C,_ as D,b as S,u as c,K as d,Y as A,D as z,Z as b}from"./emit-Dr6XSLfW.mjs";import"./paths-BmX5O1sG.mjs";export{m as GENERATED_HEADER,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,g as emitContainers,u as emitCrons,E as emitDataModel,p as emitDrizzleSchema,C as emitFunctions,D as emitQueues,S as emitSeed,c as emitServer,d as emitShard,A as emitVectors,z as emitWorkflows,b as emitWranglerCronTriggers};
@@ -0,0 +1 @@
1
+ import{jsonSchemaFromNode as n,objectSchemaFromNodes as a}from"@lunora/values";const N=e=>{if(e===void 0)return{};const t=e.trim();if(t==="true")return{const:!0};if(t==="false")return{const:!1};if(t==="null")return{const:null,type:"null"};if(t.startsWith('"')&&t.endsWith('"'))try{return{const:JSON.parse(t),type:"string"}}catch{return{const:t.slice(1,-1),type:"string"}}if(t.startsWith("'")&&t.endsWith("'"))return{const:t.slice(1,-1),type:"string"};const r=Number(t);return Number.isNaN(r)?{const:t}:{const:r}},s={constraints:()=>{},inner:e=>e.inner,isNullable:e=>e.column?.notNull===!1,kind:e=>e.kind,literalSchema:e=>N(e.literalValue),members:e=>e.members??[],shape:e=>e.shape??{},tableName:e=>e.tableName,valueChild:e=>e.valueType},o=e=>n(e,s),l=e=>a(e,s),O=e=>l(e),c=["BAD_REQUEST","CONFLICT","COUNT_RLS_UNSUPPORTED","FORBIDDEN","FUNCTION_NOT_FOUND","INTERNAL","INTERNAL_SERVER_ERROR","METHOD_NOT_ALLOWED","NOT_FOUND","NOT_IMPLEMENTED","PAYLOAD_TOO_LARGE","TOO_MANY_REQUESTS","UNAUTHORIZED","UNPROCESSABLE","VALIDATION_ERROR"];export{c as LUNORA_ERROR_CODES,O as argsObjectSchema,N as literalConst,l as objectSchema,o as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import{existsSync as u}from"node:fs";import{join as l}from"node:path";import{Node as i,SyntaxKind as a}from"ts-morph";import{diagnosticAt as p}from"./CodegenDiagnosticError-DPezpZTz.mjs";const m="mutators.ts",f=new Set(["@lunora/server","lunorash/server"]),d=e=>{const r=e.getSymbol();if(!r)return e.getText()==="defineMutator";for(const t of r.getDeclarations())if(i.isImportSpecifier(t))return f.has(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMutator":!1;return!1},g=e=>{const r=e.getSymbol();if(!r)return!1;for(const t of r.getDeclarations()){if(!i.isNamespaceImport(t))continue;const o=t.getFirstAncestorByKind(a.ImportDeclaration);return o!==void 0&&f.has(o.getModuleSpecifierValue())}return!1},x=e=>{if(i.isIdentifier(e))return d(e);if(i.isPropertyAccessExpression(e)){const r=e.getExpression();return e.getName()==="defineMutator"&&i.isIdentifier(r)&&g(r)}return!1},M=e=>{const r=[];for(const t of e.getVariableDeclarations()){if(!t.isExported())continue;const o=t.getInitializer();if(o?.getKind()!==a.CallExpression)continue;const s=o.getExpression();if(!x(s))continue;const n=t.getNameNode();if(!i.isIdentifier(n))throw p(n,"defineMutator exports must be plain named exports (no destructuring)");r.push({exportName:n.getText(),filePath:"mutators"})}return r},E=(e,r)=>{const t=l(r,m);if(!u(t))return[];const o=e.getSourceFile(t)??e.addSourceFileAtPath(t),s=M(o);return s.sort((n,c)=>n.exportName.localeCompare(c.exportName)),s};export{m as MUTATORS_FILENAME,E as discoverMutators,x as isDefineMutatorCallee};
@@ -0,0 +1 @@
1
+ import{existsSync as x}from"node:fs";import{join as h}from"node:path";import{SyntaxKind as p,Node as o}from"ts-morph";import{listLunoraSourceFiles as l,lunoraRelativePath as m,classifyProcedureCall as y}from"./discoverFunctions-BdibLQmc.mjs";const E="notify.ts",A=new Set(["chat","inApp","send","webhook"]),d=new Set(["broadcast","send"]),P=(t,r)=>{if(r){const n=t.getArguments()[0];return n&&(o.isArrowFunction(n)||o.isFunctionExpression(n))?n:void 0}const e=t.getArguments()[0];if(!e||!o.isObjectLiteralExpression(e))return;const s=e.getProperty("handler");if(!s||!o.isPropertyAssignment(s))return;const i=s.getInitializer();return i&&(o.isArrowFunction(i)||o.isFunctionExpression(i))?i:void 0},F=t=>{const r=t.getInitializer();if(!r||!o.isCallExpression(r))return;const e=y(r);if(!e)return;const s=P(r,e.receiver);return s?{exportName:t.getName(),handler:s,kind:e.kind}:void 0},g=t=>{const r=[];for(const e of t.getVariableStatements())if(e.isExported())for(const s of e.getDeclarations()){const i=F(s);i&&r.push(i)}return r},f=t=>{if(!o.isPropertyAccessExpression(t))return;const r=t.getName(),e=t.getExpression();if((r==="notify"||r==="push")&&o.isIdentifier(e)&&e.getText()==="ctx")return r;if(r==="push"&&f(e)==="notify")return"push"},S=t=>{if(!o.isPropertyAccessExpression(t))return;const r=t.getName(),e=f(t.getExpression());if(e==="notify"&&A.has(r))return`ctx.notify.${r}`;if(e==="push"&&d.has(r))return`ctx.push.${r}`},N=t=>o.isPropertyAccessExpression(t)?f(t.getExpression())==="push"&&d.has(t.getName()):!1,D=(t,r)=>{const e=[];for(const s of l(r)){const i=t.getSourceFile(s)??t.addSourceFileAtPath(s),n=m(r,s);for(const c of g(i))if(!(c.kind!=="query"&&c.kind!=="mutation"))for(const a of c.handler.getDescendantsOfKind(p.PropertyAccessExpression)){const u=S(a);u!==void 0&&e.push({callee:u,exportName:c.exportName,file:n,kind:c.kind,line:a.getStartLineNumber()})}}return e},b=(t,r)=>{for(const e of l(r)){const s=t.getSourceFile(e)??t.addSourceFileAtPath(e);for(const i of g(s))for(const n of i.handler.getDescendantsOfKind(p.PropertyAccessExpression))if(N(n))return!0}return!1},v=t=>{const r=t.getExportAssignment(i=>!i.isExportEquals());if(!r)return;const e=r.getExpression();if(!o.isIdentifier(e))return e;const s=e.getSymbol()?.getValueDeclaration();return s&&o.isVariableDeclaration(s)?s.getInitializer():e},L=(t,r)=>{const e=h(r,E);if(!x(e))return;const s=t.getSourceFile(e)??t.addSourceFileAtPath(e),i=v(s);let n=!1,c=!1;if(i&&o.isCallExpression(i)){const a=i.getArguments()[0];a&&o.isObjectLiteralExpression(a)&&(n=a.getProperty("webPush")!==void 0,c=a.getProperty("fcm")!==void 0)}return{hasFcm:c,hasWebPush:n,usesPush:b(t,r)}};export{E as NOTIFY_FILENAME,D as discoverNotifyCalls,L as discoverNotifyConfig};
@@ -0,0 +1,3 @@
1
+ import{w as a}from"./emit-Dr6XSLfW.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
+ `,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
+ `;export{m as OPENRPC_VERSION,d as buildOpenRpcDocument,R as emitOpenRpc,O as emitOpenRpcModule};
@@ -0,0 +1 @@
1
+ import{existsSync as d}from"node:fs";import{join as p}from"node:path";import{LunoraError as g}from"@lunora/errors";import{queueDefaultName as l,queueBindingName as f}from"@lunora/queue";import{SyntaxKind as N,Node as u}from"ts-morph";import{diagnosticAt as a}from"./CodegenDiagnosticError-DPezpZTz.mjs";const h="queues.ts",x=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineQueue";for(const e of t.getDeclarations())if(u.isImportSpecifier(e))return e.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/queue"?!1:e.getNameNode().getText()==="defineQueue";return!1},c=(r,t,e)=>{if(u.isStringLiteral(r)||u.isNoSubstitutionTemplateLiteral(r))return r.getLiteralValue();throw a(r,`queue "${t}": \`${e}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},b=(r,t,e)=>{if(u.isNumericLiteral(r))return r.getLiteralValue();throw a(r,`queue "${t}": \`${e}\` must be a static numeric literal — it is deploy configuration codegen writes into wrangler.jsonc`)},w=(r,t)=>{const e=r.getProperty("name");if(!e||!u.isPropertyAssignment(e))return;const i=c(e.getInitializerOrThrow(),t,"name");if(i.length===0)throw a(e,`queue "${t}": \`name\` must be a non-empty string when provided`);return i},y=(r,t)=>{const e=r.getArguments()[0];if(!e||!u.isObjectLiteralExpression(e))throw a(r,`queue "${t}": defineQueue must be passed an inline object literal`);const i={bindingName:f(t),exportName:t,mode:"push",name:w(e,t)??l(t),tuning:{}},o=e.getProperty("mode");if(o&&u.isPropertyAssignment(o)){const n=c(o.getInitializerOrThrow(),t,"mode");if(n!=="push"&&n!=="pull")throw a(o,`queue "${t}": \`mode\` must be "push" or "pull" (got ${JSON.stringify(n)})`);i.mode=n}const s=e.getProperty("deadLetterQueue");s&&u.isPropertyAssignment(s)&&(i.tuning.deadLetterQueue=c(s.getInitializerOrThrow(),t,"deadLetterQueue"));for(const n of["maxBatchSize","maxBatchTimeout","maxRetries","retryDelay"]){const m=e.getProperty(n);m&&u.isPropertyAssignment(m)&&(i.tuning[n]=b(m.getInitializerOrThrow(),t,n))}return i},E=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==N.CallExpression)continue;const o=i,s=o.getExpression();if(!u.isIdentifier(s)||!x(s))continue;const n=e.getNameNode();if(!u.isIdentifier(n))throw a(n,"defineQueue exports must be plain named exports (no destructuring)");t.push(y(o,n.getText()))}return t},q=r=>{const t=new Map,e=new Map;for(const i of r){const o=t.get(i.name);if(o!==void 0)throw new g("DUPLICATE_QUEUE_NAME",`Duplicate queue name "${i.name}": produced by both "${o}" and "${i.exportName}". Deployed queue names must be unique across the project.`,{status:500});t.set(i.name,i.exportName);const s=e.get(i.bindingName);if(s!==void 0)throw new g("DUPLICATE_QUEUE_BINDING",`Duplicate queue binding "${i.bindingName}": produced by both "${s}" and "${i.exportName}". Queue export names must yield unique binding names.`,{status:500});e.set(i.bindingName,i.exportName)}},D=(r,t)=>{const e=p(t,h);if(!d(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),o=E(i);return o.sort((s,n)=>s.exportName.localeCompare(n.exportName)),q(o),o};export{h as QUEUES_FILENAME,D as discoverQueues};
@@ -0,0 +1,3 @@
1
+ import{existsSync as E,readFileSync as ye,mkdirSync as jt,writeFileSync as qt,rmSync as Bt}from"node:fs";import{join as g,dirname as de}from"node:path";import{performance as ge}from"node:perf_hooks";import{LunoraError as q}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as Xe}from"ts-morph";import{lintSchema as Vt}from"./formatAdvisories-DZvv-0MG.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as f,classifyProcedureCall as K,inlineHandler as Ut,procedureHandler as ft,chainUsesWrappedCall as pt,isDatabaseAccessor as k,chainHasStep as Wt,discoverFunctions as Gt}from"./discoverFunctions-BdibLQmc.mjs";import{discoverAgents as _t}from"./AGENTS_FILENAME-BesaDYkL.mjs";import Ht from"./discoverAuthApiCalls-DOfSQqVK.mjs";import{discoverContainers as Qt}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import Xt from"./discoverCrons-B09_uEuL.mjs";import{diagnosticAt as _}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{r as fe,a as Jt,G as Zt,n as Yt,u as es,g as ts,K as ss,o as rs,L as ns,D as is,E as os,_ as as,X as cs,Y as us,z as ls,b as ds,Z as gs}from"./emit-Dr6XSLfW.mjs";import{discoverFlagKeys as fs}from"./FLAGS_FILENAME-DW5oGq1q.mjs";import ps from"./discoverHttpRoutes-BOWz6y_n.mjs";import ms from"./discoverInserts-BtteTyNy.mjs";import xs,{discoverMaskStrategies as hs,discoverMaskMetadata as Es}from"./discoverMaskProcedures-COPmwMBm.mjs";import ys from"./discoverMigrations-iGMlp9YJ.mjs";import{MUTATORS_FILENAME as As,isDefineMutatorCallee as $s,discoverMutators as Ss}from"./MUTATORS_FILENAME-BKKPROzu.mjs";import Ns from"./discoverNondeterministicCalls-Dmgc4QBx.mjs";import{discoverNotifyConfig as vs,discoverNotifyCalls as bs}from"./NOTIFY_FILENAME-C-c7Lg-U.mjs";import Ps from"./discoverQueries-CcfuGKHh.mjs";import{discoverQueues as ws}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Is from"./discoverR2sqlCalls-CjZKvg-N.mjs";import Ls,{discoverRlsMetadata as Os}from"./discoverRlsMetadata-BXmNOgry.mjs";import{discoverSandboxUsage as Fs}from"./discoverSandboxUsage-CDdBqWcM.mjs";import Ds from"./discoverSchema-m2voTncu.mjs";import{secretKindOf as Ts,redact as Cs}from"./redact-CQ8-to6l.mjs";import{discoverShapes as ks}from"./SHAPES_FILENAME-DTkSJSsg.mjs";import Ks from"./discoverStorageRulesMetadata-b71cJJHz.mjs";import{e as Rs}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as Ms}from"./WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{emitApp as zs}from"./emitApp-B671iU7r.mjs";import{buildOpenApiDocument as js,emitOpenApiModule as qs}from"./buildOpenApiDocument-DXX1G3GZ.mjs";import{buildOpenRpcDocument as Bs,emitOpenRpcModule as Vs}from"./OPENRPC_VERSION-DpV3v2W8.mjs";import{buildSchemaSnapshot as Us,serializeSchemaSnapshot as Ws}from"./SCHEMA_SNAPSHOT_VERSION-Bpf1FGMG.mjs";const mt=new Set(["delete","get","head","options","patch","post","put"]),Gs=new Set(["handler","stream"]),_s=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Je=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Hs=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!mt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},Qs=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||mt.has(r.getName()))break;s=r.getExpression()}return Hs(s)},Xs=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(Je.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Je.has(s.getText()))return!0}return!1},Js=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!Gs.has(r.getName()))return;const n=Qs(s);if(!n||!_s.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}},Zs=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Js(n,t);o&&s.push(o)}return s},Ys=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Zs(n,f(t,r)))}return s},Ze=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)},Ye=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)},pe=e=>i.isIdentifier(e)?Ye(e):e.getDescendantsOfKind(u.Identifier).some(t=>Ye(t)),et=(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)},er=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t:void 0},b=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e))return e.getName()},he=e=>i.isIdentifier(e)?Ze(e):e.getDescendantsOfKind(u.Identifier).some(t=>Ze(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},P=e=>{if(he(e))return!0;const t=L(e);return t!==void 0&&he(t)},D=e=>{if(pe(e))return!0;const t=L(e);if(t!==void 0&&pe(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&&pe(n)})},B=(e,t)=>i.isIdentifier(e)?et(e,t):e.getDescendantsOfKind(u.Identifier).some(s=>et(s,t)),tr=(e,t)=>{if(B(e,t))return!0;const s=L(e);if(s!==void 0&&B(s,t))return!0;const r=er(e);if(r!==void 0){const n=L(r);return n!==void 0&&B(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>"},sr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",rr=(e,t)=>{if(!sr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!P(s)||D(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},nr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=rr(r,t);n&&s.push(n)}return s},ir=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...nr(n,f(t,r)))}return s},or=new Set(["generateText","streamText"]),ar=new Set(["messages","prompt","system"]),cr=[{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"]}],ur=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of cr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},lr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=ur(t);if(s!==void 0)return s}},dr=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},gr=e=>{if(he(e))return!0;const t=dr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},fr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!ar.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&gr(s))return!0}return!1},pr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=b(r.getExpression());if(n===void 0||!or.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(b(c.getExpression())==="tool"&&(a=lr(c),a!==void 0))break;a!==void 0&&s.push({exportName:h(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:fr(o)})}return s},mr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...pr(n,f(t,r)))}return s},xr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},hr=(e,t)=>{if(!xr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!P(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},Er=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=hr(r,t);n&&s.push(n)}return s},yr=(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},Ar=/\.check\(|\.meta\(|length|max/iu,$r=/\bv\.any\s*\(/u,Sr=/\bv\.string\s*\(/u,Nr=e=>$r.test(e),vr=e=>Sr.test(e)&&!Ar.test(e),br=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("args");if(!s||!i.isPropertyAssignment(s))return;const r=s.getInitializer();return r&&i.isObjectLiteralExpression(r)?r:void 0},Pr=e=>{const t=[];let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;if(r.getName()==="input"){const n=s.getArguments()[0];n&&i.isObjectLiteralExpression(n)&&t.push(n)}s=r.getExpression()}return t},wr=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();Nr(a)?t.push(c):vr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Ir=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const n=r.receiver?Pr(r.receiver):[br(s)].filter(c=>c!==void 0),{anyArgs:o,unboundedStringArgs:a}=wr(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Lr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Ir(n,t);o&&s.push(o)}return s},Or=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Lr(n,f(t,r)))}return s},I=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},me=e=>e?.getKind()===u.TrueKeyword,Fr=e=>e?.getKind()===u.FalseKeyword,Dr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Tr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),Cr=e=>{const t=I(e,"advanced"),s=I(e,"emailAndPassword"),r=I(e,"session");return{analyzable:!0,disableCsrfCheck:me(I(t,"disableCSRFCheck")),emailPasswordEnabled:me(I(s,"enabled")),requireEmailVerification:me(I(s,"requireEmailVerification")),secureCookiesDisabled:Fr(I(t,"useSecureCookies")),sessionFreshAgeZero:Dr(I(r,"freshAge")),trustedOriginsWildcard:Tr(I(e,"trustedOrigins"))}},kr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Kr=(e,t)=>{if(b(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?Cr(s):kr();return{exportName:h(e),file:t,line:e.getStartLineNumber(),...n}},Rr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Kr(r,t);n&&s.push(n)}return s},Mr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Rr(n,f(t,r)))}return s},zr=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},jr=(e,t,s)=>{const r=zr(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!P(n)||D(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:r}},qr=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=jr(n,t,s);o&&r.push(o)}return r},H=(e,t,s)=>{const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...qr(o,f(t,n),s))}return r},Br=new Set(["content","pdf","scrape","screenshot"]),Vr=(e,t)=>H(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Br}),Ur=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Wr=new Set(["RateLimiter"]),Gr=new Set(["extend"]),xt=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}},tt=e=>e&&i.isObjectLiteralExpression(e)?xt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},_r=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},Hr=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)?_r(e):void 0},Qr=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Hr(t.getBody());return s?xt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Xr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=b(r.getExpression());n!==void 0&&(Ur.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...tt(r.getArguments()[0])}):Gr.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...Qr(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=b(r.getExpression());n===void 0||!Wr.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...tt(r.getArguments()[0])})}return s},Jr=(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},st="ctx.containers.",Zr=e=>{if(!e.startsWith(st))return!1;const t=e.slice(st.length);return t.length>0&&!t.includes(".")},Yr=(e,t)=>H(e,t,{argIndex:0,matchReceiver:Zr,methods:new Set(["get"])}),en=new Set(["allow","deny","setAllowed"]),tn=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())},sn=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!tn(e)))return{detail:"enableInternet: true",exportName:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},rn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!en.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()}},nn=(e,t)=>sn(e,t)??rn(e,t),on=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=nn(r,t);n&&s.push(n)}return s},an=(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},cn="env.ts",ht=new Set(["@lunora/server","lunorash/server"]),un=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ht.has(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},ln=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&&ht.has(r.getModuleSpecifierValue())}return!1},dn=e=>{if(i.isIdentifier(e))return un(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&ln(t)}return!1},gn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!dn(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},fn=(e,t)=>{const s=g(t,cn);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=gn(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},pn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),mn=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return pn.has(s)?s:void 0},xn=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}},hn=(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=mn(a);if(c===void 0)continue;const l=a.getArguments()[0],m=l&&i.isObjectLiteralExpression(l)?xn(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:m.analyzable,emptyKeys:m.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:m.presentKeys})}}return s},En=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),yn=new Set(["dbRateLimit","rateLimit"]),An=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},$n=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Sn=(e,t)=>{const s=b(e.getExpression());if(s===void 0)return;const r=En.get(s);if(r!==void 0)return{callee:s,exportName:h(e),failOpen:An(e.getArguments()[r]),file:t,limitName:yn.has(s)?$n(e):"",line:e.getStartLineNumber()}},Nn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Sn(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(...Nn(n,f(t,r)))}return s},bn=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},Pn=(e,t)=>{const s=Object.fromEntries(fe.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=bn(n);for(const c of fe)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(fe.every(c=>s[c.key]))break}return s},wn=(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"),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")}),In=e=>i.isIdentifier(e)&&e.getText()==="ctx",Ln=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&In(t.getExpression())},On=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},Fn=(e,t)=>{if(!Ln(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=On(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:h(e),file:t,key:n,line:e.getStartLineNumber()}},Dn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Fn(r,t);n&&s.push(n)}return s},Tn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Dn(n,f(t,r)))}return s},Cn=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},kn=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Kn=(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))Cn(a)&&s.push({file:o,indexName:kn(a),line:a.getStartLineNumber()})}return s},Rn=new Set(["delete","get","head","options","patch","post","put"]),Mn=new Set(["handler","stream"]),zn=new Set(["runAction","runMutation"]),jn=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),U=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,rt=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,nt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},it=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(zn.has(a)&&U(c,t))return a;if(jn.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&U(c.getExpression(),t))return`db.${a}`}},ot=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&U(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!U(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},qn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Mn.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(Rn.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},Bn=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=rt(e.getArguments()[0]),l=c&&nt(c,!0);if(!c||l===void 0)return;const m=it(c,l);return m===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ot(c,l),sideEffect:m}}const r=qn(e);if(r===void 0)return;const n=rt(e.getArguments()[0]),o=n&&nt(n,!1);if(!n||o===void 0)return;const a=it(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:ot(n,o),sideEffect:a}},Vn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Bn(r,t);n&&s.push(n)}return s},Un=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Vn(n,f(t,r)))}return s},Wn=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Gn=new Set(["append","set"]),Ae=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",Et=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",at=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>Wn.has(Ae(s.getExpression()))&&B(s,t)),_n=(e,t)=>{if(at(e,t))return!0;const s=L(e);return s!==void 0&&at(s,t)},Ee=(e,t)=>tr(e,t)&&!_n(e,t),Hn=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=L(e);return t!==void 0&&i.isNewExpression(t)&&Ae(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=L(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},$e=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&Ee(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Et(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();Ee(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&&$e(n,t,s)}},yt=(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&&$e(n,"response-init",t)},Qn=(e,t)=>{const s=Ae(e.getExpression());if(s==="Response")yt(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&$e(r,"headers-ctor",t)}},Xn=(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"){yt(e.getArguments()[1],t);return}if(Gn.has(r)&&Hn(n)){const o=e.getArguments()[1];o!==void 0&&Ee(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Et(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},Jn=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))Qn(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))Xn(s,t)},Zn=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=Ut(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 Jn(r,{exportName:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},Yn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...Zn(r,t));return s},ei=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Yn(n,f(t,r)))}return s},At="identity.ts",$t=new Set(["@lunora/server","lunorash/server"]),ti=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return $t.has(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},si=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&&$t.has(r.getModuleSpecifierValue())}return!1},ri=e=>{if(i.isIdentifier(e))return ti(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&si(t)}return!1},ni=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!ri(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},ii=(e,t)=>{const s=g(t,At);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=ni(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},oi=new Set(["auth","context.auth","ctx.auth"]),ai="userId",ci=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},ui=(e,t)=>{const s=g(t,At);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(b(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?ci(o):void 0}},ct=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return oi.has(e.getExpression().getText())?e:void 0},li=e=>{if(i.isPropertyAccessExpression(e)&&ct(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&ct(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},di=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=li(n);o!==void 0&&r.push({declared:o===ai||s.has(o),exportName:h(n),file:t,key:o,line:n.getStartLineNumber()})}return r},gi=(e,t)=>{const s=ui(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(...di(o,f(t,n),s))}return r},fi=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},pi=(e,t)=>{if(b(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=fi(s);if(!(!r||!P(r)||D(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},mi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=pi(r,t);n&&s.push(n)}return s},xi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...mi(n,f(t,r)))}return s},hi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Ei=(e,t)=>H(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:hi}),yi=new Set(["queue","send"]),ut=new Set(["bcc","cc","to"]),Ai=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!yi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},$i=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return ut.has(t.getName())&&P(r)&&!D(r)}if(!i.isPropertyAssignment(t)||!ut.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&P(s)&&!D(s)}):!1,Si=(e,t)=>{const s=Ai(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!$i(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},Ni=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Si(r,t);n&&s.push(n)}return s},vi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ni(n,f(t,r)))}return s},bi=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"},Pi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},wi=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return $s(s.getExpression())?s:void 0},Ii=e=>{const t=wi(e),s=t===void 0?void 0:Pi(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>bi(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},Li=e=>e.getVariableDeclarations().flatMap(t=>Ii(t)),Oi=(e,t)=>{const s=g(t,As);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Li(r)},Fi=new Set(["delete","get","patch"]),Di=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Ti=new Set(["auth","identity","session","user"]),Ci=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),ki=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!k(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Ki=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},Ri=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),Mi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,zi=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>Ri(s.getExpression(),t)&&Mi(s.getThenStatement())),ji=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!Fi.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}},qi=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},Bi=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>qi(s)==="ctx")),Vi=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Ci.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Ui=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(Di.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Ti.has(t.getName()))return!0}return Bi(e)||Vi(e)},Wi=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=ft(s);if(n===void 0)return[];const o=r.receiver!==void 0&&pt(r.receiver,"use","rls"),a=Ui(n),c=new Set,l=[];for(const m of n.getDescendantsOfKind(u.CallExpression)){const y=ki(m);if(y===void 0)continue;const O=Ki(m);if(O===void 0||c.has(O)||!zi(n,O))continue;const R=ji(n,O);R!==void 0&&(c.add(O),l.push({exportName:e.getName(),file:t,line:m.getStartLineNumber(),mentionsOwnership:a,sinkMethod:R,table:y,usesRls:o,visibility:r.visibility}))}return l},Gi=(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(...Wi(c,o))}return s},_i=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Hi=new Set(["insert","insertManyUnsafe","patch","replace"]),Qi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Hi.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},Xi=(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},Ji=(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||!_i.has(a))&&P(c)&&!D(c)&&n.push({exportName:h(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},Zi=(e,t)=>{const s=Qi(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?Xi(r,s).flatMap(n=>Ji(n,s,e,t)):[]},Yi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...Zi(r,t));return s},eo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Yi(n,f(t,r)))}return s},to=e=>{const t=g(e,"package.json");if(!E(t))return new Set;try{const s=JSON.parse(ye(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}},so=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ro=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,no=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ro(t.getInitializer()):void 0},io=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=b(r.getExpression());if(n===void 0||!so.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?no(o):void 0;s.push({callee:n,exportName:h(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}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},ao=new Set(["defineQueue","defineWorkflow"]),co=new Set(["run","runAction","runMutation","runQuery"]),uo=new Set(["api","internal"]),lo=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},go=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},St=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Nt=(e,t)=>e===t||e.startsWith(`${t}.`),vt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},lt=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},bt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>lt(s));return i.isIdentifier(e)&&lt(e)&&t.push(e),t},fo=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},po=e=>{const t=St(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},mo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:po(e),n=new Set,o=a=>vt(a).some(c=>r.some(l=>Nt(c.getText(),l)))?!0:bt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of fo(a))n.add(l)}return{names:n,prefixes:r}},xo=(e,t)=>vt(e).some(s=>t.prefixes.some(r=>Nt(s.getText(),r)))?!0:bt(e).some(s=>t.names.has(s.getText())),ho=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)||!uo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},Eo=(e,t,s)=>{const r=St(e,0);if(r===void 0)return[];const n=mo(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!co.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!xo(l,n))continue;const m=ho(a.getArguments()[0]);m!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:h(a),line:a.getStartLineNumber(),targetExport:m.exportName,targetFile:m.file})}return o},yo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=lo(r);if(n===void 0||!ao.has(n))continue;const o=go(r);o!==void 0&&s.push(...Eo(o,n==="defineQueue"?"queue":"workflow",t))}return s},Ao=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...yo(n,f(t,r)))}return s},dt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},$o=/account|credential|member|passkey|session|user/iu,Pt=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},So=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},No=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},V={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},vo=e=>{const t=No(e),s=t?Pt(t):void 0;if(t&&s==="protectPublic"){const r=So(t);return{...V,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in dt?{...V,[dt[s]]:!0}:V},bo=e=>{const t={...V};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=vo(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},Po=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)&&$o.test(r.getLiteralText()))},wo=new Set(["create","runAfter","runAt","send","sendBatch"]),Io=new Set(["queues","scheduler","workflows"]),Lo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!wo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Io.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},Oo=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"},Fo=new Set(["generateObject","generateText","streamObject","streamText"]),Do=e=>{const t=Pt(e);if(t===void 0||!Fo.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")},To=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"}),Co=e=>{let t=!1,s=!1,r=!1,n=!1;for(const o of e.getDescendantsOfKind(u.CallExpression))if(Po(o)&&(n=!0),Lo(o)&&(t=!0),Oo(o)&&(r=!0),Do(o)&&(s=!0),n&&t&&r&&s)break;return{callsMail:To(e),fanOut:t,unboundedAiGeneration:s,usesInsertManyUnsafe:r,writesUserTable:n}},ko=(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?bo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},{callsMail:o,fanOut:a,unboundedAiGeneration:c,usesInsertManyUnsafe:l,writesUserTable:m}=Co(e);return{callsMail:o,exportName:e.getName(),fanOut:a,file:t,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:m}},Ko=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=ko(n,t);o&&s.push(o)}return s},Ro=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ko(n,f(t,r)))}return s},Mo=new Set(["dbRateLimit","rateLimit"]),zo=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},jo=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},qo=e=>i.isArrowFunction(e)?e.getBody():e,Bo=(e,t)=>{const s=b(e.getExpression());if(s===void 0||!Mo.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=zo(r);if(!n)return;const o=qo(n);if(!(!P(o)||D(o)))return{callee:s,exportName:h(e),file:t,limitName:jo(e),line:e.getStartLineNumber()}},Vo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Bo(r,t);n&&s.push(n)}return s},Uo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Vo(n,f(t,r)))}return s},Wo=new Set(["findFirst","findFirstOrThrow","findMany","get"]),Go=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Wo.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()},_o=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()}},Ho=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},wt=(e,t=!1)=>{const s=Ho(e);if(i.isIdentifier(s)){if(t)return;const r=L(s);return r===void 0?void 0:wt(r,!0)}if(i.isCallExpression(s))return Go(s)??_o(s)},Qo=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},Xo=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=ft(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Wt(r.receiver,"output"),a=r.receiver!==void 0&&pt(r.receiver,"use","mask"),c=new Set,l=[];for(const m of Qo(n)){const y=wt(m);y===void 0||c.has(y)||(c.add(y),l.push({exportName:e.getName(),file:t,line:m.getStartLineNumber(),table:y,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},Jo=(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(...Xo(c,o))}return s},Zo=new Set(["findFirst","findFirstOrThrow","findMany"]),Yo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Zo.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},ea=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},ta=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},sa=(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=Yo(o);if(a===void 0)continue;const c=ea(ta(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},ra=(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(...sa(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}},na=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},ia=(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(na(o))continue;const a=G(o);if(a===void 0)continue;const c=Ts(a);if(c===void 0)continue;const l=o.getStartLineNumber(),m=`${String(l)}:${c}`;n.has(m)||(n.add(m),s.push({file:t,kind:c,line:l,preview:Cs(a)}))}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},aa=new Set(["findFirst","findFirstOrThrow","findMany"]),ca=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!aa.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()}}},ua=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},la=(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=ca(o);if(a===void 0)continue;const c=ua(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),m=!l&&P(c);!l&&!m||n.push({exportName:e.getName(),file:t,fromArgs:m,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},da=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...la(c,o))}return s},ga=new Set(["query","unsafe"]),fa=e=>{if(!i.isPropertyAccessExpression(e)||!ga.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"},pa=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),ma=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",xa=(e,t)=>{if(!fa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!pa(s)))return{exportName:ma(e),file:t,line:s.getStartLineNumber()}},ha=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=xa(r,t);n&&s.push(n)}return s},Ea=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ha(n,f(t,r)))}return s},ya=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Aa=(e,t)=>H(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:ya}),$a=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Sa=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Na=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=Sa(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},va=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=$a.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},ba=(e,t)=>{const s=va(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...Na(e.getArguments()[s.optionsIndex])}},Pa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ba(r,t);n&&s.push(n)}return s},wa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Pa(n,f(t,r)))}return s},Ia=new Set(["when","where"]),xe=new Set(["definePolicy","defineShape"]),La=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return xe.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 xe.has(n)?n:void 0}const s=t.getText();return xe.has(s)?s:void 0},Oa=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,It=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Oa(e))return"empty-object";if(i.isParenthesizedExpression(e))return It(e.getExpression())}},Lt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Ot=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>Lt(t)===e),Ft=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>Lt(t)===e),Fa=e=>{const t=Ot(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Ft(e).length>0},Da=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Ot(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Ft(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},Ta=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Ca=(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)||!Ia.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Fa(a))for(const c of Da(a)){const l=It(c);l!==void 0&&n.push({exportName:Ta(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},ka=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=La(r);n!==void 0&&s.push(...Ca(r,n,t))}return s},Ka=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ka(n,f(t,r)))}return s},Ra=new Set(["query","upsert","upsertMany"]),Ma=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Ra.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},za=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},ja=(e,t)=>{const s=Ma(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=za(r);if(!(!n||!P(n)||D(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},qa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ja(r,t);n&&s.push(n)}return s},Ba=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...qa(n,f(t,r)))}return s},Va=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"},Ua=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Wa=(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(!Va(a))continue;const c=Rs(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:Ua(a)})}}return s},Ga=".lunora-schema.json",$=(e,t)=>{E(e)&&ye(e,"utf8")===t||qt(e,t,"utf8")},v=(e,t)=>{if(t===""){Bt(e,{force:!0});return}$(e,t)},_a=e=>{const t=g(e,"package.json");if(E(t))try{const s=JSON.parse(ye(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Ha=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Qa=e=>{let t=E(e)?e:de(e);for(;t&&t!==de(t);){const s=g(t,"tsconfig.json");if(E(s))return s;t=de(t)}},gt=e=>e.replaceAll("\\","/"),Xa=(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})}},Ja=e=>{const t=Qa(e);return t?new Xe({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xe({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Cc=(e,t)=>{const s=d(t),r=g(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>gt(c))),o=gt(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},kc=e=>{const t=Ha(),s=t?ge.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??Ja(r),a=Ds(o,n,e.projectRoot),c=Gt(o,r),l=ps(o,r),m=ys(o,r),y=ks(o,r),O=Ss(o,r),R=ii(o,r),Se=fn(o,r),S=Ms(o,r),T=ws(o,r),N=_t(o,r);Xa(S,N);const Q=Xt(o,r,S,N),C=Qt(o,r),Ne=e.lint===!1?[]:Vt({adminRoutes:Ys(o,r),aiRawRuns:ir(o,r),aiToolSideEffects:mr(o,r),argumentDerivedFetches:yr(o,r),argumentValidators:Or(o,r),authApiCalls:Ht(o,r),authConfigs:Mr(o,r),browserUrlAccesses:Vr(o,r),configCalls:Jr(o,r),containerKeyAccesses:Yr(o,r),containerOverrides:an(o,r),containers:C,exportSinks:hn(o,r),failOpenGuards:vn(o,r),flagSecurityDefaults:Tn(o,r),geoIndexUsages:Kn(o,r),httpActionGuards:Un(o,r),httpHeaderWrites:ei(o,r),identityClaimReads:gi(o,r),imageDeliveryUrlAccesses:xi(o,r),inserts:ms(o,r),kvKeyAccesses:Ei(o,r),mailRecipientAccesses:vi(o,r),maskProcedures:xs(o,r),maskStrategies:hs(o,r),mutatorWrites:Oi(o,r),nondeterministicCalls:Ns(o,r),normalizeIdAuthorizations:Gi(o,r),notifyCalls:bs(o,r),notifyConfig:vs(o,r),ownerFieldWrites:eo(o,r),unrestrictedWhereBranches:Ka(o,r),paymentWebhooks:oo(o,r),privilegedDispatches:Ao(o,r),procedureProtections:Ro(o,r),queries:Ps(o,r),queues:T,r2sqlCalls:Is(o,r),ratelimitKeySelectors:Uo(o,r),rawRowReturns:Jo(o,r),relationLoads:ra(o,r),rlsProcedures:Ls(o,r),schema:a,secretLiterals:oa(o,r),shapes:y,softDeleteReads:da(o,r),sqlInterpolations:Ea(o,r),storageKeyAccesses:Aa(o,r),storageUploads:wa(o,r),vectorNamespaceAccesses:Ba(o,r),workflowCalls:Wa(o,r),workflows:S,wranglerVariables:e.wranglerVariables}),Dt=Os(o,r),Tt=Es(o,r),X=Ks(o,r),A=Pn(o,r),J=A.ai,Z=A.payments,ve=A.kv,be=A.access,Y=E(g(r,"flags.ts")),Ct=Y?fs(o,r):[],ee=E(g(r,"notify.ts")),te=A.hyperdrive,se=Fs(o,r),kt=se.usesSandboxBrowser||se.usesSandboxContainer,re=A.browser||se.usesSandboxBrowser,ne=A.images,ie=A.analytics,Pe=A.pipelines,oe=A.r2sql,ae=A.x402,w=to(e.projectRoot),M=wn(A,{containerCount:C.length,cronCount:Q.length,dependencies:w,hasPaymentTables:a.tables.some(p=>p.name==="subscriptions")&&a.tables.some(p=>p.name==="events"),queueCount:T.length,storageColumnCount:Object.keys(Jt(a)).length,storageRuleCount:X.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:S.length}),F=w.has("lunorash"),we=t?ge.now():0,Ie=Zt(a,F),Le=Yt({agents:N,functions:c,httpRoutes:l,useUmbrella:F,workflows:S}),Oe=es({agents:N,containers:C,env:Se,hasAccessFacade:be,hasAi:J,hasAnalytics:ie,hasBrowser:re,hasFlags:Y,hasHyperdrive:te,hasImages:ne,hasKv:ve,hasNotify:ee,hasPayments:Z,hasPipelines:Pe,hasR2sql:oe,hasX402:ae,identity:R,queues:T,schema:a,storageRuleBuckets:X.rules.map(p=>p.bucket),useUmbrella:F,workflows:S}),Fe=ts({agents:N,functions:c,migrations:m,mutators:O,shapes:y,useUmbrella:F,usesSandbox:kt}),De=ss({advisories:Ne,agents:N,containers:C,env:Se,flagKeys:Ct,hasAccessFacade:be,hasAi:J,hasAnalytics:ie,hasBrowser:re,hasFlags:Y,hasHyperdrive:te,hasImages:ne,hasKv:ve,hasNotify:ee,hasPayments:Z,hasPipelines:Pe,hasR2sql:oe,hasX402:ae,maskMetadata:Tt,mutators:O,queues:T,rlsMetadata:Dt,schema:a,shapes:y,storageRules:X,studioFeatures:M,useUmbrella:F,workflows:S}),Te=rs(y,w.has("@lunora/db"),F),Ce=ns(C,a.jurisdiction),ke=is(S),Ke=os(N),Re=as(T),Me=cs(Q),ze=us(a.vectorIndexes),z=ls(a,F),je=ds(w.has("@lunora/seed")),j=e.apiSpec??"openapi",ce=j==="openapi"||j==="both",ue=j==="openrpc"||j==="both",qe=zs({emailAgents:N.filter(p=>p.onEmail===!0).map(p=>({bindingName:p.bindingName,exportName:p.exportName})),hasAccess:w.has("@lunora/cloudflare-access"),hasAi:J,hasAnalytics:ie,hasAuth:w.has("@lunora/auth"),hasBrowser:re,hasFramework:w.has("@lunora/astro")||w.has("@lunora/svelte")||w.has("@lunora/vue"),hasGlobal:a.tables.some(p=>p.shardMode==="global"&&p.globalBackend!=="hyperdrive"),hasHyperdrive:te,hasHyperdriveGlobal:a.tables.some(p=>p.shardMode==="global"&&p.globalBackend==="hyperdrive"),hasImages:ne,hasKv:M.kv,hasNotify:ee,hasPayments:Z,hasR2sql:oe,hasQueue:T.some(p=>p.mode==="push"),hasScheduler:M.scheduler,hasStorage:M.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:S.length>0,hasX402:ae,identity:R,jurisdiction:a.jurisdiction,useUmbrella:F,voiceAgents:N.filter(p=>p.voice===!0&&p.voiceBindingName!==void 0).map(p=>({bindingName:p.voiceBindingName,exportName:p.exportName})),wantsOpenApi:ce,wantsOpenRpc:ue}),Be=_a(e.projectRoot),Ve=js({functions:c,httpRoutes:l,version:Be}),Ue=Bs({functions:c,version:Be}),We=`${JSON.stringify(Ve,void 0,2)}
2
+ `,Ge=`${JSON.stringify(Ue,void 0,2)}
3
+ `,_e=qs(Ve),He=Vs(Ue),Qe=Us(a,m.map(p=>p.id)),le=g(r,Ga),Kt=E(le),x=g(r,"_generated");if(e.dryRun||(E(x)||jt(x,{recursive:!0}),$(g(x,"app.ts"),qe),$(g(x,"dataModel.ts"),Ie),$(g(x,"api.ts"),Le),$(g(x,"server.ts"),Oe),$(g(x,"functions.ts"),Fe),$(g(x,"shard.ts"),De),$(g(x,"crons.ts"),Me),$(g(x,"vectors.ts"),ze),$(g(x,"drizzle.global.ts"),z.global),$(g(x,"drizzle.shard.ts"),z.shard),v(g(x,"containers.ts"),Ce),v(g(x,"workflows.ts"),ke),v(g(x,"agents.ts"),Ke),v(g(x,"queues.ts"),Re),v(g(x,"seed.ts"),je),v(g(x,"collections.ts"),Te),v(g(x,"openapi.json"),ce?We:""),v(g(x,"openapi.ts"),ce?_e:""),v(g(x,"openrpc.json"),ue?Ge:""),v(g(x,"openrpc.ts"),ue?He:""),(!Kt||e.updateSchemaBaseline===!0)&&$(le,Ws(Qe))),t){const p=ge.now(),Rt=Math.round(p-s),Mt=Math.round(we-s),zt=Math.round(p-we);console.error(`@lunora/codegen: codegen took ${Rt.toString()}ms (discovery ${Mt.toString()}ms, emit ${zt.toString()}ms)`)}return{advisories:Ne,agents:N,containers:C,cronTriggers:gs(Q),generated:{agents:Ke,api:Le,app:qe,collections:Te,containers:Ce,crons:Me,dataModel:Ie,drizzleGlobal:z.global,drizzleShard:z.shard,functions:Fe,openApi:We,openApiModule:_e,openRpc:Ge,openRpcModule:He,queues:Re,seed:je,server:Oe,shard:De,vectors:ze,workflows:ke},outputDirectory:x,queues:T,schemaSnapshot:Qe,schemaSnapshotPath:le,workflows:S}};export{Ga as SCHEMA_SNAPSHOT_FILENAME,Ja as createCodegenProject,Cc as refreshCodegenProject,kc as runCodegen};
@@ -0,0 +1,15 @@
1
+ import{LunoraError as f}from"@lunora/errors";const l=1,g=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,p=e=>e.kind==="optional"?{kind:e.inner?.kind??"unknown",optional:!0}:{kind:e.kind,optional:!1},b=e=>{const n={};for(const[a,o]of Object.entries(e.shape))n[a]=p(o);const i={};for(const a of e.indexes)i[a.name]={fields:[...a.fields],unique:a.unique??!1};const t={};for(const a of e.relations)t[a.name]={field:a.field,kind:a.kind,table:a.table};return{fields:n,indexes:i,relations:t,shardMode:g(e.shardMode)}},y=e=>{const n={},i=Object.keys(e);i.sort();for(const t of i)n[t]=e[t];return n},q=(e,n)=>{const i={};for(const a of e.tables)i[a.name]=b(a);const t=[...n].sort();return{jurisdiction:e.jurisdiction,migrationIds:t,tables:y(i),version:l}},R=e=>`${JSON.stringify(e,void 0,2)}
2
+ `;class c extends f{constructor(n){super("SCHEMA_SNAPSHOT_PARSE",n,{name:"SchemaSnapshotParseError"})}}const d=e=>typeof e=="object"&&e!==null,v=e=>d(e)&&d(e.fields)&&d(e.indexes)&&d(e.relations)&&typeof e.shardMode=="string",T=e=>{if(e===void 0||e.trim()==="")return;let n;try{n=JSON.parse(e)}catch(i){throw new c(`baseline is not valid JSON: ${i instanceof Error?i.message:String(i)}`)}if(!d(n)||n.version!==l||!d(n.tables))throw new c(`baseline is malformed or written by an incompatible version (expected version ${String(l)})`);for(const[i,t]of Object.entries(n.tables))if(!v(t))throw new c(`baseline table "${i}" has an invalid structure`);return{jurisdiction:typeof n.jurisdiction=="string"?n.jurisdiction:void 0,migrationIds:Array.isArray(n.migrationIds)?n.migrationIds:[],tables:n.tables,version:l}},$=(e,n)=>e.unique===n.unique&&e.fields.length===n.fields.length&&e.fields.every((i,t)=>i===n.fields[t]),k=(e,n,i,t)=>{const a=[];return i.kind!==t.kind&&a.push({severity:"breaking",summary:`field ${e}.${n} changed type: ${i.kind} → ${t.kind} — add a data migration to convert existing values`,type:"changedFieldKind"}),i.optional&&!t.optional?a.push({severity:"breaking",summary:`field ${e}.${n} became required — rows missing it would be invalid; add a data migration to backfill it`,type:"fieldOptionalToRequired"}):!i.optional&&t.optional&&a.push({severity:"safe",summary:`field ${e}.${n} became optional`,type:"fieldRequiredToOptional"}),a},w=(e,n,i)=>i.optional?{severity:"safe",summary:`added optional field ${e}.${n}`,type:"addedOptionalField"}:{severity:"breaking",summary:`added required field ${e}.${n} — existing rows have no value; add a data migration to backfill it`,type:"addedRequiredField"},S=(e,n,i,t)=>{for(const[a,o]of Object.entries(i.fields)){const s=n.fields[a];s===void 0?t.push(w(e,a,o)):t.push(...k(e,a,s,o))}for(const a of Object.keys(n.fields))i.fields[a]===void 0&&t.push({severity:"breaking",summary:`removed field ${e}.${a} — add a data migration if stored data must be cleaned up`,type:"removedField"})},j=(e,n,i,t)=>{for(const[a,o]of Object.entries(i.indexes)){const s=n.indexes[a];if(s===void 0){t.push({severity:"safe",summary:`added index ${a} on ${e}`,type:"addedIndex"});continue}$(s,o)||t.push({severity:"breaking",summary:`index ${a} on ${e} changed shape — a query may have relied on the old index`,type:"changedIndex"})}for(const a of Object.keys(n.indexes))i.indexes[a]===void 0&&t.push({severity:"breaking",summary:`removed index ${a} on ${e} — a query that used \`.withIndex("${a}")\` would break`,type:"removedIndex"})},x=(e,n,i,t)=>{for(const a of Object.keys(i.relations))n.relations[a]===void 0&&t.push({severity:"safe",summary:`added relation ${e}.${a}`,type:"addedRelation"});for(const a of Object.keys(n.relations))i.relations[a]===void 0&&t.push({severity:"breaking",summary:`removed relation ${e}.${a}`,type:"removedRelation"})},O=(e,n,i,t)=>{n.shardMode!==i.shardMode&&t.push({severity:"breaking",summary:`table ${e} changed shard mode: ${n.shardMode} → ${i.shardMode} — its physical storage moves; add a data migration / re-shard plan`,type:"changedShardMode"}),S(e,n,i,t),j(e,n,i,t),x(e,n,i,t)},I=(e,n)=>{const i=[],t=e?.tables??{};for(const[a,o]of Object.entries(n.tables)){const s=t[a];if(s===void 0){i.push({severity:"safe",summary:`added table ${a}`,type:"addedTable"});continue}O(a,s,o,i)}for(const a of Object.keys(t))n.tables[a]===void 0&&i.push({severity:"breaking",summary:`removed table ${a} — add a data migration if its data must be archived/cleaned up`,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==n.jurisdiction){const a=e.jurisdiction??"(none)",o=n.jurisdiction??"(none)";i.push({severity:"breaking",summary:`Durable Object jurisdiction changed from ${a} 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:i}},E=e=>{const{allowDrift:n=!1,baseline:i,current:t}=e,a=I(i,t),o=a.changes.filter(r=>r.severity==="breaking"),s=t.migrationIds.filter(r=>!(i?.migrationIds??[]).includes(r));if(a.changes.length===0||i===void 0)return{blocked:!1,changes:a.changes,newMigrationIds:s,reason:""};if(o.length===0){const r=a.changes.map(m=>` - ${m.summary}`).join(`
3
+ `);return{blocked:!1,changes:a.changes,newMigrationIds:s,reason:`schema drift detected (all additive/safe):
4
+ ${r}`}}const h=o.map(r=>` - ${r.summary}`).join(`
5
+ `);if(s.length>0)return{blocked:!1,changes:a.changes,newMigrationIds:s,reason:`breaking schema drift detected, but ${String(s.length)} new migration(s) were added (${s.join(", ")}):
6
+ ${h}`};const u=`deploy blocked: ${String(o.length)} breaking schema change(s) detected since the last blessed schema baseline — these changes are incompatible with existing data without a migration:
7
+ ${h}
8
+
9
+ To fix:
10
+ • For breaking changes: add a \`defineMigration({ id, table, up })\` in lunora/ for each affected table, then run \`lunora migrate\` (or \`lunora codegen\`) to apply and re-bless the baseline.
11
+ • For backward-compatible changes (e.g. adding an optional field): pass \`--allow-schema-drift\` to skip the block.
12
+ • To accept the new shape without a migration (you know data is compatible): pass \`--update-schema-baseline\`.
13
+ Docs: https://lunora.dev/docs/migrations`;return n?{blocked:!1,changes:a.changes,newMigrationIds:s,reason:`${u}
14
+
15
+ (overridden by --allow-schema-drift)`}:{blocked:!0,changes:a.changes,newMigrationIds:s,reason:u}};export{l as SCHEMA_SNAPSHOT_VERSION,c as SchemaSnapshotParseError,q as buildSchemaSnapshot,I as diffSchemaSnapshots,E as evaluateSchemaDrift,T as parseSchemaSnapshot,R as serializeSchemaSnapshot};
@@ -0,0 +1 @@
1
+ import{existsSync as f}from"node:fs";import{join as l}from"node:path";import{SyntaxKind as c,Node as n}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{d as u}from"./parse-validator-CSDlMEvE.mjs";const m="shapes.ts",p=new Set(["@lunora/server","lunorash/server"]),d=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(n.isImportSpecifier(e))return p.has(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},x=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!n.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(c.ImportDeclaration);return i!==void 0&&p.has(i.getModuleSpecifierValue())}return!1},S=r=>{if(n.isIdentifier(r))return d(r);if(n.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&n.isIdentifier(t)&&x(t)}return!1},h=r=>{const[t]=r.getArguments();if(!t||!n.isObjectLiteralExpression(t))return;const e=t.getProperty("table");if(!e||!n.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&n.isStringLiteral(i)?i.getLiteralValue():void 0},E=r=>{const[t]=r.getArguments();if(!t||!n.isObjectLiteralExpression(t))return{};const e=t.getProperty("args");if(!e||!n.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!n.isObjectLiteralExpression(i)?{}:u(i)},I=r=>{const t=[];for(const e of r.getVariableDeclarations()){if(!e.isExported())continue;const i=e.getInitializer();if(i?.getKind()!==c.CallExpression)continue;const s=i,a=s.getExpression();if(!S(a))continue;const o=e.getNameNode();if(!n.isIdentifier(o))throw g(o,"defineShape exports must be plain named exports (no destructuring)");t.push({args:E(s),exportName:o.getText(),filePath:"shapes",table:h(s)})}return t},L=(r,t)=>{const e=l(t,m);if(!f(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=I(i);return s.sort((a,o)=>a.exportName.localeCompare(o.exportName)),s};export{m as SHAPES_FILENAME,L as discoverShapes};
@@ -0,0 +1 @@
1
+ import{existsSync as m}from"node:fs";import{join as p}from"node:path";import{LunoraError as l}from"@lunora/errors";import{workflowDefaultName as c,workflowClassName as u,workflowBindingName as g}from"@lunora/workflow";import{Node as i,SyntaxKind as d}from"ts-morph";import{diagnosticAt as a}from"./CodegenDiagnosticError-DPezpZTz.mjs";const w="workflows.ts",x=new Set(["do","sleep","sleepUntil","waitForEvent"]),N=o=>{const e=o.getSymbol();if(!e)return o.getText()==="defineWorkflow";for(const t of e.getDeclarations())if(i.isImportSpecifier(t))return t.getImportDeclaration().getModuleSpecifierValue()!=="@lunora/workflow"?!1:t.getNameNode().getText()==="defineWorkflow";return!1},b=(o,e,t)=>{if(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))return o.getLiteralValue();throw a(o,`workflow "${e}": \`${t}\` must be a static string literal — it is deploy configuration codegen writes into wrangler.jsonc`)},E=o=>{const e=o.getExpression();if(!i.isPropertyAccessExpression(e)||!x.has(e.getName()))return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="step"?!0:i.isIdentifier(t)&&t.getText()==="step"},h=o=>{const e=o.getProperty("handler");if(!e)return[];const t=i.isPropertyAssignment(e)?e.getInitializer():e;if(!t)return[];const r=[];for(const n of t.getDescendantsOfKind(d.CallExpression)){if(!E(n))continue;const s=n.getArguments()[0];!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s))||r.push({line:n.getStartLineNumber(),method:n.getExpression().getName(),name:s.getLiteralValue()})}return r},k=(o,e)=>{const t=o.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))throw a(o,`workflow "${e}": defineWorkflow must be passed an inline object literal`);const r={bindingName:g(e),className:u(e),exportName:e,name:c(e),steps:h(t)},n=t.getProperty("name");return n&&i.isPropertyAssignment(n)&&(r.name=b(n.getInitializerOrThrow(),e,"name")),r},S=o=>{let e=o;for(;e&&(i.isAsExpression(e)||i.isSatisfiesExpression(e)||i.isParenthesizedExpression(e));)e=e.getExpression();return e&&i.isCallExpression(e)?e:void 0},y=o=>{const e=[];for(const t of o.getVariableDeclarations()){if(!t.isExported())continue;const r=S(t.getInitializer());if(!r)continue;const n=r.getExpression();if(!i.isIdentifier(n)||!N(n))continue;const s=t.getNameNode();if(!i.isIdentifier(s))throw a(s,"defineWorkflow exports must be plain named exports (no destructuring)");e.push(k(r,s.getText()))}return e},L=o=>{const e=new Map,t=new Map;for(const r of o){const n=e.get(r.name);if(n!==void 0)throw new l("DUPLICATE_WORKFLOW_NAME",`Duplicate workflow name "${r.name}": produced by both "${n}" and "${r.exportName}". Deployed workflow names must be unique across the project.`,{status:500});e.set(r.name,r.exportName);const s=t.get(r.bindingName);if(s!==void 0)throw new l("DUPLICATE_WORKFLOW_BINDING",`Duplicate workflow binding "${r.bindingName}": produced by both "${s}" and "${r.exportName}". Workflow export names must yield unique binding names.`,{status:500});t.set(r.bindingName,r.exportName)}},T=(o,e)=>{const t=p(e,w);if(!m(t))return[];const r=o.getSourceFile(t)??o.addSourceFileAtPath(t),n=y(r);return n.sort((s,f)=>s.exportName.localeCompare(f.exportName)),L(n),n};export{w as WORKFLOWS_FILENAME,T as discoverWorkflows};