@lunora/codegen 1.0.0-alpha.144 → 1.0.0-alpha.145
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +60 -9
- package/dist/index.d.ts +60 -9
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-F2VhjmJG.mjs → GENERATED_HEADER-D4WIATth.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-C30LtXay.mjs → OPENRPC_VERSION-CJwwFY8T.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-D7qF6qrd.mjs → SCHEMA_SNAPSHOT_FILENAME-BtWckBME.mjs} +4 -4
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs +2 -0
- package/dist/packem_shared/SchemaSnapshotParseError-qXCOA7dD.mjs +18 -0
- package/dist/packem_shared/{buildOpenApiDocument-CmLfuJpW.mjs → buildOpenApiDocument-CU1yw_t3.mjs} +1 -1
- package/dist/packem_shared/{emit-EJw8shd_.mjs → emit-Bo3kao_A.mjs} +1 -1
- package/dist/packem_shared/{emitApp-DftAzAA2.mjs → emitApp-CPXPVz9b.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-DLXXalg2.mjs +0 -2
- package/dist/packem_shared/SchemaSnapshotParseError-CvPTjDrT.mjs +0 -16
package/dist/index.d.mts
CHANGED
|
@@ -75,15 +75,38 @@ interface SchemaSnapshot {
|
|
|
75
75
|
* UI-disagrees-with-the-deploy-gate divergence this module exists to prevent.
|
|
76
76
|
*/
|
|
77
77
|
type DriftScope = "schema" | "table";
|
|
78
|
+
/**
|
|
79
|
+
* What actually fixes a change, so a consumer can name the right tool.
|
|
80
|
+
*
|
|
81
|
+
* - `"backfill"` — a `defineMigration` transform rewrites the affected rows.
|
|
82
|
+
* The ONLY value for which a data migration is the answer.
|
|
83
|
+
* - `"rehome"` — the rows' physical storage moves (a different Durable Object,
|
|
84
|
+
* or a different region). The per-shard runner only ever replaces a row inside
|
|
85
|
+
* the shard it was handed, so no transform reaches these; the fix is an
|
|
86
|
+
* export/import round trip, or a revert.
|
|
87
|
+
* - `"code"` — nothing happens to stored data; a query or a call site has to
|
|
88
|
+
* change (a dropped index, a dropped relation).
|
|
89
|
+
* - `"none"` — additive, nothing to do.
|
|
90
|
+
*
|
|
91
|
+
* This lives HERE, next to the change union, for the same reason {@link DriftScope}
|
|
92
|
+
* does: a hand-maintained set of type names in the consumer gives zero
|
|
93
|
+
* compile-time pressure, so a new variant would silently default to whatever the
|
|
94
|
+
* set omits. The deploy gate uses this to decide both what a data migration may
|
|
95
|
+
* excuse and which tables it offers to scaffold one for — a wrong default there
|
|
96
|
+
* sends the operator to a tool that cannot work.
|
|
97
|
+
*/
|
|
98
|
+
type DriftRemediation = "backfill" | "code" | "none" | "rehome";
|
|
78
99
|
/** One classified structural change between two snapshots. */
|
|
79
100
|
interface DriftChange {
|
|
101
|
+
/** What fixes this change — see {@link DriftRemediation}. `"none"` for every `safe` change. */
|
|
102
|
+
remediation: DriftRemediation;
|
|
80
103
|
/**
|
|
81
104
|
* `"table"` means this table's own DDL moved (fields, indexes, shard mode) —
|
|
82
105
|
* a relation whose foreign key lives on the OTHER table stays `"schema"`, so
|
|
83
106
|
* the "changed" signal keeps meaning "this table's shape moved".
|
|
84
107
|
*/
|
|
85
108
|
scope: DriftScope;
|
|
86
|
-
/** `"breaking"` changes need
|
|
109
|
+
/** `"breaking"` changes need attention before deploy; `"safe"` changes are additive. */
|
|
87
110
|
severity: "breaking" | "safe";
|
|
88
111
|
/** Human-readable, actionable description (used in the gate message). */
|
|
89
112
|
summary: string;
|
|
@@ -436,8 +459,10 @@ interface FunctionIR {
|
|
|
436
459
|
/**
|
|
437
460
|
* A `defineMigration({...})` declaration discovered in the user's lunora
|
|
438
461
|
* sources. The emitted `LUNORA_MIGRATIONS` registry keys on {@link MigrationIR.id}; the
|
|
439
|
-
* import wiring needs {@link MigrationIR.exportName}/{@link MigrationIR.filePath}.
|
|
440
|
-
*
|
|
462
|
+
* import wiring needs {@link MigrationIR.exportName}/{@link MigrationIR.filePath}. The runtime object
|
|
463
|
+
* carries the authoritative {@link MigrationIR.table}, but the lifted value is
|
|
464
|
+
* load-bearing at build time: the schema-drift gate matches it against the
|
|
465
|
+
* tables with breaking drift, so a migration left at `""` covers nothing.
|
|
441
466
|
*/
|
|
442
467
|
interface MigrationIR {
|
|
443
468
|
/** Export binding name, used to reference the module member in generated imports. */
|
|
@@ -2546,6 +2571,13 @@ interface CodegenResult {
|
|
|
2546
2571
|
/** WorkflowEntrypoint classes (`_generated/workflows.ts`); `""` (and not written) when no workflows are declared. */
|
|
2547
2572
|
workflows: string;
|
|
2548
2573
|
};
|
|
2574
|
+
/**
|
|
2575
|
+
* Data migrations discovered from `defineMigration` exports under `lunora/`,
|
|
2576
|
+
* each with the table it iterates. The drift gate matches a NEW id against
|
|
2577
|
+
* its table so a backfill only excuses breaking drift on the table it
|
|
2578
|
+
* actually visits. Empty when the project declares none.
|
|
2579
|
+
*/
|
|
2580
|
+
migrations: ReadonlyArray<MigrationIR>;
|
|
2549
2581
|
outputDirectory: string;
|
|
2550
2582
|
/**
|
|
2551
2583
|
* Portability diagnostics for the requested {@link CodegenOptions.target}:
|
|
@@ -3365,11 +3397,15 @@ declare class SchemaSnapshotParseError extends LunoraError {
|
|
|
3365
3397
|
declare const parseSchemaSnapshot: (content: string | undefined) => SchemaSnapshot | undefined;
|
|
3366
3398
|
/** The decision the pre-deploy gate returns. */
|
|
3367
3399
|
interface SchemaDriftDecision {
|
|
3368
|
-
/** True when the deploy must be blocked (breaking drift
|
|
3400
|
+
/** True when the deploy must be blocked (breaking drift no new migration covers, and no override). */
|
|
3369
3401
|
blocked: boolean;
|
|
3370
3402
|
/** Every classified change (both severities), for reporting. */
|
|
3371
3403
|
changes: ReadonlyArray<DriftChange>;
|
|
3372
|
-
/**
|
|
3404
|
+
/**
|
|
3405
|
+
* Migration ids declared now but absent from the baseline. Reported for
|
|
3406
|
+
* context; the gate acts on which of them cover an affected TABLE, not on how
|
|
3407
|
+
* many there are.
|
|
3408
|
+
*/
|
|
3373
3409
|
newMigrationIds: ReadonlyArray<string>;
|
|
3374
3410
|
/**
|
|
3375
3411
|
* A multi-line, actionable explanation. Always present; empty string when
|
|
@@ -3381,9 +3417,22 @@ interface SchemaDriftDecision {
|
|
|
3381
3417
|
* Decide whether breaking schema drift should block a deploy.
|
|
3382
3418
|
*
|
|
3383
3419
|
* Blocks only when the baseline exists (a first-ever capture is never blocking),
|
|
3384
|
-
* there is at least one `breaking` change, no
|
|
3385
|
-
*
|
|
3386
|
-
*
|
|
3420
|
+
* there is at least one `breaking` change, no new migration COVERS it, and the
|
|
3421
|
+
* `allowDrift` override is not set. Safe-only drift passes.
|
|
3422
|
+
*
|
|
3423
|
+
* "Covers" is per-table, not per-run: a new migration excuses breaking drift on
|
|
3424
|
+
* the table it iterates, and nothing else. Counting new ids alone let a backfill
|
|
3425
|
+
* on `messages` unblock a required field added to `users` — the gate reported
|
|
3426
|
+
* "accompanied by a migration" for a change that migration would never visit.
|
|
3427
|
+
* The shard-mode diff cites this block to justify the studio not shipping a
|
|
3428
|
+
* stranded-rows detector (see `shared/schema-snapshot.ts`), and that claim only
|
|
3429
|
+
* holds if an unrelated migration cannot wave it through.
|
|
3430
|
+
*
|
|
3431
|
+
* Only a `"backfill"` change is coverable at all. A `"rehome"` change moves rows
|
|
3432
|
+
* to another Durable Object or region and a `"code"` change breaks a call site;
|
|
3433
|
+
* rewriting rows fixes neither, so a migration must not excuse them however well
|
|
3434
|
+
* its table matches. Those are cleared by fixing the code or accepting the new
|
|
3435
|
+
* shape (`--allow-schema-drift` / `--update-schema-baseline`).
|
|
3387
3436
|
*/
|
|
3388
3437
|
declare const evaluateSchemaDrift: (options: {
|
|
3389
3438
|
allowDrift?: boolean;
|
|
@@ -3391,6 +3440,8 @@ declare const evaluateSchemaDrift: (options: {
|
|
|
3391
3440
|
/** The command printing the remediation, so it names only flags that command accepts. */
|
|
3392
3441
|
command?: string;
|
|
3393
3442
|
current: SchemaSnapshot;
|
|
3443
|
+
/** This run's declared migrations, so a new one is matched to the table it iterates. */
|
|
3444
|
+
migrations: ReadonlyArray<Pick<MigrationIR, "id" | "table">>;
|
|
3394
3445
|
}) => SchemaDriftDecision;
|
|
3395
3446
|
/**
|
|
3396
3447
|
* Convert a {@link SchemaIR} into a synthetic runtime {@link Schema} carrying just
|
|
@@ -3707,4 +3758,4 @@ declare const secretKindOf: (value: string) => string | undefined;
|
|
|
3707
3758
|
/** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
|
|
3708
3759
|
declare const redact: (value: string) => string;
|
|
3709
3760
|
declare const VERSION = "0.0.0";
|
|
3710
|
-
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
|
3761
|
+
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftRemediation, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -75,15 +75,38 @@ interface SchemaSnapshot {
|
|
|
75
75
|
* UI-disagrees-with-the-deploy-gate divergence this module exists to prevent.
|
|
76
76
|
*/
|
|
77
77
|
type DriftScope = "schema" | "table";
|
|
78
|
+
/**
|
|
79
|
+
* What actually fixes a change, so a consumer can name the right tool.
|
|
80
|
+
*
|
|
81
|
+
* - `"backfill"` — a `defineMigration` transform rewrites the affected rows.
|
|
82
|
+
* The ONLY value for which a data migration is the answer.
|
|
83
|
+
* - `"rehome"` — the rows' physical storage moves (a different Durable Object,
|
|
84
|
+
* or a different region). The per-shard runner only ever replaces a row inside
|
|
85
|
+
* the shard it was handed, so no transform reaches these; the fix is an
|
|
86
|
+
* export/import round trip, or a revert.
|
|
87
|
+
* - `"code"` — nothing happens to stored data; a query or a call site has to
|
|
88
|
+
* change (a dropped index, a dropped relation).
|
|
89
|
+
* - `"none"` — additive, nothing to do.
|
|
90
|
+
*
|
|
91
|
+
* This lives HERE, next to the change union, for the same reason {@link DriftScope}
|
|
92
|
+
* does: a hand-maintained set of type names in the consumer gives zero
|
|
93
|
+
* compile-time pressure, so a new variant would silently default to whatever the
|
|
94
|
+
* set omits. The deploy gate uses this to decide both what a data migration may
|
|
95
|
+
* excuse and which tables it offers to scaffold one for — a wrong default there
|
|
96
|
+
* sends the operator to a tool that cannot work.
|
|
97
|
+
*/
|
|
98
|
+
type DriftRemediation = "backfill" | "code" | "none" | "rehome";
|
|
78
99
|
/** One classified structural change between two snapshots. */
|
|
79
100
|
interface DriftChange {
|
|
101
|
+
/** What fixes this change — see {@link DriftRemediation}. `"none"` for every `safe` change. */
|
|
102
|
+
remediation: DriftRemediation;
|
|
80
103
|
/**
|
|
81
104
|
* `"table"` means this table's own DDL moved (fields, indexes, shard mode) —
|
|
82
105
|
* a relation whose foreign key lives on the OTHER table stays `"schema"`, so
|
|
83
106
|
* the "changed" signal keeps meaning "this table's shape moved".
|
|
84
107
|
*/
|
|
85
108
|
scope: DriftScope;
|
|
86
|
-
/** `"breaking"` changes need
|
|
109
|
+
/** `"breaking"` changes need attention before deploy; `"safe"` changes are additive. */
|
|
87
110
|
severity: "breaking" | "safe";
|
|
88
111
|
/** Human-readable, actionable description (used in the gate message). */
|
|
89
112
|
summary: string;
|
|
@@ -436,8 +459,10 @@ interface FunctionIR {
|
|
|
436
459
|
/**
|
|
437
460
|
* A `defineMigration({...})` declaration discovered in the user's lunora
|
|
438
461
|
* sources. The emitted `LUNORA_MIGRATIONS` registry keys on {@link MigrationIR.id}; the
|
|
439
|
-
* import wiring needs {@link MigrationIR.exportName}/{@link MigrationIR.filePath}.
|
|
440
|
-
*
|
|
462
|
+
* import wiring needs {@link MigrationIR.exportName}/{@link MigrationIR.filePath}. The runtime object
|
|
463
|
+
* carries the authoritative {@link MigrationIR.table}, but the lifted value is
|
|
464
|
+
* load-bearing at build time: the schema-drift gate matches it against the
|
|
465
|
+
* tables with breaking drift, so a migration left at `""` covers nothing.
|
|
441
466
|
*/
|
|
442
467
|
interface MigrationIR {
|
|
443
468
|
/** Export binding name, used to reference the module member in generated imports. */
|
|
@@ -2546,6 +2571,13 @@ interface CodegenResult {
|
|
|
2546
2571
|
/** WorkflowEntrypoint classes (`_generated/workflows.ts`); `""` (and not written) when no workflows are declared. */
|
|
2547
2572
|
workflows: string;
|
|
2548
2573
|
};
|
|
2574
|
+
/**
|
|
2575
|
+
* Data migrations discovered from `defineMigration` exports under `lunora/`,
|
|
2576
|
+
* each with the table it iterates. The drift gate matches a NEW id against
|
|
2577
|
+
* its table so a backfill only excuses breaking drift on the table it
|
|
2578
|
+
* actually visits. Empty when the project declares none.
|
|
2579
|
+
*/
|
|
2580
|
+
migrations: ReadonlyArray<MigrationIR>;
|
|
2549
2581
|
outputDirectory: string;
|
|
2550
2582
|
/**
|
|
2551
2583
|
* Portability diagnostics for the requested {@link CodegenOptions.target}:
|
|
@@ -3365,11 +3397,15 @@ declare class SchemaSnapshotParseError extends LunoraError {
|
|
|
3365
3397
|
declare const parseSchemaSnapshot: (content: string | undefined) => SchemaSnapshot | undefined;
|
|
3366
3398
|
/** The decision the pre-deploy gate returns. */
|
|
3367
3399
|
interface SchemaDriftDecision {
|
|
3368
|
-
/** True when the deploy must be blocked (breaking drift
|
|
3400
|
+
/** True when the deploy must be blocked (breaking drift no new migration covers, and no override). */
|
|
3369
3401
|
blocked: boolean;
|
|
3370
3402
|
/** Every classified change (both severities), for reporting. */
|
|
3371
3403
|
changes: ReadonlyArray<DriftChange>;
|
|
3372
|
-
/**
|
|
3404
|
+
/**
|
|
3405
|
+
* Migration ids declared now but absent from the baseline. Reported for
|
|
3406
|
+
* context; the gate acts on which of them cover an affected TABLE, not on how
|
|
3407
|
+
* many there are.
|
|
3408
|
+
*/
|
|
3373
3409
|
newMigrationIds: ReadonlyArray<string>;
|
|
3374
3410
|
/**
|
|
3375
3411
|
* A multi-line, actionable explanation. Always present; empty string when
|
|
@@ -3381,9 +3417,22 @@ interface SchemaDriftDecision {
|
|
|
3381
3417
|
* Decide whether breaking schema drift should block a deploy.
|
|
3382
3418
|
*
|
|
3383
3419
|
* Blocks only when the baseline exists (a first-ever capture is never blocking),
|
|
3384
|
-
* there is at least one `breaking` change, no
|
|
3385
|
-
*
|
|
3386
|
-
*
|
|
3420
|
+
* there is at least one `breaking` change, no new migration COVERS it, and the
|
|
3421
|
+
* `allowDrift` override is not set. Safe-only drift passes.
|
|
3422
|
+
*
|
|
3423
|
+
* "Covers" is per-table, not per-run: a new migration excuses breaking drift on
|
|
3424
|
+
* the table it iterates, and nothing else. Counting new ids alone let a backfill
|
|
3425
|
+
* on `messages` unblock a required field added to `users` — the gate reported
|
|
3426
|
+
* "accompanied by a migration" for a change that migration would never visit.
|
|
3427
|
+
* The shard-mode diff cites this block to justify the studio not shipping a
|
|
3428
|
+
* stranded-rows detector (see `shared/schema-snapshot.ts`), and that claim only
|
|
3429
|
+
* holds if an unrelated migration cannot wave it through.
|
|
3430
|
+
*
|
|
3431
|
+
* Only a `"backfill"` change is coverable at all. A `"rehome"` change moves rows
|
|
3432
|
+
* to another Durable Object or region and a `"code"` change breaks a call site;
|
|
3433
|
+
* rewriting rows fixes neither, so a migration must not excuse them however well
|
|
3434
|
+
* its table matches. Those are cleared by fixing the code or accepting the new
|
|
3435
|
+
* shape (`--allow-schema-drift` / `--update-schema-baseline`).
|
|
3387
3436
|
*/
|
|
3388
3437
|
declare const evaluateSchemaDrift: (options: {
|
|
3389
3438
|
allowDrift?: boolean;
|
|
@@ -3391,6 +3440,8 @@ declare const evaluateSchemaDrift: (options: {
|
|
|
3391
3440
|
/** The command printing the remediation, so it names only flags that command accepts. */
|
|
3392
3441
|
command?: string;
|
|
3393
3442
|
current: SchemaSnapshot;
|
|
3443
|
+
/** This run's declared migrations, so a new one is matched to the table it iterates. */
|
|
3444
|
+
migrations: ReadonlyArray<Pick<MigrationIR, "id" | "table">>;
|
|
3394
3445
|
}) => SchemaDriftDecision;
|
|
3395
3446
|
/**
|
|
3396
3447
|
* Convert a {@link SchemaIR} into a synthetic runtime {@link Schema} carrying just
|
|
@@ -3707,4 +3758,4 @@ declare const secretKindOf: (value: string) => string | undefined;
|
|
|
3707
3758
|
/** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
|
|
3708
3759
|
declare const redact: (value: string) => string;
|
|
3709
3760
|
declare const VERSION = "0.0.0";
|
|
3710
|
-
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
|
3761
|
+
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type ContextPropertyCallIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftRemediation, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcDocument, type OpenRpcEmitInput, type OpenRpcMethod, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, type RuntimeVerb, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SDK_LANGUAGES, SDK_TARGETS, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type SdkFiles, type SdkMethod, type SdkNamespace, type SdkRenderInput, type SdkResult, type SdkTarget, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, describeErrorLevelFindings, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverHyperdriveCalls, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, errorAdvisoryNames, errorPlatformDiagnosticNames, evaluateSchemaDrift, findTsconfig, formatAdvisories, generateSdk, isTypedSchema, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-D1qA0h5m.mjs";import{default as g}from"./packem_shared/discoverAuthApiCalls-C35kkayg.mjs";import{CONTAINERS_FILENAME as R,discoverContainers as C}from"./packem_shared/CONTAINERS_FILENAME-oKaARMoA.mjs";import{default as h}from"./packem_shared/discoverCrons-wXBfQcfn.mjs";import{FLAGS_FILENAME as T,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-BasxlnVS.mjs";import{default as F}from"./packem_shared/discoverFunctions-DglkHRlt.mjs";import{default as P}from"./packem_shared/discoverHttpRoutes-B60GWv_I.mjs";import{default as G}from"./packem_shared/discoverHyperdriveCalls-De_QiFIl.mjs";import{default as b}from"./packem_shared/discoverInserts-C5l2INmE.mjs";import{d as y}from"./packem_shared/index-CCDlo9L7.mjs";import{default as j}from"./packem_shared/discoverMigrations-CWH7T6qz.mjs";import{MUTATORS_FILENAME as V,discoverMutators as z}from"./packem_shared/MUTATORS_FILENAME-BKSzaCkq.mjs";import{default as w}from"./packem_shared/discoverNondeterministicCalls-JsO91i57.mjs";import{NOTIFY_FILENAME as B,discoverNotifyCalls as J,discoverNotifyConfig as Y}from"./packem_shared/NOTIFY_FILENAME-B-eIjru_.mjs";import{default as Z}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as ee}from"./packem_shared/queries-B_xEHIeL.mjs";import{QUEUES_FILENAME as oe,discoverQueues as te}from"./packem_shared/QUEUES_FILENAME-D229WtRm.mjs";import{default as ae}from"./packem_shared/discoverR2sqlCalls-BdkZw-D2.mjs";import{default as me}from"./packem_shared/discoverRlsProcedures-CRshfYZE.mjs";import{default as fe}from"./packem_shared/discoverRlsMetadata-DGUGYgWs.mjs";import{discoverSandboxUsage as ce}from"./packem_shared/discoverSandboxUsage-DdewAOuj.mjs";import{default as le}from"./packem_shared/discoverSchema-CubSTjtY.mjs";import{SHAPES_FILENAME as xe,discoverShapes as Ee}from"./packem_shared/SHAPES_FILENAME-D3N7xcEk.mjs";import{default as ue}from"./packem_shared/discoverStorageRulesMetadata-gyO60A5S.mjs";import{WORKFLOWS_FILENAME as Ne,discoverWorkflows as ge}from"./packem_shared/WORKFLOWS_FILENAME-DRaiCNa6.mjs";import{G as Re,e as Ce,a as Me,b as he,c as _e,d as Te,f as Ie,g as Le,h as Fe,i as De,j as Pe,k as Ue,l as Ge,m as He}from"./packem_shared/emit-Bo3kao_A.mjs";import{emitApp as ke}from"./packem_shared/emitApp-CPXPVz9b.mjs";import{buildOpenApiDocument as We,emitOpenApi as je,emitOpenApiModule as Ke}from"./packem_shared/buildOpenApiDocument-CU1yw_t3.mjs";import{OPENRPC_VERSION as ze,buildOpenRpcDocument as Qe,emitOpenRpc as we,emitOpenRpcModule as qe}from"./packem_shared/OPENRPC_VERSION-CJwwFY8T.mjs";import{DEFAULT_TARGET as Je,platformMatrixIds as Ye,readProjectTarget as Xe,resolveCodegenTarget as Ze}from"./packem_shared/DEFAULT_TARGET-CwB3hjFH.mjs";import{SCHEMA_SNAPSHOT_FILENAME as er,createCodegenProject as rr,findTsconfig as or,refreshCodegenProject as tr,runCodegen as sr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BtWckBME.mjs";import{SchemaSnapshotParseError as ir,buildSchemaSnapshot as mr,evaluateSchemaDrift as dr,parseSchemaSnapshot as fr}from"./packem_shared/SchemaSnapshotParseError-qXCOA7dD.mjs";import{schemaFromIr as cr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as lr,validatorIrToJsonSchema as Sr}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as Er,SDK_TARGETS as Ar,generateSdk as ur}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Nr,secretKindOf as gr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Rr,findSolutionByMessage as Cr}from"@lunora/errors";import{isTypedSchema as hr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,R as CONTAINERS_FILENAME,x as CodegenDiagnosticError,Je as DEFAULT_TARGET,T as FLAGS_FILENAME,Re as GENERATED_HEADER,lr as LUNORA_ERROR_CODES,Rr as LUNORA_SOLUTION_RULES,V as MUTATORS_FILENAME,B as NOTIFY_FILENAME,ze as OPENRPC_VERSION,oe as QUEUES_FILENAME,er as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,Er as SDK_LANGUAGES,Ar as SDK_TARGETS,xe as SHAPES_FILENAME,ir as SchemaSnapshotParseError,e as VERSION,Ne as WORKFLOWS_FILENAME,We as buildOpenApiDocument,Qe as buildOpenRpcDocument,mr as buildSchemaSnapshot,rr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,g as discoverAuthApiCalls,C as discoverContainers,h as discoverCrons,I as discoverFlags,F as discoverFunctions,P as discoverHttpRoutes,G as discoverHyperdriveCalls,b as discoverInserts,y as discoverMaskProcedures,j as discoverMigrations,z as discoverMutators,w as discoverNondeterministicCalls,J as discoverNotifyCalls,Y as discoverNotifyConfig,ee as discoverQueries,te as discoverQueues,ae as discoverR2sqlCalls,fe as discoverRlsMetadata,me as discoverRlsProcedures,ce as discoverSandboxUsage,le as discoverSchema,Ee as discoverShapes,ue as discoverStorageRulesMetadata,ge as discoverWorkflows,Ce as emitAgents,Me as emitApi,ke as emitApp,he as emitCollections,_e as emitContainers,Te as emitCrons,Ie as emitDataModel,Le as emitDrizzleSchema,Fe as emitFunctions,je as emitOpenApi,Ke as emitOpenApiModule,we as emitOpenRpc,qe as emitOpenRpcModule,De as emitServer,Pe as emitShard,Ue as emitVectors,Ge as emitWorkflows,He as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,dr as evaluateSchemaDrift,Cr as findLunoraSolution,or as findTsconfig,m as formatAdvisories,ur as generateSdk,hr as isTypedSchema,d as lintSchema,fr as parseSchemaSnapshot,Ye as platformMatrixIds,Z as readPackageDependencies,Xe as readProjectTarget,Nr as redact,tr as refreshCodegenProject,Ze as resolveCodegenTarget,sr as runCodegen,cr as schemaFromIr,gr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Sr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-Bo3kao_A.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-Bo3kao_A.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.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:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
2
|
`,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{existsSync as b,mkdirSync as ss,readFileSync as At,writeFileSync as ns,rmSync as rs}from"node:fs";import{join as f,dirname as
|
|
1
|
+
import{existsSync as b,mkdirSync as ss,readFileSync as At,writeFileSync as ns,rmSync as rs}from"node:fs";import{join as f,dirname as pe}from"node:path";import{performance as ge}from"node:perf_hooks";import{runAdvisor as is}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Xe}from"ts-morph";import{serializeSchemaSnapshot as os}from"./SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs";import{toAdvisorContext as as}from"./formatAdvisories-CkEu1eye.mjs";import{s as cs}from"./paths-C-9fwEgQ.mjs";import{discoverAgents as ls}from"./AGENTS_FILENAME-D1qA0h5m.mjs";import{discoverContainers as us}from"./CONTAINERS_FILENAME-oKaARMoA.mjs";import{diagnosticAt as ne}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as re}from"./module-specifiers-WF8iAydP.mjs";import{C as me,i as ds,f as fs,n as ps,j as gs,b as ms,c as hs,l as xs,e as Es,o as vs,d as Ss,k as As,g as ys,p as Ns,m as bs,a as Ps,h as Is}from"./emit-Bo3kao_A.mjs";import{l as g,a as E,f as P,p as N,g as yt,j as ve,h as ws,i as D,b as Ze,r as Nt,e as Ts}from"./ast-CjWtsS6S.mjs";import Cs from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as Fs}from"./QUEUES_FILENAME-D229WtRm.mjs";import{discoverSandboxUsage as Os}from"./discoverSandboxUsage-DdewAOuj.mjs";import Rs from"./discoverStorageRulesMetadata-gyO60A5S.mjs";import{discoverWorkflows as Ls}from"./WORKFLOWS_FILENAME-DRaiCNa6.mjs";import{gatePlatformFeatures as Ds,resolveCodegenTarget as ks}from"./DEFAULT_TARGET-CwB3hjFH.mjs";import{i as F,a as K,e as v,r as Ms,b as Ks,s as ie,c as _s,f as zs,d as Us}from"./queries-B_xEHIeL.mjs";import{a as A,c as _,d as bt,e as Bs}from"./classify-procedure-call-AKeIK05y.mjs";import qs from"./discoverAuthApiCalls-C35kkayg.mjs";import $s from"./discoverCrons-wXBfQcfn.mjs";import Je from"./discoverFunctions-DglkHRlt.mjs";import{i as js,r as Vs,e as Ws}from"./unwrap-handler-return-CmIWbykC.mjs";import et from"./discoverHttpRoutes-B60GWv_I.mjs";import Hs from"./discoverHyperdriveCalls-De_QiFIl.mjs";import Gs from"./discoverInserts-C5l2INmE.mjs";import{m as ye,a as Z,s as Pt,d as Ys}from"./index-CCDlo9L7.mjs";import{e as It}from"./exported-procedure-chains-MlZRKqSD.mjs";import Qs from"./discoverMigrations-CWH7T6qz.mjs";import{MUTATORS_FILENAME as Xs,isDefineMutatorCallee as Zs,discoverMutators as tt}from"./MUTATORS_FILENAME-BKSzaCkq.mjs";import Js from"./discoverNondeterministicCalls-JsO91i57.mjs";import{discoverNotifyConfig as en,discoverNotifyCalls as tn}from"./NOTIFY_FILENAME-B-eIjru_.mjs";import sn from"./discoverR2sqlCalls-BdkZw-D2.mjs";import nn from"./discoverRlsProcedures-CRshfYZE.mjs";import rn from"./discoverRlsMetadata-DGUGYgWs.mjs";import on from"./discoverSchema-CubSTjtY.mjs";import{secretKindOf as an,redact as cn,isHeuristicSecretKind as ln,isSecretishName as un}from"./redact-Cy14LEnc.mjs";import{discoverShapes as dn}from"./SHAPES_FILENAME-D3N7xcEk.mjs";import{emitApp as fn}from"./emitApp-CPXPVz9b.mjs";import{buildOpenApiDocument as pn,emitOpenApiModule as gn}from"./buildOpenApiDocument-CU1yw_t3.mjs";import{buildOpenRpcDocument as mn,emitOpenRpcModule as hn}from"./OPENRPC_VERSION-CJwwFY8T.mjs";import{s as xn}from"./parse-validator-Q58kladC.mjs";import{buildSchemaSnapshot as En}from"./SchemaSnapshotParseError-qXCOA7dD.mjs";const vn=e=>{const t=new Map;for(const s of e){const n=cs(s),i=t.get(n);if(i===void 0){t.set(n,s);continue}if(i!==s)throw new L("INTERNAL",`@lunora/codegen: "${i}" and "${s}" both map to the api namespace "${n}" — the generated api.ts would declare "${n}" twice and the dispatch key "${n}:<fn>" would be ambiguous. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}},Sn=e=>{const t=[],s=e.tables.filter(n=>n.shardMode==="global");return s.some(n=>n.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(n=>n.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},An=(e,t)=>{if(t===void 0)return;const s=Sn(e).filter(i=>!t.has(i.name));if(s.length===0)return;const n=s.map(i=>` - ${i.name} — ${i.reason}`).join(`
|
|
2
2
|
`);throw new L("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${n}
|
|
4
4
|
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},yn="env.ts",Nn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return re(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},bn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&re(n.getModuleSpecifierValue())}return!1},Pn=e=>{if(o.isIdentifier(e))return Nn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&bn(t)}return!1},In=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Pn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ne(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},wn=(e,t)=>{const s=f(t,yn);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=In(n);if(i.length!==0){if(i.length>1)throw ne(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Tn=e=>{const t=n=>o.isIdentifier(n)&&n.getText()==="ctx",s=new Set;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression))t(n.getExpression())&&s.add(n.getName());for(const n of e.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getInitializer(),r=n.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(r)))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Cn=(e,t)=>{const s=Object.fromEntries(ge.map(n=>[n.key,!1]));for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Tn(i);for(const c of ge)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(ge.every(c=>s[c.key]))break}return s},wt="identity.ts",Fn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return re(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},On=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&re(n.getModuleSpecifierValue())}return!1},Rn=e=>{if(o.isIdentifier(e))return Fn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&On(t)}return!1},Ln=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Rn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ne(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Dn=(e,t)=>{const s=f(t,wt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Ln(n);if(i.length!==0){if(i.length>1)throw ne(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},kn=e=>o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>(o.isPropertyAssignment(t)||o.isShorthandPropertyAssignment(t))&&t.getName()==="durable"),Mn=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=i.getDescendantsOfKind(l.PropertyAccessExpression).some(r=>r.getName()==="secrets"&&o.isIdentifier(r.getExpression())&&r.getExpression().getText()==="ctx")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>kn(u))})),s.durableStreams&&s.secrets)break}return s},Kn=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new L("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new L("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new L("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},_n=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=Dn(s,t),a=wn(s,t),c=Ls(s,t),u=Fs(s,t),d=ls(s,t);Kn(c,d);const x=us(s,t),y=Rs(s,t),p=Mn(s,t),O=Ds(Cn(s,t),ks(n,e.target),{crossShardFanout:i.tables.some(w=>typeof w.shardMode=="object"),durableStreams:p.durableStreams,globalTables:i.tables.some(w=>w.shardMode==="global"),queues:u.length>0,secrets:p.secrets}),S=O.usage,T=Os(s,t),k=S.browser||T.usesSandboxBrowser,U=Cs(n),R=U??new Set,z=R.has("lunorash");An(i,U);const B=b(f(t,"flags.ts")),W=b(f(t,"notify.ts"));return{agents:d,containers:x,dataModelContent:fs(i),declaredDependencies:U,dependencies:R,env:a,featureUsage:S,hasBrowser:k,hasFlags:B,hasNotify:W,identity:r,platformGate:O,queues:u,serverContent:ds({agents:d,containers:x,env:a,hasAccessFacade:S.access,hasAi:S.ai,hasAnalytics:S.analytics,hasBrowser:k,hasFlags:B,hasHyperdrive:S.hyperdrive,hasImages:S.images,hasKv:S.kv,hasNotify:W,hasPayments:S.payments,hasPipelines:S.pipelines,hasR2sql:S.r2sql,hasX402:S.x402,identity:r,queues:u,schema:i,storageRuleBuckets:y.rules.map(w=>w.bucket),useUmbrella:z,workflows:c}),storageRulesMetadata:y,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer,useUmbrella:z,workflows:c}},Tt=new Set(["delete","get","head","options","patch","post","put"]),zn=new Set(["handler","stream"]),Un=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,st=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Bn=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Tt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},qn=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||Tt.has(n.getName()))break;s=n.getExpression()}return Bn(s)},$n=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(st.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&st.has(s.getText()))return!0}return!1},jn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!zn.has(n.getName()))return;const i=qn(s);if(!i||!Un.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&$n(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Vn=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=jn(i,t);r&&s.push(r)}return s},Wn=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Vn(i,E(t,n)))}return s},Hn=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Gn=(e,t)=>{if(!Hn(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!F(s)||K(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Yn=(e,t)=>P(e,t,Gn),Qn=new Set(["generateText","streamText"]),Xn=new Set(["messages","prompt","system"]),Zn=[{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"]}],Jn=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of Zn)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},er=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Jn(t);if(s!==void 0)return s}},tr=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},sr=e=>{if(Ms(e))return!0;const t=tr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},nr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!Xn.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&sr(s))return!0}return!1},rr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());if(i===void 0||!Qn.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=er(c),a!==void 0))break;a!==void 0&&s.push({exportName:v(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:nr(r)})}return s},ir=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...rr(i,E(t,n)))}return s},or=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},ar=(e,t)=>{if(!or(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!F(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},cr=(e,t)=>P(e,t,ar),Ct=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),lr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer();return!n||!o.isObjectLiteralExpression(n)?{objects:[],opaque:!0}:{objects:[n],opaque:Ct(n)}},ur=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0];r&&o.isObjectLiteralExpression(r)?(t.push(r),s||=Ct(r)):s=!0}n=i.getExpression()}return{objects:t,opaque:s}},Ft=(e,t)=>t?ur(t):lr(e),dr=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),fr=/\.check\(|\.meta\(|length|max/iu,pr=/\bv\.any\s*\(/u,gr=/\bv\.string\s*\(/u,mr=e=>pr.test(e),hr=e=>gr.test(e)&&!fr.test(e),xr=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=r.getText(),c=i.getName();mr(a)?t.push(c):hr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Er=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=_(s);if(n?.visibility!=="public")return;const{objects:i}=Ft(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=xr(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},vr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Er(i,t);r&&s.push(r)}return s},Sr=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vr(i,E(t,n)))}return s},me=e=>e?.getKind()===l.TrueKeyword,Ar=e=>e?.getKind()===l.FalseKeyword,yr=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Nr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),br=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),Pr=e=>e!==void 0&&o.isCallExpression(e)&&Nr.has(A(e.getExpression())??""),Ir=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),wr=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:me(N(t,"disableCSRFCheck")),emailPasswordEnabled:me(N(s,"enabled")),requireEmailVerification:me(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:br(N(e,"plugins"))&&Pr(N(e,"database")),secureCookiesDisabled:Ar(N(t,"useSecureCookies")),sessionFreshAgeZero:yr(N(n,"freshAge")),trustedOriginsWildcard:Ir(N(e,"trustedOrigins"))}},Tr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Cr=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?wr(s):Tr();return{exportName:v(e),file:t,line:e.getStartLineNumber(),...i}},Fr=(e,t)=>P(e,t,Cr),Or=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Rr=(e,t,s)=>{const n=Or(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!F(i)||K(i))&&!(s.requireUnmodifiedReach===!0&&!Ks(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:n}},Lr=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=Rr(i,t,s);r&&n.push(r)}return n},oe=(e,t,s)=>{const n=[];for(const i of g(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Lr(r,E(t,i),s))}return n},Dr=new Set(["content","pdf","scrape","screenshot"]),kr=(e,t)=>oe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Dr}),Mr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Kr=new Set(["RateLimiter"]),_r=new Set(["extend"]),Ot=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},nt=e=>e&&o.isObjectLiteralExpression(e)?Ot(e):{analyzable:!1,presentKeys:[],trueKeys:[]},zr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&o.isObjectLiteralExpression(n)?n:void 0},Ur=e=>{if(o.isObjectLiteralExpression(e))return e;if(o.isParenthesizedExpression(e)){const t=e.getExpression();return o.isObjectLiteralExpression(t)?t:void 0}return o.isBlock(e)?zr(e):void 0},Br=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&Ur(t.getBody());return s?Ot(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},qr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());i!==void 0&&(Mr.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...nt(n.getArguments()[0])}):_r.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Br(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=A(n.getExpression());i===void 0||!Kr.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...nt(n.getArguments()[0])})}return s},$r=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...qr(i,E(t,n)))}return s},rt="ctx.containers.",jr=e=>{if(!e.startsWith(rt))return!1;const t=e.slice(rt.length);return t.length>0&&!t.includes(".")},Vr=(e,t)=>oe(e,t,{argIndex:0,matchReceiver:jr,methods:new Set(["get"])}),Wr=new Set(["allow","deny","setAllowed"]),Hr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Gr=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Hr(e)))return{detail:"enableInternet: true",exportName:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Yr=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Wr.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Qr=(e,t)=>Gr(e,t)??Yr(e,t),Xr=(e,t)=>P(e,t,Qr),Zr=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Jr=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Zr.has(s)?s:void 0},ei=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=n.getName();t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},ti=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=Jr(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?ei(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:r,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},si=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ni=new Set(["dbRateLimit","rateLimit"]),ri=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},ii=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=si.get(s);if(n!==void 0)return{callee:s,exportName:v(e),failOpen:ri(e.getArguments()[n]),file:t,limitName:ni.has(s)?yt(e):"",line:e.getStartLineNumber()}},oi=(e,t)=>P(e,t,ii),ai=new Set(["boolean","number","object","string"]),ci=e=>{const t=e.getName();if(!ai.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ee(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ee(n.getExpression()))return t},li=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=ci(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},ui=(e,t)=>{const s=new Map;for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=li(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},di=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=_(t);if(s?.kind!=="query")return;const n=ws(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},it=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},fi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=it(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=it(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},pi=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=fi(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},gi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=di(i);r&&s.push(...pi(r,t))}return s},mi=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...gi(i,E(t,n)))}return s},hi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ee(t.getExpression())},xi=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Ei=(e,t)=>{if(!hi(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=xi(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:v(e),file:t,key:i,line:e.getStartLineNumber()}},vi=(e,t)=>P(e,t,Ei),Si=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||js(r))return;const a=e.getSourceFile().getFilePath();return Vs(i,e,a)?Ws(i,e,a,0,new Set):r},Ai=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},yi=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ni=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))Ai(a)&&s.push({file:r,indexName:yi(a),line:a.getStartLineNumber()})}return s},V=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,Rt=e=>{const t=e.getArguments()[0],s=V(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&o.isPropertyAssignment(n)?V(n.getInitializer()):void 0},bi=new Set(["delete","get","head","options","patch","post","put"]),Pi=new Set(["handler","stream"]),Ii=new Set(["runAction","runMutation"]),wi=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),J=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,ot=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return o.isIdentifier(n)?n.getText():void 0;if(o.isObjectBindingPattern(n)){for(const i of n.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const a=i.getNameNode();return o.isIdentifier(a)?a.getText():void 0}}},at=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(Ii.has(a)&&J(c,t))return a;if(wi.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&J(c.getExpression(),t))return`db.${a}`}},ct=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&J(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!J(n.getInitializer(),t))){for(const r of i.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},Ti=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Pi.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(bi.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Ci=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=V(e.getArguments()[0]),u=c&&ot(c,!0);if(!c||u===void 0)return;const d=at(c,u);return d===void 0?void 0:{exportName:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ct(c,u),sideEffect:d}}const n=Ti(e);if(n===void 0)return;const i=V(e.getArguments()[0]),r=i&&ot(i,!1);if(!i||r===void 0)return;const a=at(i,r);return a===void 0?void 0:{exportName:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:ct(i,r),sideEffect:a}},Fi=(e,t)=>P(e,t,Ci),Oi=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Ri=new Set(["append","set"]),Lt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",lt=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Oi.has(A(n.getExpression())??"")&&zs(n,t)),Li=(e,t)=>{if(lt(e,t))return!0;const s=ie(e);return s!==void 0&<(s,t)},ve=(e,t)=>_s(e,t)&&!Li(e,t),Di=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ie(e);return t!==void 0&&o.isNewExpression(t)&&A(t.getExpression())==="Headers"},ee=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ie(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},ye=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&ve(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Lt(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();ve(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=ee(n.getExpression());i!==void 0&&ye(i,t,s)}},Dt=(e,t)=>{const s=ee(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=ee(n.getInitializer());i!==void 0&&ye(i,"response-init",t)},ki=(e,t)=>{const s=A(e.getExpression());if(s==="Response")Dt(e.getArguments()[1],t);else if(s==="Headers"){const n=ee(e.getArguments()[0]);n!==void 0&&ye(n,"headers-ctor",t)}},Mi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){Dt(e.getArguments()[1],t);return}if(Ri.has(n)&&Di(i)){const r=e.getArguments()[1];r!==void 0&&ve(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Lt(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Ki=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))ki(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Mi(s,t)},_i=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=V(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return Ki(n,{exportName:v(e),relativePath:t,requestName:r.getText(),rows:a}),a},zi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(..._i(n,t));return s},Ui=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...zi(i,E(t,n)))}return s},Bi=new Set(["auth","context.auth","ctx.auth"]),qi="userId",$i=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},ji=(e,t)=>{const s=f(t,wt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?$i(r):void 0}},ut=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Bi.has(e.getExpression().getText())?e:void 0},Vi=e=>{if(o.isPropertyAccessExpression(e)&&ut(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&ut(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},Wi=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Vi(i);r!==void 0&&n.push({declared:r===qi||s.has(r),exportName:v(i),file:t,key:r,line:i.getStartLineNumber()})}return n},Hi=(e,t)=>{const s=ji(e,t);if(s===void 0)return[];const n=[];for(const i of g(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Wi(r,E(t,i),s))}return n},Gi=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!F(n)||K(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Yi=(e,t)=>P(e,t,Gi),Qi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Xi=(e,t)=>oe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Qi}),Zi=new Set(["queue","send"]),dt=new Set(["bcc","cc","to"]),Ji=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Zi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},eo=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return dt.has(t.getName())&&F(n)&&!K(n)}if(!o.isPropertyAssignment(t)||!dt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&F(s)&&!K(s)}):!1,to=(e,t)=>{const s=Ji(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!eo(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},so=(e,t)=>P(e,t,to),no=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,ro=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?no(e):!0,kt=(e,t=!1)=>{for(const s of e.getProperties()){if(ro(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||kt(n,!0))return!0}return!1},io=(e,t)=>{for(const s of g(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of It(n))for(const r of Ae(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||kt(a)))return!0}}return!1},oo=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Z(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=Z(a);c!==void 0&&s.push({column:c,strategy:Pt(a),table:i})}}return s},ao=(e,t)=>{const s=new Map;for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of It(i))for(const a of Ae(r))for(const c of oo(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},co=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=Z(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=Z(u);if(d===void 0)continue;const x=Pt(u);x!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:x,table:a})}}return i},lo=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?_(s):void 0;return n?.receiver?Ae(n.receiver).flatMap(i=>co(i,e.getName(),t)):[]},uo=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...lo(c,r))}return s},fo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return D(s)},po=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},go=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Zs(s.getExpression())?s:void 0},mo=e=>{const t=go(e),s=t===void 0?void 0:po(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>fo(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},ho=e=>e.getVariableDeclarations().flatMap(t=>mo(t)),xo=(e,t)=>{const s=f(t,Xs);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ho(n)},Eo=new Set(["delete","get","patch"]),vo=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),So=new Set(["auth","identity","session","user"]),Ao=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),yo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!D(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},No=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},bo=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Po=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Io=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>bo(s.getExpression(),t)&&Po(s.getThenStatement())),wo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Eo.has(i))continue;const r=n.getExpression();if(!(D(r)||o.isPropertyAccessExpression(r)&&D(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},To=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},Co=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>To(s)==="ctx")),Fo=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Ao.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Oo=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(vo.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&So.has(t.getName()))return!0}return Co(e)||Fo(e)},Ro=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Rt(s);if(i===void 0)return[];const r=n.receiver!==void 0&&bt(n.receiver,"use","rls"),a=Oo(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const x=yo(d);if(x===void 0)continue;const y=No(d);if(y===void 0||c.has(y)||!Io(i,y))continue;const p=wo(i,y);p!==void 0&&(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:x,usesRls:r,visibility:n.visibility}))}return u},Lo=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ro(c,r))}return s},Do=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ko=new Set(["insert","insertManyUnsafe","patch","replace"]),Mo=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ko.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Ko=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},_o=(e,t,s,n)=>{const i=[];for(const r of e.getProperties()){let a,c;o.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):o.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!Do.has(a))&&F(c)&&!K(c)&&i.push({exportName:v(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return i},zo=(e,t)=>{const s=Mo(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?Ko(n,s).flatMap(i=>_o(i,s,e,t)):[]},Uo=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of zo(i,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Bo=(e,t,s=[])=>{const n=[],i=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of g(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=E(t,r);n.push(...Uo(a,c,u=>i.get(`${c}:${u}`)))}return n},qo=["providerSubscriptionId","state"],$o=["providerEventId","processedAt"],ft=(e,t)=>t.every(s=>s in e.shape),jo=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&ft(t,qo)&&ft(s,$o)},Vo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Wo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Wo(t.getInitializer()):void 0},Go=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Vo.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Ho(n):void 0;return{callee:s,exportName:v(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Yo=(e,t)=>P(e,t,Go),Qo=new Set(["defineQueue","defineWorkflow"]),Xo=new Set(["run","runAction","runMutation","runQuery"]),Zo=new Set(["api","internal"]),Jo=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},ea=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},Mt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},Kt=(e,t)=>e===t||e.startsWith(`${t}.`),_t=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},pt=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},zt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>pt(s));return o.isIdentifier(e)&&pt(e)&&t.push(e),t},ta=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},sa=e=>{const t=Mt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},na=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:sa(e),i=new Set,r=a=>_t(a).some(c=>n.some(u=>Kt(c.getText(),u)))?!0:zt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of ta(a))i.add(u)}return{names:i,prefixes:n}},ra=(e,t)=>_t(e).some(s=>t.prefixes.some(n=>Kt(s.getText(),n)))?!0:zt(e).some(s=>t.names.has(s.getText())),ia=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!Zo.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},oa=(e,t,s)=>{const n=Mt(e,0);if(n===void 0)return[];const i=na(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!Xo.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!ra(u,i))continue;const d=ia(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:v(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},aa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=Jo(n);if(i===void 0||!Qo.has(i))continue;const r=ea(n);r!==void 0&&s.push(...oa(r,i==="defineQueue"?"queue":"workflow",t))}return s},ca=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...aa(i,E(t,n)))}return s},gt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},mt=new Set(["account","credential","member","passkey","session","user"]),la=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ua=e=>{const s=la(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return mt.has(s)||mt.has(n)},da=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},fa=(e,t)=>{const{objects:s,opaque:n}=Ft(e,t);return dr(s).some(i=>da(i))?!0:n?void 0:!1},pa=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},ga=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},X={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},ma=e=>{const t=ga(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=pa(t);return{...X,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in gt?{...X,[gt[s]]:!0}:X},ha=e=>{const t={...X};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=ma(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},xa=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Ea=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!xa.has(t.getName()))return!1;const s=t.getExpression();if(!D(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:ua(i.getLiteralText())},va=new Set(["create","runAfter","runAt","send","sendBatch"]),Sa=new Set(["queues","scheduler","workflows"]),Aa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!va.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Sa.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},ya=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return D(s)},Ut=new Set(["generateObject","generateText","streamObject","streamText"]),Na=e=>{const t=A(e.getExpression());return t!==void 0&&Ut.has(t)},ba=e=>{const t=A(e.getExpression());if(t===void 0||!Ut.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Pa=new Set(["log","span","trace"]),Ia=new Set(["ai"]),wa=new Set(["email","mail"]),Ta=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),he=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Ca=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Fa=new Set(["every","filter","flatMap","forEach","map","some"]),Oa=new Set(["all","allSettled","race"]),Ra=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(Fa.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&Oa.has(n))return t},La=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ca.has(t.getKind())){const s=Ra(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Da=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},ka=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ma=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Ta.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=ka(n);r&&(t=!0,!La(r)&&!Da(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ka=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),ht="lunora-advisor-exempt",_a=/^[\s*/]+/u,za=/[\w-]/u,Ua=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
5
|
+
Install them with your package manager, then re-run codegen.`)},yn="env.ts",Nn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return re(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},bn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&re(n.getModuleSpecifierValue())}return!1},Pn=e=>{if(o.isIdentifier(e))return Nn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&bn(t)}return!1},In=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Pn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ne(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},wn=(e,t)=>{const s=f(t,yn);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=In(n);if(i.length!==0){if(i.length>1)throw ne(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Tn=e=>{const t=n=>o.isIdentifier(n)&&n.getText()==="ctx",s=new Set;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression))t(n.getExpression())&&s.add(n.getName());for(const n of e.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getInitializer(),r=n.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(r)))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Cn=(e,t)=>{const s=Object.fromEntries(me.map(n=>[n.key,!1]));for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Tn(i);for(const c of me)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(me.every(c=>s[c.key]))break}return s},wt="identity.ts",Fn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return re(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},On=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&re(n.getModuleSpecifierValue())}return!1},Rn=e=>{if(o.isIdentifier(e))return Fn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&On(t)}return!1},Ln=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Rn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw ne(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Dn=(e,t)=>{const s=f(t,wt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Ln(n);if(i.length!==0){if(i.length>1)throw ne(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},kn=e=>o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>(o.isPropertyAssignment(t)||o.isShorthandPropertyAssignment(t))&&t.getName()==="durable"),Mn=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=i.getDescendantsOfKind(l.PropertyAccessExpression).some(r=>r.getName()==="secrets"&&o.isIdentifier(r.getExpression())&&r.getExpression().getText()==="ctx")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>kn(u))})),s.durableStreams&&s.secrets)break}return s},Kn=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new L("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new L("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new L("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},_n=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=Dn(s,t),a=wn(s,t),c=Ls(s,t),u=Fs(s,t),d=ls(s,t);Kn(c,d);const x=us(s,t),y=Rs(s,t),p=Mn(s,t),O=Ds(Cn(s,t),ks(n,e.target),{crossShardFanout:i.tables.some(w=>typeof w.shardMode=="object"),durableStreams:p.durableStreams,globalTables:i.tables.some(w=>w.shardMode==="global"),queues:u.length>0,secrets:p.secrets}),S=O.usage,T=Os(s,t),k=S.browser||T.usesSandboxBrowser,U=Cs(n),R=U??new Set,z=R.has("lunorash");An(i,U);const B=b(f(t,"flags.ts")),W=b(f(t,"notify.ts"));return{agents:d,containers:x,dataModelContent:fs(i),declaredDependencies:U,dependencies:R,env:a,featureUsage:S,hasBrowser:k,hasFlags:B,hasNotify:W,identity:r,platformGate:O,queues:u,serverContent:ds({agents:d,containers:x,env:a,hasAccessFacade:S.access,hasAi:S.ai,hasAnalytics:S.analytics,hasBrowser:k,hasFlags:B,hasHyperdrive:S.hyperdrive,hasImages:S.images,hasKv:S.kv,hasNotify:W,hasPayments:S.payments,hasPipelines:S.pipelines,hasR2sql:S.r2sql,hasX402:S.x402,identity:r,queues:u,schema:i,storageRuleBuckets:y.rules.map(w=>w.bucket),useUmbrella:z,workflows:c}),storageRulesMetadata:y,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer,useUmbrella:z,workflows:c}},Tt=new Set(["delete","get","head","options","patch","post","put"]),zn=new Set(["handler","stream"]),Un=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,st=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Bn=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Tt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},qn=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||Tt.has(n.getName()))break;s=n.getExpression()}return Bn(s)},$n=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(st.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&st.has(s.getText()))return!0}return!1},jn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!zn.has(n.getName()))return;const i=qn(s);if(!i||!Un.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&$n(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Vn=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=jn(i,t);r&&s.push(r)}return s},Wn=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Vn(i,E(t,n)))}return s},Hn=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Gn=(e,t)=>{if(!Hn(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!F(s)||K(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Yn=(e,t)=>P(e,t,Gn),Qn=new Set(["generateText","streamText"]),Xn=new Set(["messages","prompt","system"]),Zn=[{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"]}],Jn=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of Zn)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},er=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Jn(t);if(s!==void 0)return s}},tr=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},sr=e=>{if(Ms(e))return!0;const t=tr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},nr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!Xn.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&sr(s))return!0}return!1},rr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());if(i===void 0||!Qn.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(A(c.getExpression())==="tool"&&(a=er(c),a!==void 0))break;a!==void 0&&s.push({exportName:v(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:nr(r)})}return s},ir=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...rr(i,E(t,n)))}return s},or=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},ar=(e,t)=>{if(!or(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!F(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},cr=(e,t)=>P(e,t,ar),Ct=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),lr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer();return!n||!o.isObjectLiteralExpression(n)?{objects:[],opaque:!0}:{objects:[n],opaque:Ct(n)}},ur=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0];r&&o.isObjectLiteralExpression(r)?(t.push(r),s||=Ct(r)):s=!0}n=i.getExpression()}return{objects:t,opaque:s}},Ft=(e,t)=>t?ur(t):lr(e),dr=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),fr=/\.check\(|\.meta\(|length|max/iu,pr=/\bv\.any\s*\(/u,gr=/\bv\.string\s*\(/u,mr=e=>pr.test(e),hr=e=>gr.test(e)&&!fr.test(e),xr=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=r.getText(),c=i.getName();mr(a)?t.push(c):hr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Er=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=_(s);if(n?.visibility!=="public")return;const{objects:i}=Ft(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=xr(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},vr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Er(i,t);r&&s.push(r)}return s},Sr=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vr(i,E(t,n)))}return s},he=e=>e?.getKind()===l.TrueKeyword,Ar=e=>e?.getKind()===l.FalseKeyword,yr=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Nr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),br=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&A(t.getExpression())==="scim"),Pr=e=>e!==void 0&&o.isCallExpression(e)&&Nr.has(A(e.getExpression())??""),Ir=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),wr=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:he(N(t,"disableCSRFCheck")),emailPasswordEnabled:he(N(s,"enabled")),requireEmailVerification:he(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:br(N(e,"plugins"))&&Pr(N(e,"database")),secureCookiesDisabled:Ar(N(t,"useSecureCookies")),sessionFreshAgeZero:yr(N(n,"freshAge")),trustedOriginsWildcard:Ir(N(e,"trustedOrigins"))}},Tr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Cr=(e,t)=>{if(A(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?wr(s):Tr();return{exportName:v(e),file:t,line:e.getStartLineNumber(),...i}},Fr=(e,t)=>P(e,t,Cr),Or=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Rr=(e,t,s)=>{const n=Or(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!F(i)||K(i))&&!(s.requireUnmodifiedReach===!0&&!Ks(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:n}},Lr=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=Rr(i,t,s);r&&n.push(r)}return n},oe=(e,t,s)=>{const n=[];for(const i of g(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Lr(r,E(t,i),s))}return n},Dr=new Set(["content","pdf","scrape","screenshot"]),kr=(e,t)=>oe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Dr}),Mr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Kr=new Set(["RateLimiter"]),_r=new Set(["extend"]),Ot=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},nt=e=>e&&o.isObjectLiteralExpression(e)?Ot(e):{analyzable:!1,presentKeys:[],trueKeys:[]},zr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&o.isObjectLiteralExpression(n)?n:void 0},Ur=e=>{if(o.isObjectLiteralExpression(e))return e;if(o.isParenthesizedExpression(e)){const t=e.getExpression();return o.isObjectLiteralExpression(t)?t:void 0}return o.isBlock(e)?zr(e):void 0},Br=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&Ur(t.getBody());return s?Ot(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},qr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=A(n.getExpression());i!==void 0&&(Mr.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...nt(n.getArguments()[0])}):_r.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Br(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=A(n.getExpression());i===void 0||!Kr.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...nt(n.getArguments()[0])})}return s},$r=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...qr(i,E(t,n)))}return s},rt="ctx.containers.",jr=e=>{if(!e.startsWith(rt))return!1;const t=e.slice(rt.length);return t.length>0&&!t.includes(".")},Vr=(e,t)=>oe(e,t,{argIndex:0,matchReceiver:jr,methods:new Set(["get"])}),Wr=new Set(["allow","deny","setAllowed"]),Hr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Gr=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Hr(e)))return{detail:"enableInternet: true",exportName:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Yr=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Wr.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},Qr=(e,t)=>Gr(e,t)??Yr(e,t),Xr=(e,t)=>P(e,t,Qr),Zr=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Jr=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return Zr.has(s)?s:void 0},ei=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=n.getName();t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},ti=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){const c=Jr(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?ei(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:r,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},si=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ni=new Set(["dbRateLimit","rateLimit"]),ri=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},ii=(e,t)=>{const s=A(e.getExpression());if(s===void 0)return;const n=si.get(s);if(n!==void 0)return{callee:s,exportName:v(e),failOpen:ri(e.getArguments()[n]),file:t,limitName:ni.has(s)?yt(e):"",line:e.getStartLineNumber()}},oi=(e,t)=>P(e,t,ii),ai=new Set(["boolean","number","object","string"]),ci=e=>{const t=e.getName();if(!ai.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&ve(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&ve(n.getExpression()))return t},li=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=ci(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},ui=(e,t)=>{const s=new Map;for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=li(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},di=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=_(t);if(s?.kind!=="query")return;const n=ws(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},it=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},fi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=it(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=it(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},pi=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=fi(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},gi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=di(i);r&&s.push(...pi(r,t))}return s},mi=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...gi(i,E(t,n)))}return s},hi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ve(t.getExpression())},xi=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Ei=(e,t)=>{if(!hi(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=xi(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:v(e),file:t,key:i,line:e.getStartLineNumber()}},vi=(e,t)=>P(e,t,Ei),Si=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||js(r))return;const a=e.getSourceFile().getFilePath();return Vs(i,e,a)?Ws(i,e,a,0,new Set):r},Ai=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},yi=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ni=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))Ai(a)&&s.push({file:r,indexName:yi(a),line:a.getStartLineNumber()})}return s},V=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,Rt=e=>{const t=e.getArguments()[0],s=V(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&o.isPropertyAssignment(n)?V(n.getInitializer()):void 0},bi=new Set(["delete","get","head","options","patch","post","put"]),Pi=new Set(["handler","stream"]),Ii=new Set(["runAction","runMutation"]),wi=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),J=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,ot=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return o.isIdentifier(n)?n.getText():void 0;if(o.isObjectBindingPattern(n)){for(const i of n.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const a=i.getNameNode();return o.isIdentifier(a)?a.getText():void 0}}},at=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(Ii.has(a)&&J(c,t))return a;if(wi.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&J(c.getExpression(),t))return`db.${a}`}},ct=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&J(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!J(n.getInitializer(),t))){for(const r of i.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},Ti=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Pi.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(bi.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Ci=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=V(e.getArguments()[0]),u=c&&ot(c,!0);if(!c||u===void 0)return;const d=at(c,u);return d===void 0?void 0:{exportName:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ct(c,u),sideEffect:d}}const n=Ti(e);if(n===void 0)return;const i=V(e.getArguments()[0]),r=i&&ot(i,!1);if(!i||r===void 0)return;const a=at(i,r);return a===void 0?void 0:{exportName:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:ct(i,r),sideEffect:a}},Fi=(e,t)=>P(e,t,Ci),Oi=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Ri=new Set(["append","set"]),Lt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",lt=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Oi.has(A(n.getExpression())??"")&&zs(n,t)),Li=(e,t)=>{if(lt(e,t))return!0;const s=ie(e);return s!==void 0&<(s,t)},Se=(e,t)=>_s(e,t)&&!Li(e,t),Di=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ie(e);return t!==void 0&&o.isNewExpression(t)&&A(t.getExpression())==="Headers"},ee=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=ie(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},Ne=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Se(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:Lt(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Se(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=ee(n.getExpression());i!==void 0&&Ne(i,t,s)}},Dt=(e,t)=>{const s=ee(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=ee(n.getInitializer());i!==void 0&&Ne(i,"response-init",t)},ki=(e,t)=>{const s=A(e.getExpression());if(s==="Response")Dt(e.getArguments()[1],t);else if(s==="Headers"){const n=ee(e.getArguments()[0]);n!==void 0&&Ne(n,"headers-ctor",t)}},Mi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){Dt(e.getArguments()[1],t);return}if(Ri.has(n)&&Di(i)){const r=e.getArguments()[1];r!==void 0&&Se(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:Lt(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},Ki=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))ki(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Mi(s,t)},_i=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=V(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return Ki(n,{exportName:v(e),relativePath:t,requestName:r.getText(),rows:a}),a},zi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(..._i(n,t));return s},Ui=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...zi(i,E(t,n)))}return s},Bi=new Set(["auth","context.auth","ctx.auth"]),qi="userId",$i=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},ji=(e,t)=>{const s=f(t,wt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(A(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?$i(r):void 0}},ut=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Bi.has(e.getExpression().getText())?e:void 0},Vi=e=>{if(o.isPropertyAccessExpression(e)&&ut(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&ut(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},Wi=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Vi(i);r!==void 0&&n.push({declared:r===qi||s.has(r),exportName:v(i),file:t,key:r,line:i.getStartLineNumber()})}return n},Hi=(e,t)=>{const s=ji(e,t);if(s===void 0)return[];const n=[];for(const i of g(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Wi(r,E(t,i),s))}return n},Gi=(e,t)=>{if(A(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!F(n)||K(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Yi=(e,t)=>P(e,t,Gi),Qi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Xi=(e,t)=>oe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Qi}),Zi=new Set(["queue","send"]),dt=new Set(["bcc","cc","to"]),Ji=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Zi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},eo=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return dt.has(t.getName())&&F(n)&&!K(n)}if(!o.isPropertyAssignment(t)||!dt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&F(s)&&!K(s)}):!1,to=(e,t)=>{const s=Ji(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!eo(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},so=(e,t)=>P(e,t,to),no=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,ro=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?no(e):!0,kt=(e,t=!1)=>{for(const s of e.getProperties()){if(ro(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||kt(n,!0))return!0}return!1},io=(e,t)=>{for(const s of g(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of It(n))for(const r of ye(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||kt(a)))return!0}}return!1},oo=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=Z(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=Z(a);c!==void 0&&s.push({column:c,strategy:Pt(a),table:i})}}return s},ao=(e,t)=>{const s=new Map;for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of It(i))for(const a of ye(r))for(const c of oo(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},co=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=Z(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=Z(u);if(d===void 0)continue;const x=Pt(u);x!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:x,table:a})}}return i},lo=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?_(s):void 0;return n?.receiver?ye(n.receiver).flatMap(i=>co(i,e.getName(),t)):[]},uo=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...lo(c,r))}return s},fo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return D(s)},po=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},go=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Zs(s.getExpression())?s:void 0},mo=e=>{const t=go(e),s=t===void 0?void 0:po(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>fo(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},ho=e=>e.getVariableDeclarations().flatMap(t=>mo(t)),xo=(e,t)=>{const s=f(t,Xs);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ho(n)},Eo=new Set(["delete","get","patch"]),vo=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),So=new Set(["auth","identity","session","user"]),Ao=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),yo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!D(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},No=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},bo=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Po=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Io=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>bo(s.getExpression(),t)&&Po(s.getThenStatement())),wo=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!Eo.has(i))continue;const r=n.getExpression();if(!(D(r)||o.isPropertyAccessExpression(r)&&D(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},To=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},Co=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>To(s)==="ctx")),Fo=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Ao.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Oo=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(vo.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&So.has(t.getName()))return!0}return Co(e)||Fo(e)},Ro=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=Rt(s);if(i===void 0)return[];const r=n.receiver!==void 0&&bt(n.receiver,"use","rls"),a=Oo(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const x=yo(d);if(x===void 0)continue;const y=No(d);if(y===void 0||c.has(y)||!Io(i,y))continue;const p=wo(i,y);p!==void 0&&(c.add(y),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:p,table:x,usesRls:r,visibility:n.visibility}))}return u},Lo=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ro(c,r))}return s},Do=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ko=new Set(["insert","insertManyUnsafe","patch","replace"]),Mo=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!ko.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},Ko=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},_o=(e,t,s,n)=>{const i=[];for(const r of e.getProperties()){let a,c;o.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):o.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!Do.has(a))&&F(c)&&!K(c)&&i.push({exportName:v(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return i},zo=(e,t)=>{const s=Mo(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?Ko(n,s).flatMap(i=>_o(i,s,e,t)):[]},Uo=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of zo(i,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Bo=(e,t,s=[])=>{const n=[],i=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of g(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=E(t,r);n.push(...Uo(a,c,u=>i.get(`${c}:${u}`)))}return n},qo=["providerSubscriptionId","state"],$o=["providerEventId","processedAt"],ft=(e,t)=>t.every(s=>s in e.shape),jo=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&ft(t,qo)&&ft(s,$o)},Vo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Wo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Ho=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Wo(t.getInitializer()):void 0},Go=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Vo.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Ho(n):void 0;return{callee:s,exportName:v(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},Yo=(e,t)=>P(e,t,Go),Qo=new Set(["defineQueue","defineWorkflow"]),Xo=new Set(["run","runAction","runMutation","runQuery"]),Zo=new Set(["api","internal"]),Jo=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},ea=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},Mt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},Kt=(e,t)=>e===t||e.startsWith(`${t}.`),_t=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},pt=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},zt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>pt(s));return o.isIdentifier(e)&&pt(e)&&t.push(e),t},ta=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},sa=e=>{const t=Mt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},na=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:sa(e),i=new Set,r=a=>_t(a).some(c=>n.some(u=>Kt(c.getText(),u)))?!0:zt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of ta(a))i.add(u)}return{names:i,prefixes:n}},ra=(e,t)=>_t(e).some(s=>t.prefixes.some(n=>Kt(s.getText(),n)))?!0:zt(e).some(s=>t.names.has(s.getText())),ia=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!Zo.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},oa=(e,t,s)=>{const n=Mt(e,0);if(n===void 0)return[];const i=na(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!Xo.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!ra(u,i))continue;const d=ia(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:v(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},aa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=Jo(n);if(i===void 0||!Qo.has(i))continue;const r=ea(n);r!==void 0&&s.push(...oa(r,i==="defineQueue"?"queue":"workflow",t))}return s},ca=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...aa(i,E(t,n)))}return s},gt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},mt=new Set(["account","credential","member","passkey","session","user"]),la=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ua=e=>{const s=la(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return mt.has(s)||mt.has(n)},da=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},fa=(e,t)=>{const{objects:s,opaque:n}=Ft(e,t);return dr(s).some(i=>da(i))?!0:n?void 0:!1},pa=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},ga=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},X={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},ma=e=>{const t=ga(e),s=t?A(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=pa(t);return{...X,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in gt?{...X,[gt[s]]:!0}:X},ha=e=>{const t={...X};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=ma(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},xa=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Ea=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!xa.has(t.getName()))return!1;const s=t.getExpression();if(!D(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:ua(i.getLiteralText())},va=new Set(["create","runAfter","runAt","send","sendBatch"]),Sa=new Set(["queues","scheduler","workflows"]),Aa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!va.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Sa.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},ya=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return D(s)},Ut=new Set(["generateObject","generateText","streamObject","streamText"]),Na=e=>{const t=A(e.getExpression());return t!==void 0&&Ut.has(t)},ba=e=>{const t=A(e.getExpression());if(t===void 0||!Ut.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Pa=new Set(["log","span","trace"]),Ia=new Set(["ai"]),wa=new Set(["email","mail"]),Ta=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),xe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Ca=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),Fa=new Set(["every","filter","flatMap","forEach","map","some"]),Oa=new Set(["all","allSettled","race"]),Ra=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(Fa.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&Oa.has(n))return t},La=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Ca.has(t.getKind())){const s=Ra(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},Da=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},ka=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ma=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!Ta.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=ka(n);r&&(t=!0,!La(r)&&!Da(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},Ka=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),ht="lunora-advisor-exempt",_a=/^[\s*/]+/u,za=/[\w-]/u,Ua=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
6
|
`);for(const n of s.split(`
|
|
7
|
-
`)){const i=n.replace(_a,"");if(!i.startsWith(ht))continue;const r=i.slice(ht.length);if(za.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ba=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},qa=(e,t)=>{const s=Ba(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},$a=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Ea(u)&&(r=!0),Aa(u)&&(t=!0),ya(u)&&(i=!0),Na(u)&&(s=!0),ba(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ma(e);return{callsMail:he(e,wa),emitsEvent:he(e,Pa),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||he(e,Ia),throwsBareError:Ka(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},ja=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=_(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?ha(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=qa(e,s);return{...r?$a(r):{},...Ua(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:fa(s,n.receiver),kind:n.kind,visibility:n.visibility}},Va=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=ja(i,t);r&&s.push(r)}return s},Wa=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Va(i,E(t,n)))}return s},Ha=new Set(["dbRateLimit","rateLimit"]),Ga=e=>o.isArrowFunction(e)?e.getBody():e,Ya=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Ha.has(s))return;const n=e.getArguments()[2];if(!n)return;const i=N(n,"key");if(!i)return;const r=Ga(i);if(!(!F(r)||K(r)))return{callee:s,exportName:v(e),file:t,limitName:yt(e),line:e.getStartLineNumber()}},Qa=(e,t)=>P(e,t,Ya),Xa=new Set(["findFirst","findFirstOrThrow","findMany","get"]),Za=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Xa.has(t.getName()))return;const s=t.getExpression();if(D(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&D(s.getExpression()))return s.getName()},Ja=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&D(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},ec=e=>{let t=Ze(e)??e;for(;o.isAwaitExpression(t);)t=Ze(t.getExpression())??t.getExpression();return t},Bt=(e,t=!1)=>{const s=ec(e);if(o.isIdentifier(s)){if(t)return;const n=ie(s);return n===void 0?void 0:Bt(n,!0)}if(o.isCallExpression(s))return Za(s)??Ja(s)},tc=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},sc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query")return[];const i=Rt(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Bs(n.receiver,"output"),a=n.receiver!==void 0&&bt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of tc(i)){const x=Bt(d);x===void 0||c.has(x)||(c.add(x),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:x,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},nc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...sc(c,r))}return s},rc=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},ic=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?_(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Nt(r);if(a===void 0)continue;const c=rc(N(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},oc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ic(c,r))}return s},te=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=te(e.getLeft()),s=te(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},ac=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&te(t)!==void 0},cc=/(?:^|\/)__tests__\//u,lc=/\.(?:spec|test)$/u,uc=e=>cc.test(e)||lc.test(e),dc=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},fc=(e,t,s)=>ln(e)?!uc(s)&&un(dc(t)):!0,pc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(ac(r))continue;const a=te(r);if(a===void 0)continue;const c=an(a);if(c===void 0||!fc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:cn(a)}))}return s},gc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pc(i,E(t,n)))}return s},mc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?_(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Nt(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&F(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},hc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...mc(c,r))}return s},xc=new Set(["query","unsafe"]),Ec=e=>{if(!o.isPropertyAccessExpression(e)||!xc.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},vc=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Sc=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Ac=(e,t)=>{if(!Ec(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!vc(s)))return{exportName:Sc(e),file:t,line:s.getStartLineNumber()}},yc=(e,t)=>P(e,t,Ac),Nc=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],bc=e=>{for(const[t,s]of Nc)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Pc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=bc(a);c!==void 0&&s.push({file:E(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Ic=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),wc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return oe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Ic,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Tc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Cc=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Fc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),r==="expiresInSeconds"&&(s=Cc(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Oc=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Tc.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Rc=(e,t)=>{const s=Oc(e.getExpression());if(s!==void 0)return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...Fc(e.getArguments()[s.optionsIndex])}},Lc=(e,t)=>P(e,t,Rc),Dc=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),kc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),Ne=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&kc.has(s)?s:void 0},qt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},$t={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},Mc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},be=(e,t,s,n,i)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${i.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),Kc=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(s.has(`${t}:${a}`)||!qt(r))continue;const c=Ne(r);c!==void 0&&n.push(be(t,a,c,r.getStartLineNumber(),$t))}return n},_c=(e,t,s)=>{if(s.has(`${t}:default`))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ne(i.getExpression());r!==void 0&&n.push(be(t,"default",r,i.getStartLineNumber(),$t))}return n},zc=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(s.has(`${t}:${a}`))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!qt(c))continue;const u=Ne(c);u!==void 0&&n.push(be(t,a,u,r.getStartLineNumber(),Mc))}return n},Uc=(e,t,s)=>[...Kc(e,t,s),..._c(e,t,s),...zc(e,t,s)],Bc=(e,t,s)=>{const n=new Set(s.map(r=>`${r.filePath}:${r.exportName}`)),i=[];for(const r of g(t)){const a=e.getSourceFile(r);a!==void 0&&i.push(...Uc(a,E(t,r),n))}return i.toSorted((r,a)=>r.cacheKey.localeCompare(a.cacheKey))},qc=new Set(["when","where"]),xe=new Set(["definePolicy","defineShape"]),$c=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return xe.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return xe.has(i)?i:void 0}const s=t.getText();return xe.has(s)?s:void 0},jc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,jt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(jc(e))return"empty-object";if(o.isParenthesizedExpression(e))return jt(e.getExpression())}},Pe=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Vc=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Pe(t)===e),Vt=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Pe(t)===e),Wc=e=>{const t=Vc(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Vt(e).length>0},Hc=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>Pe(t)===e),Se=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",Gc=(e,t)=>Se(e)||Se(t),Yc=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),xt=e=>!Se(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Qc=(e,t,s)=>{const n=Yc.get(e);if(n!==void 0)return Gc(t,s)?n==="positive"?"negative":"positive":xt(t)||xt(s)?void 0:n},j=e=>{if(o.isParenthesizedExpression(e))return j(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Qc(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=j(e.getLeft()),i=j(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},Et=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},Xc=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Zc=e=>o.isReturnStatement(e)?e.getExpression()??e:e,Jc=e=>{const t=[];for(const s of Vt(e)){const n=j(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Hc(e)){const n=j(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Et(s.getThenStatement()):Et(s.getElseStatement())??Xc(s);i!==void 0&&t.push(Zc(i))}return t},el=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},tl=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!qc.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&Wc(a))for(const c of Jc(a)){const u=jt(c);u!==void 0&&i.push({exportName:el(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return i},sl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=$c(n);i!==void 0&&s.push(...tl(n,i,t))}return s},nl=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sl(i,E(t,n)))}return s},rl=new Set(["query","upsert","upsertMany"]),il=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(rl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},ol=(e,t)=>{const s=il(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=N(n,"namespace");if(!(!i||!F(i)||K(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},al=(e,t)=>P(e,t,ol),cl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},ll=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ul=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!cl(a))continue;const c=Ts(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:ll(a)})}}return s},dl=".lunora-schema.json",I=(e,t)=>{b(e)&&At(e,"utf8")===t||ns(e,t,"utf8")},C=(e,t)=>{if(t===""){rs(e,{force:!0});return}I(e,t)},fl=e=>{const t=f(e,"package.json");if(b(t))try{const s=JSON.parse(At(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},pl=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},gl=e=>{let t=b(e)?e:fe(e);for(;t&&t!==fe(t);){const s=f(t,"tsconfig.json");if(b(s))return s;t=fe(t)}},vt=e=>e.replaceAll("\\","/"),ml=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},se=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},St=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,hl=8,xl=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:x}=e;let y=Je(a,i),p=tt(a,i),O=et(a,i);vn([...y,...p].map(S=>S.filePath));for(let S=1;;S+=1){const T=Ps({agents:t,functions:y,httpRoutes:O,mutators:p,useUmbrella:d,workflows:x}),k=Is({agents:t,functions:y,migrations:r,mutators:p,shapes:c,useUmbrella:d,usesSandbox:u});if(S>=hl||St(a,s,T)&&St(a,n,k))return{apiContent:T,functions:y,functionsContent:k,httpRoutes:O,mutators:p};se(a,s,T),se(a,n,k),y=Je(a,i),p=tt(a,i),O=et(a,i)}},El=e=>{const t=gl(e);return t?new Xe({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xe({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},fu=(e,t)=>{const s=g(t),n=f(t,"schema.ts");b(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>vt(c))),r=vt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},pu=e=>{const t=pl(),s=t?pe.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),i=f(n,"schema.ts");if(!b(i))throw new L("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??El(n);xn(Si);const a=on(r,i,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:x,env:y,featureUsage:p,hasBrowser:O,hasFlags:S,hasNotify:T,identity:k,platformGate:U,queues:R,serverContent:z,storageRulesMetadata:B,usesSandbox:W,useUmbrella:w,workflows:M}=_n({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),m=f(n,"_generated"),Ie=f(m,"dataModel.ts"),we=f(m,"server.ts"),Wt=f(m,"api.ts"),Ht=f(m,"functions.ts");se(r,Ie,d),se(r,we,z);const Te=Qs(r,n),q=dn(r,n),{apiContent:Ce,functions:$,functionsContent:Fe,httpRoutes:Gt,mutators:Yt}=xl({agents:c,apiPath:Wt,generatedFunctionsPath:Ht,lunoraDirectory:n,migrations:Te,project:r,shapes:q,useUmbrella:w,usesSandbox:W,workflows:M}),ae=$s(r,n,M,c),H=e.lint===!1?void 0:as({adminRoutes:Wn(r,n),aiRawRuns:Yn(r,n),aiToolSideEffects:ir(r,n),argumentDerivedFetches:cr(r,n),argumentValidators:Sr(r,n),authApiCalls:qs(r,n),authConfigs:Fr(r,n),browserUrlAccesses:kr(r,n),configCalls:$r(r,n),containerKeyAccesses:Vr(r,n),containerOverrides:Xr(r,n),containers:u,exportSinks:ti(r,n),staleMigrationImports:Pc(r,n),failOpenGuards:oi(r,n),flagReads:mi(r,n),flagSecurityDefaults:vi(r,n),geoIndexUsages:Ni(r,n),httpActionGuards:Fi(r,n),httpHeaderWrites:Ui(r,n),hyperdriveCalls:Hs(r,n),identityClaimReads:Hi(r,n),imageDeliveryUrlAccesses:Yi(r,n),inserts:Gs(r,n),kvKeyAccesses:Xi(r,n),mailRecipientAccesses:so(r,n),maskProcedures:Ys(r,n),maskStrategies:uo(r,n),mutatorWrites:xo(r,n),nondeterministicCalls:Js(r,n),normalizeIdAuthorizations:Lo(r,n),notifyCalls:tn(r,n),notifyConfig:en(r,n),ownerFieldWrites:Bo(r,n,$),unrestrictedWhereBranches:nl(r,n),paymentWebhooks:Yo(r,n),privilegedDispatches:ca(r,n),procedureProtections:Wa(r,n),queries:Us(r,n),queues:R,r2sqlCalls:sn(r,n),ratelimitKeySelectors:Qa(r,n),rawRowReturns:nc(r,n),relationLoads:oc(r,n),rlsProcedures:nn(r,n),schema:a,secretLiterals:gc(r,n),shapes:q,softDeleteReads:hc(r,n),sqlInterpolations:yc(r,n),storageKeyAccesses:wc(r,n,$),storageUploads:Lc(r,n),vectorNamespaceAccesses:al(r,n),workflowCalls:ul(r,n),workflows:M,wranglerVariables:e.wranglerVariables}),Oe=H===void 0?[]:[...is(H,{source:"static"}),...Bc(r,n,$)],Qt=rn(r,n),Re=ao(r,n);ml(q,Re,io(r,n));const Xt=S?ui(r,n):[],G=Dc(p,{containerCount:u.length,cronCount:ae.length,dependencies:x,hasPaymentTables:jo(a.tables),queueCount:R.length,storageColumnCount:Object.keys(ps(a)).length,storageRuleCount:B.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:M.length}),Le=t?pe.now():0,ce=En(a,Te.map(h=>h.id)),De=gs({advisories:Oe,advisorProcedures:H?.procedureProtections??[],agents:c,containers:u,env:y,flagKeys:Xt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:O,hasFlags:S,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:T,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:Re,mutators:Yt,queues:R,rlsMetadata:Qt,schema:a,schemaSnapshot:ce,shapes:q,storageRules:B,studioFeatures:G,useUmbrella:w,workflows:M}),ke=ms(q,x.has("@lunora/db"),w),Me=hs(u,a.jurisdiction),Ke=xs(M),_e=Es(c),ze=vs(R),Ue=Ss(ae),Be=As(a.vectorIndexes),Y=ys(a,w),qe=Ns(x.has("@lunora/seed")),Q=e.apiSpec??"openapi",le=Q==="openapi"||Q==="both",ue=Q==="openrpc"||Q==="both",$e=fn({emailAgents:c.filter(h=>h.onEmail===!0).map(h=>({bindingName:h.bindingName,exportName:h.exportName})),hasAccess:x.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:x.has("@lunora/auth"),hasBrowser:O,hasFramework:x.has("@lunora/astro")||x.has("@lunora/svelte")||x.has("@lunora/vue"),hasGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:p.kv,hasKvIntrospector:G.kv,hasNotify:T,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:R.some(h=>h.mode==="push"),hasScheduler:G.scheduler,hasStorage:G.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:M.length>0,hasX402:p.x402,identity:k,jurisdiction:a.jurisdiction,tableNames:a.tables.map(h=>h.name),useUmbrella:w,voiceAgents:c.filter(h=>h.voice===!0&&h.voiceBindingName!==void 0).map(h=>({bindingName:h.voiceBindingName,exportName:h.exportName})),wantsOpenApi:le,wantsOpenRpc:ue}),je=fl(e.projectRoot),Ve=pn({functions:$,httpRoutes:Gt,version:je}),We=mn({functions:$,version:je}),He=`${JSON.stringify(Ve,void 0,2)}
|
|
7
|
+
`)){const i=n.replace(_a,"");if(!i.startsWith(ht))continue;const r=i.slice(ht.length);if(za.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Ba=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},qa=(e,t)=>{const s=Ba(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},$a=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Ea(u)&&(r=!0),Aa(u)&&(t=!0),ya(u)&&(i=!0),Na(u)&&(s=!0),ba(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ma(e);return{callsMail:xe(e,wa),emitsEvent:xe(e,Pa),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||xe(e,Ia),throwsBareError:Ka(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},ja=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=_(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?ha(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=qa(e,s);return{...r?$a(r):{},...Ua(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:fa(s,n.receiver),kind:n.kind,visibility:n.visibility}},Va=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=ja(i,t);r&&s.push(r)}return s},Wa=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Va(i,E(t,n)))}return s},Ha=new Set(["dbRateLimit","rateLimit"]),Ga=e=>o.isArrowFunction(e)?e.getBody():e,Ya=(e,t)=>{const s=A(e.getExpression());if(s===void 0||!Ha.has(s))return;const n=e.getArguments()[2];if(!n)return;const i=N(n,"key");if(!i)return;const r=Ga(i);if(!(!F(r)||K(r)))return{callee:s,exportName:v(e),file:t,limitName:yt(e),line:e.getStartLineNumber()}},Qa=(e,t)=>P(e,t,Ya),Xa=new Set(["findFirst","findFirstOrThrow","findMany","get"]),Za=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Xa.has(t.getName()))return;const s=t.getExpression();if(D(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&D(s.getExpression()))return s.getName()},Ja=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&D(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},ec=e=>{let t=Ze(e)??e;for(;o.isAwaitExpression(t);)t=Ze(t.getExpression())??t.getExpression();return t},Bt=(e,t=!1)=>{const s=ec(e);if(o.isIdentifier(s)){if(t)return;const n=ie(s);return n===void 0?void 0:Bt(n,!0)}if(o.isCallExpression(s))return Za(s)??Ja(s)},tc=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},sc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=_(s);if(n?.kind!=="query")return[];const i=Rt(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Bs(n.receiver,"output"),a=n.receiver!==void 0&&bt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of tc(i)){const x=Bt(d);x===void 0||c.has(x)||(c.add(x),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:x,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},nc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...sc(c,r))}return s},rc=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},ic=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?_(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Nt(r);if(a===void 0)continue;const c=rc(N(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},oc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ic(c,r))}return s},te=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=te(e.getLeft()),s=te(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},ac=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&te(t)!==void 0},cc=/(?:^|\/)__tests__\//u,lc=/\.(?:spec|test)$/u,uc=e=>cc.test(e)||lc.test(e),dc=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},fc=(e,t,s)=>ln(e)?!uc(s)&&un(dc(t)):!0,pc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(ac(r))continue;const a=te(r);if(a===void 0)continue;const c=an(a);if(c===void 0||!fc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:cn(a)}))}return s},gc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...pc(i,E(t,n)))}return s},mc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?_(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Nt(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&F(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},hc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...mc(c,r))}return s},xc=new Set(["query","unsafe"]),Ec=e=>{if(!o.isPropertyAccessExpression(e)||!xc.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},vc=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Sc=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Ac=(e,t)=>{if(!Ec(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!vc(s)))return{exportName:Sc(e),file:t,line:s.getStartLineNumber()}},yc=(e,t)=>P(e,t,Ac),Nc=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],bc=e=>{for(const[t,s]of Nc)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Pc=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=bc(a);c!==void 0&&s.push({file:E(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Ic=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),wc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return oe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Ic,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Tc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Cc=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Fc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),r==="expiresInSeconds"&&(s=Cc(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Oc=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Tc.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Rc=(e,t)=>{const s=Oc(e.getExpression());if(s!==void 0)return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...Fc(e.getArguments()[s.optionsIndex])}},Lc=(e,t)=>P(e,t,Rc),Dc=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),kc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),be=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&kc.has(s)?s:void 0},qt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},$t={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},Mc={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},Pe=(e,t,s,n,i)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${i.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),Kc=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(s.has(`${t}:${a}`)||!qt(r))continue;const c=be(r);c!==void 0&&n.push(Pe(t,a,c,r.getStartLineNumber(),$t))}return n},_c=(e,t,s)=>{if(s.has(`${t}:default`))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=be(i.getExpression());r!==void 0&&n.push(Pe(t,"default",r,i.getStartLineNumber(),$t))}return n},zc=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(s.has(`${t}:${a}`))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!qt(c))continue;const u=be(c);u!==void 0&&n.push(Pe(t,a,u,r.getStartLineNumber(),Mc))}return n},Uc=(e,t,s)=>[...Kc(e,t,s),..._c(e,t,s),...zc(e,t,s)],Bc=(e,t,s)=>{const n=new Set(s.map(r=>`${r.filePath}:${r.exportName}`)),i=[];for(const r of g(t)){const a=e.getSourceFile(r);a!==void 0&&i.push(...Uc(a,E(t,r),n))}return i.toSorted((r,a)=>r.cacheKey.localeCompare(a.cacheKey))},qc=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),$c=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Ee.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return Ee.has(i)?i:void 0}const s=t.getText();return Ee.has(s)?s:void 0},jc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,jt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(jc(e))return"empty-object";if(o.isParenthesizedExpression(e))return jt(e.getExpression())}},Ie=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Vc=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Ie(t)===e),Vt=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Ie(t)===e),Wc=e=>{const t=Vc(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Vt(e).length>0},Hc=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>Ie(t)===e),Ae=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",Gc=(e,t)=>Ae(e)||Ae(t),Yc=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),xt=e=>!Ae(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),Qc=(e,t,s)=>{const n=Yc.get(e);if(n!==void 0)return Gc(t,s)?n==="positive"?"negative":"positive":xt(t)||xt(s)?void 0:n},j=e=>{if(o.isParenthesizedExpression(e))return j(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=Qc(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=j(e.getLeft()),i=j(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},Et=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},Xc=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},Zc=e=>o.isReturnStatement(e)?e.getExpression()??e:e,Jc=e=>{const t=[];for(const s of Vt(e)){const n=j(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Hc(e)){const n=j(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?Et(s.getThenStatement()):Et(s.getElseStatement())??Xc(s);i!==void 0&&t.push(Zc(i))}return t},el=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},tl=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!qc.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&Wc(a))for(const c of Jc(a)){const u=jt(c);u!==void 0&&i.push({exportName:el(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return i},sl=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=$c(n);i!==void 0&&s.push(...tl(n,i,t))}return s},nl=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...sl(i,E(t,n)))}return s},rl=new Set(["query","upsert","upsertMany"]),il=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(rl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},ol=(e,t)=>{const s=il(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=N(n,"namespace");if(!(!i||!F(i)||K(i)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},al=(e,t)=>P(e,t,ol),cl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},ll=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ul=(e,t)=>{const s=[];for(const n of g(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!cl(a))continue;const c=Ts(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:ll(a)})}}return s},dl=".lunora-schema.json",I=(e,t)=>{b(e)&&At(e,"utf8")===t||ns(e,t,"utf8")},C=(e,t)=>{if(t===""){rs(e,{force:!0});return}I(e,t)},fl=e=>{const t=f(e,"package.json");if(b(t))try{const s=JSON.parse(At(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},pl=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},gl=e=>{let t=b(e)?e:pe(e);for(;t&&t!==pe(t);){const s=f(t,"tsconfig.json");if(b(s))return s;t=pe(t)}},vt=e=>e.replaceAll("\\","/"),ml=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new L("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new L("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},se=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},St=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,hl=8,xl=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:x}=e;let y=Je(a,i),p=tt(a,i),O=et(a,i);vn([...y,...p].map(S=>S.filePath));for(let S=1;;S+=1){const T=Ps({agents:t,functions:y,httpRoutes:O,mutators:p,useUmbrella:d,workflows:x}),k=Is({agents:t,functions:y,migrations:r,mutators:p,shapes:c,useUmbrella:d,usesSandbox:u});if(S>=hl||St(a,s,T)&&St(a,n,k))return{apiContent:T,functions:y,functionsContent:k,httpRoutes:O,mutators:p};se(a,s,T),se(a,n,k),y=Je(a,i),p=tt(a,i),O=et(a,i)}},El=e=>{const t=gl(e);return t?new Xe({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xe({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},fu=(e,t)=>{const s=g(t),n=f(t,"schema.ts");b(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>vt(c))),r=vt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},pu=e=>{const t=pl(),s=t?ge.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),i=f(n,"schema.ts");if(!b(i))throw new L("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??El(n);xn(Si);const a=on(r,i,e.projectRoot),{agents:c,containers:u,dataModelContent:d,dependencies:x,env:y,featureUsage:p,hasBrowser:O,hasFlags:S,hasNotify:T,identity:k,platformGate:U,queues:R,serverContent:z,storageRulesMetadata:B,usesSandbox:W,useUmbrella:w,workflows:M}=_n({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),m=f(n,"_generated"),we=f(m,"dataModel.ts"),Te=f(m,"server.ts"),Wt=f(m,"api.ts"),Ht=f(m,"functions.ts");se(r,we,d),se(r,Te,z);const ae=Qs(r,n),q=dn(r,n),{apiContent:Ce,functions:$,functionsContent:Fe,httpRoutes:Gt,mutators:Yt}=xl({agents:c,apiPath:Wt,generatedFunctionsPath:Ht,lunoraDirectory:n,migrations:ae,project:r,shapes:q,useUmbrella:w,usesSandbox:W,workflows:M}),ce=$s(r,n,M,c),H=e.lint===!1?void 0:as({adminRoutes:Wn(r,n),aiRawRuns:Yn(r,n),aiToolSideEffects:ir(r,n),argumentDerivedFetches:cr(r,n),argumentValidators:Sr(r,n),authApiCalls:qs(r,n),authConfigs:Fr(r,n),browserUrlAccesses:kr(r,n),configCalls:$r(r,n),containerKeyAccesses:Vr(r,n),containerOverrides:Xr(r,n),containers:u,exportSinks:ti(r,n),staleMigrationImports:Pc(r,n),failOpenGuards:oi(r,n),flagReads:mi(r,n),flagSecurityDefaults:vi(r,n),geoIndexUsages:Ni(r,n),httpActionGuards:Fi(r,n),httpHeaderWrites:Ui(r,n),hyperdriveCalls:Hs(r,n),identityClaimReads:Hi(r,n),imageDeliveryUrlAccesses:Yi(r,n),inserts:Gs(r,n),kvKeyAccesses:Xi(r,n),mailRecipientAccesses:so(r,n),maskProcedures:Ys(r,n),maskStrategies:uo(r,n),mutatorWrites:xo(r,n),nondeterministicCalls:Js(r,n),normalizeIdAuthorizations:Lo(r,n),notifyCalls:tn(r,n),notifyConfig:en(r,n),ownerFieldWrites:Bo(r,n,$),unrestrictedWhereBranches:nl(r,n),paymentWebhooks:Yo(r,n),privilegedDispatches:ca(r,n),procedureProtections:Wa(r,n),queries:Us(r,n),queues:R,r2sqlCalls:sn(r,n),ratelimitKeySelectors:Qa(r,n),rawRowReturns:nc(r,n),relationLoads:oc(r,n),rlsProcedures:nn(r,n),schema:a,secretLiterals:gc(r,n),shapes:q,softDeleteReads:hc(r,n),sqlInterpolations:yc(r,n),storageKeyAccesses:wc(r,n,$),storageUploads:Lc(r,n),vectorNamespaceAccesses:al(r,n),workflowCalls:ul(r,n),workflows:M,wranglerVariables:e.wranglerVariables}),Oe=H===void 0?[]:[...is(H,{source:"static"}),...Bc(r,n,$)],Qt=rn(r,n),Re=ao(r,n);ml(q,Re,io(r,n));const Xt=S?ui(r,n):[],G=Dc(p,{containerCount:u.length,cronCount:ce.length,dependencies:x,hasPaymentTables:jo(a.tables),queueCount:R.length,storageColumnCount:Object.keys(ps(a)).length,storageRuleCount:B.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:M.length}),Le=t?ge.now():0,le=En(a,ae.map(h=>h.id)),De=gs({advisories:Oe,advisorProcedures:H?.procedureProtections??[],agents:c,containers:u,env:y,flagKeys:Xt,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:O,hasFlags:S,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:T,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasX402:p.x402,maskMetadata:Re,mutators:Yt,queues:R,rlsMetadata:Qt,schema:a,schemaSnapshot:le,shapes:q,storageRules:B,studioFeatures:G,useUmbrella:w,workflows:M}),ke=ms(q,x.has("@lunora/db"),w),Me=hs(u,a.jurisdiction),Ke=xs(M),_e=Es(c),ze=vs(R),Ue=Ss(ce),Be=As(a.vectorIndexes),Y=ys(a,w),qe=Ns(x.has("@lunora/seed")),Q=e.apiSpec??"openapi",ue=Q==="openapi"||Q==="both",de=Q==="openrpc"||Q==="both",$e=fn({emailAgents:c.filter(h=>h.onEmail===!0).map(h=>({bindingName:h.bindingName,exportName:h.exportName})),hasAccess:x.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:x.has("@lunora/auth"),hasBrowser:O,hasFramework:x.has("@lunora/astro")||x.has("@lunora/svelte")||x.has("@lunora/vue"),hasGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend!=="hyperdrive"),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend==="hyperdrive"),hasImages:p.images,hasKv:p.kv,hasKvIntrospector:G.kv,hasNotify:T,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:R.some(h=>h.mode==="push"),hasScheduler:G.scheduler,hasStorage:G.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:M.length>0,hasX402:p.x402,identity:k,jurisdiction:a.jurisdiction,tableNames:a.tables.map(h=>h.name),useUmbrella:w,voiceAgents:c.filter(h=>h.voice===!0&&h.voiceBindingName!==void 0).map(h=>({bindingName:h.voiceBindingName,exportName:h.exportName})),wantsOpenApi:ue,wantsOpenRpc:de}),je=fl(e.projectRoot),Ve=pn({functions:$,httpRoutes:Gt,version:je}),We=mn({functions:$,version:je}),He=`${JSON.stringify(Ve,void 0,2)}
|
|
8
8
|
`,Ge=`${JSON.stringify(We,void 0,2)}
|
|
9
|
-
`,Ye=gn(Ve),Qe=hn(We),
|
|
9
|
+
`,Ye=gn(Ve),Qe=hn(We),fe=f(n,dl),Zt=b(fe);if(e.dryRun||(b(m)||ss(m,{recursive:!0}),I(f(m,"app.ts"),$e),I(we,d),I(f(m,"api.ts"),Ce),I(Te,z),I(f(m,"functions.ts"),Fe),I(f(m,"shard.ts"),De),I(f(m,"crons.ts"),Ue),I(f(m,"vectors.ts"),Be),I(f(m,"drizzle.global.ts"),Y.global),I(f(m,"drizzle.shard.ts"),Y.shard),C(f(m,"containers.ts"),Me),C(f(m,"workflows.ts"),Ke),C(f(m,"agents.ts"),_e),C(f(m,"queues.ts"),ze),C(f(m,"seed.ts"),qe),C(f(m,"collections.ts"),ke),C(f(m,"openapi.json"),ue?He:""),C(f(m,"openapi.ts"),ue?Ye:""),C(f(m,"openrpc.json"),de?Ge:""),C(f(m,"openrpc.ts"),de?Qe:""),(!Zt||e.updateSchemaBaseline===!0)&&I(fe,os(le))),t){const h=ge.now(),Jt=Math.round(h-s),es=Math.round(Le-s),ts=Math.round(h-Le);console.error(`@lunora/codegen: codegen took ${Jt.toString()}ms (discovery ${es.toString()}ms, emit ${ts.toString()}ms)`)}return{advisories:Oe,advisorContext:H,agents:c,containers:u,cronTriggers:bs(ce),generated:{agents:_e,api:Ce,app:$e,collections:ke,containers:Me,crons:Ue,dataModel:d,drizzleGlobal:Y.global,drizzleShard:Y.shard,functions:Fe,openApi:He,openApiModule:Ye,openRpc:Ge,openRpcModule:Qe,queues:ze,seed:qe,server:z,shard:De,vectors:Be,workflows:Ke},migrations:ae,outputDirectory:m,platformDiagnostics:U.diagnostics,queues:R,schemaSnapshot:le,schemaSnapshotPath:fe,workflows:M}};export{dl as SCHEMA_SNAPSHOT_FILENAME,El as createCodegenProject,gl as findTsconfig,fu as refreshCodegenProject,pu as runCodegen};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const a=(e,i=2166136261)=>{let t=i;for(let o=0;o<e.length;o+=1)t^=e.codePointAt(o)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},l=e=>`${a(e,2166136261)}${a(e,16777619)}`,g=1;function S(e){const i={},t=Object.keys(e);t.sort();for(const o of t)i[o]=e[o];return i}const c=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,$=e=>l(c(e)),r=e=>typeof e=="object"&&e!==null,f=e=>r(e)&&r(e.fields)&&r(e.indexes)&&r(e.relations)&&typeof e.shardMode=="string",k=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!r(i)||i.version!==1||!r(i.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,s]of Object.entries(i.tables))if(!f(s))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof i.jurisdiction=="string"?i.jurisdiction:void 0,migrationIds:Array.isArray(i.migrationIds)?i.migrationIds:[],tables:i.tables,version:1},status:"ok"}},p=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((t,o)=>t===i.fields[o]),h=(e,i,t,o)=>{const s=[];return t.kind!==o.kind&&s.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${i} changed type: ${t.kind} → ${o.kind} — add a data migration to convert existing values`,table:e,scope:"table",type:"changedFieldKind"}),t.optional&&!o.optional?s.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${i} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&o.optional&&s.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),s},m=(e,i,t)=>t.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${i}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${i} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},u=(e,i,t,o)=>{for(const[s,n]of Object.entries(t.fields)){const d=i.fields[s];d===void 0?o.push(m(e,s,n)):o.push(...h(e,s,d,n))}for(const s of Object.keys(i.fields))t.fields[s]===void 0&&o.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${s} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},y=(e,i,t,o)=>{for(const[s,n]of Object.entries(t.indexes)){const d=i.indexes[s];if(d===void 0){o.push({remediation:"none",scope:"table",severity:"safe",summary:`added index ${s} on ${e}`,table:e,type:"addedIndex"});continue}p(d,n)||o.push({remediation:"code",severity:"breaking",summary:`index ${s} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const s of Object.keys(i.indexes))t.indexes[s]===void 0&&o.push({remediation:"code",severity:"breaking",summary:`removed index ${s} on ${e} — a query that used \`.withIndex("${s}")\` would break`,table:e,scope:"table",type:"removedIndex"})},b=(e,i,t,o)=>{for(const s of Object.keys(t.relations))i.relations[s]===void 0&&o.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${s}`,table:e,type:"addedRelation"});for(const s of Object.keys(i.relations))t.relations[s]===void 0&&o.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${s}`,table:e,type:"removedRelation"})},v=(e,i,t,o)=>{i.shardMode!==t.shardMode&&o.push({remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${i.shardMode} → ${t.shardMode} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}),u(e,i,t,o),y(e,i,t,o),b(e,i,t,o)},O=(e,i)=>{const t=[],o=e?.tables??{};for(const[s,n]of Object.entries(i.tables)){const d=o[s];if(d===void 0){t.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${s}`,table:s,type:"addedTable"});continue}v(s,d,n,t)}for(const s of Object.keys(o))i.tables[s]===void 0&&t.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${s} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:s,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const s=e.jurisdiction??"(none)",n=i.jurisdiction??"(none)";t.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${s} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{g as SCHEMA_SNAPSHOT_VERSION,O as diffSchemaSnapshots,$ as hashSchemaSnapshot,f as isValidTableSnapshot,k as parseSnapshotJson,c as serializeSchemaSnapshot,S as sortKeys};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as y,sortKeys as E,diffSchemaSnapshots as I,parseSnapshotJson as T}from"./SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs";import{serializeSchemaSnapshot as q}from"./SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs";const _=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,A=e=>e.kind==="optional"?{kind:e.inner?.kind??"unknown",optional:!0}:{kind:e.kind,optional:!1},L=e=>{const n={};for(const[t,i]of Object.entries(e.shape))n[t]=A(i);const s={};for(const t of e.indexes)s[t.name]={fields:[...t.fields],unique:t.unique??!1};const o={};for(const t of e.relations)o[t.name]={field:t.field,kind:t.kind,table:t.table};return{fields:n,indexes:s,relations:o,shardMode:_(e.shardMode)}},R=(e,n)=>{const s={};for(const t of e.tables)s[t.name]=L(t);const o=[...n].sort();return{jurisdiction:e.jurisdiction,migrationIds:o,tables:E(s),version:y}};class D extends ${constructor(n){super("SCHEMA_SNAPSHOT_PARSE",n,{name:"SchemaSnapshotParseError"})}}const F=e=>{const n=T(e);if(n.status==="invalid")throw new D(n.error);return n.status==="ok"?n.snapshot:void 0},M={deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},g=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",S=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",j=e=>{const n=e===void 0?void 0:M[e];if(e===void 0||n===void 0)return`${g}
|
|
2
|
+
${S}
|
|
3
|
+
`;const s=n.updateBaseline?S:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${g}
|
|
4
|
+
${s}
|
|
5
|
+
`},h=e=>e.map(n=>` - ${n.summary}`).join(`
|
|
6
|
+
`),w=e=>e.remediation==="backfill"&&e.table!==void 0,x=/^[A-Za-z_]\w*$/u,B=e=>` lunora migrate create backfill_${e} --table ${e}`,O=(e,n,s)=>{const o=[...new Set(e.filter(i=>w(i)).map(i=>i.table))],t=[];if(o.length>0){t.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const i=o.filter(r=>x.test(r));i.length>0&&t.push(`
|
|
7
|
+
Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
|
|
8
|
+
${i.map(r=>B(r)).join(`
|
|
9
|
+
`)}
|
|
10
|
+
|
|
11
|
+
`)}return n.length>0&&t.push(` • Migration(s) ${n.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
|
|
12
|
+
`),t.push(j(s)),[`deploy blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,h(e),"",`To fix:
|
|
13
|
+
${t.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
|
|
14
|
+
`)},H=e=>{const{allowDrift:n=!1,baseline:s,command:o,current:t,migrations:i}=e,r=I(s,t),d=r.changes.filter(a=>a.severity==="breaking"),p=t.migrationIds.filter(a=>!(s?.migrationIds??[]).includes(a)),u=i.filter(a=>p.includes(a.id)),l=(a,f)=>({blocked:a,changes:r.changes,newMigrationIds:p,reason:f}),k=new Set(u.filter(a=>a.table!=="").map(a=>a.table)),v=u.filter(a=>a.table==="").map(a=>a.id);if(r.changes.length===0||s===void 0)return l(!1,"");if(d.length===0)return l(!1,`schema drift detected (all additive/safe):
|
|
15
|
+
${h(r.changes)}`);const m=d.filter(a=>!w(a)||!k.has(a.table));if(m.length===0){const a=new Set(d.map(c=>c.table)),f=u.filter(c=>a.has(c.table)).map(c=>c.id);return l(!1,`breaking schema drift detected, covered by ${String(f.length)} new migration(s) (${f.join(", ")}):
|
|
16
|
+
${h(d)}`)}const b=O(m,v,o);return n?l(!1,`${b}
|
|
17
|
+
|
|
18
|
+
(overridden by --allow-schema-drift)`):l(!0,b)};export{y as SCHEMA_SNAPSHOT_VERSION,D as SchemaSnapshotParseError,R as buildSchemaSnapshot,I as diffSchemaSnapshots,H as evaluateSchemaDrift,F as parseSchemaSnapshot,q as serializeSchemaSnapshot};
|
package/dist/packem_shared/{buildOpenApiDocument-CmLfuJpW.mjs → buildOpenApiDocument-CU1yw_t3.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-Bo3kao_A.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
|
|
2
2
|
`,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as ct}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as kn,hashSchemaSnapshot as xn}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{agentComponent as ct}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as kn,hashSchemaSnapshot as xn}from"./SCHEMA_SNAPSHOT_VERSION-CTWRkAF5.mjs";import{s as T}from"./paths-C-9fwEgQ.mjs";const dt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",serverCtxField:{field:`
|
|
2
2
|
/** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
|
|
3
3
|
readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",serverCtxField:{field:`
|
|
4
4
|
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as S,G as D}from"./emit-
|
|
1
|
+
import{A as S,G as D}from"./emit-Bo3kao_A.mjs";const E=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,v=S.map(({appMethod:e,key:t})=>[E(t),e.method,e.configKey,e.doc]),m=e=>v.some(([t])=>e[t]),A=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],x=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],R=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],C=e=>e?['import notifyConfig from "../notify.js";']:[],k=e=>(e.emailAgents?.length??0)>0,O=e=>k(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],T=e=>k(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],L=e=>{const{hasAccess:t,hasAuth:a,hasFramework:r,hasGlobal:n,hasHyperdriveGlobal:s,hasKvIntrospector:l,hasQueue:o,hasScheduler:d,hasStorage:h,hasWorkflow:u,useUmbrella:c,wantsOpenApi:p,wantsOpenRpc:b}=e,i=c?"lunorash/runtime":"@lunora/runtime",g=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions"];n&&g.push("GlobalIntrospector","AdminTableResolver"),r&&g.push("FrameworkHostHandler");const f=[...n||s?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...r?["withFrameworkWorker"]:[]].join(", ");return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...x(t,a),...n?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],...s?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...R(l),...d?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...h?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...u?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...O(e),`import type { ${[...g].toSorted((w,y)=>w.localeCompare(y)).join(", ")} } from "${i}";`,`import { ${f} } from "${i}";`,"",...A(e.identity),...T(e),...n||s?['import schema from "../schema.js";']:[],...C(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...p?['import { openApiSpec } from "./openapi.js";']:[],...b?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";']},I=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace plus the worker origin its callbacks dispatch back to. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n /** The worker origin the `SchedulerDO` dispatches HTTP job callbacks back to. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],q=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;"," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],N=e=>v.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: NonNullable<ShardConfig["${a}"]>): this {
|
|
3
3
|
this.shardExtras.${a} = factory;
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const r=(e,i=2166136261)=>{let t=i;for(let s=0;s<e.length;s+=1)t^=e.codePointAt(s)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},l=e=>`${r(e,2166136261)}${r(e,16777619)}`,g=1;function S(e){const i={},t=Object.keys(e);t.sort();for(const s of t)i[s]=e[s];return i}const c=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
-
`,$=e=>l(c(e)),a=e=>typeof e=="object"&&e!==null,p=e=>a(e)&&a(e.fields)&&a(e.indexes)&&a(e.relations)&&typeof e.shardMode=="string",O=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(s){return{error:`baseline is not valid JSON: ${s instanceof Error?s.message:String(s)}`,status:"invalid"}}if(!a(i)||i.version!==1||!a(i.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[s,o]of Object.entries(i.tables))if(!p(o))return{error:`baseline table "${s}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof i.jurisdiction=="string"?i.jurisdiction:void 0,migrationIds:Array.isArray(i.migrationIds)?i.migrationIds:[],tables:i.tables,version:1},status:"ok"}},f=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((t,s)=>t===i.fields[s]),h=(e,i,t,s)=>{const o=[];return t.kind!==s.kind&&o.push({severity:"breaking",summary:`field ${e}.${i} changed type: ${t.kind} → ${s.kind} — add a data migration to convert existing values`,table:e,scope:"table",type:"changedFieldKind"}),t.optional&&!s.optional?o.push({severity:"breaking",summary:`field ${e}.${i} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&s.optional&&o.push({scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),o},u=(e,i,t)=>t.optional?{scope:"table",severity:"safe",summary:`added optional field ${e}.${i}`,table:e,type:"addedOptionalField"}:{severity:"breaking",summary:`added required field ${e}.${i} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},y=(e,i,t,s)=>{for(const[o,d]of Object.entries(t.fields)){const n=i.fields[o];n===void 0?s.push(u(e,o,d)):s.push(...h(e,o,n,d))}for(const o of Object.keys(i.fields))t.fields[o]===void 0&&s.push({severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},m=(e,i,t,s)=>{for(const[o,d]of Object.entries(t.indexes)){const n=i.indexes[o];if(n===void 0){s.push({scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}f(n,d)||s.push({severity:"breaking",summary:`index ${o} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const o of Object.keys(i.indexes))t.indexes[o]===void 0&&s.push({severity:"breaking",summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` would break`,table:e,scope:"table",type:"removedIndex"})},v=(e,i,t,s)=>{for(const o of Object.keys(t.relations))i.relations[o]===void 0&&s.push({scope:"schema",severity:"safe",summary:`added relation ${e}.${o}`,table:e,type:"addedRelation"});for(const o of Object.keys(i.relations))t.relations[o]===void 0&&s.push({scope:"schema",severity:"breaking",summary:`removed relation ${e}.${o}`,table:e,type:"removedRelation"})},b=(e,i,t,s)=>{i.shardMode!==t.shardMode&&s.push({severity:"breaking",summary:`table ${e} changed shard mode: ${i.shardMode} → ${t.shardMode} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}),y(e,i,t,s),m(e,i,t,s),v(e,i,t,s)},x=(e,i)=>{const t=[],s=e?.tables??{};for(const[o,d]of Object.entries(i.tables)){const n=s[o];if(n===void 0){t.push({scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}b(o,n,d,t)}for(const o of Object.keys(s))i.tables[o]===void 0&&t.push({scope:"table",severity:"breaking",summary:`removed table ${o} — add a data migration if its data must be archived/cleaned up`,table:o,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const o=e.jurisdiction??"(none)",d=i.jurisdiction??"(none)";t.push({scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${d} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{g as SCHEMA_SNAPSHOT_VERSION,x as diffSchemaSnapshots,$ as hashSchemaSnapshot,p as isValidTableSnapshot,O as parseSnapshotJson,c as serializeSchemaSnapshot,S as sortKeys};
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as m,sortKeys as b,diffSchemaSnapshots as S,parseSnapshotJson as k}from"./SCHEMA_SNAPSHOT_VERSION-DLXXalg2.mjs";import{serializeSchemaSnapshot as O}from"./SCHEMA_SNAPSHOT_VERSION-DLXXalg2.mjs";const w=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,$=e=>e.kind==="optional"?{kind:e.inner?.kind??"unknown",optional:!0}:{kind:e.kind,optional:!1},v=e=>{const t={};for(const[n,o]of Object.entries(e.shape))t[n]=$(o);const a={};for(const n of e.indexes)a[n.name]={fields:[...n.fields],unique:n.unique??!1};const s={};for(const n of e.relations)s[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:t,indexes:a,relations:s,shardMode:w(e.shardMode)}},D=(e,t)=>{const a={};for(const n of e.tables)a[n.name]=v(n);const s=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:s,tables:b(a),version:m}};class y extends g{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const L=e=>{const t=k(e);if(t.status==="invalid")throw new y(t.error);return t.status==="ok"?t.snapshot:void 0},E={deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},f=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",p=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",I=e=>{const t=e===void 0?void 0:E[e];if(e===void 0||t===void 0)return`${f}
|
|
2
|
-
${p}
|
|
3
|
-
`;const a=t.updateBaseline?p:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${f}
|
|
4
|
-
${a}
|
|
5
|
-
`},T=e=>{const{allowDrift:t=!1,baseline:a,command:s,current:n}=e,o=S(a,n),d=o.changes.filter(r=>r.severity==="breaking"),l=n.migrationIds.filter(r=>!(a?.migrationIds??[]).includes(r)),i=(r,c)=>({blocked:r,changes:o.changes,newMigrationIds:l,reason:c});if(o.changes.length===0||a===void 0)return i(!1,"");if(d.length===0){const r=o.changes.map(c=>` - ${c.summary}`).join(`
|
|
6
|
-
`);return i(!1,`schema drift detected (all additive/safe):
|
|
7
|
-
${r}`)}const u=d.map(r=>` - ${r.summary}`).join(`
|
|
8
|
-
`);if(l.length>0)return i(!1,`breaking schema drift detected, but ${String(l.length)} new migration(s) were added (${l.join(", ")}):
|
|
9
|
-
${u}`);const h=`deploy blocked: ${String(d.length)} breaking schema change(s) detected since the last blessed schema baseline — these changes are incompatible with existing data without a migration:
|
|
10
|
-
${u}
|
|
11
|
-
|
|
12
|
-
To fix:
|
|
13
|
-
• 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.
|
|
14
|
-
${I(s)}Docs: https://lunora.dev/docs/migrations`;return t?i(!1,`${h}
|
|
15
|
-
|
|
16
|
-
(overridden by --allow-schema-drift)`):i(!0,h)};export{m as SCHEMA_SNAPSHOT_VERSION,y as SchemaSnapshotParseError,D as buildSchemaSnapshot,S as diffSchemaSnapshots,T as evaluateSchemaDrift,L as parseSchemaSnapshot,O as serializeSchemaSnapshot};
|