@lunora/codegen 1.0.0-alpha.186 → 1.0.0-alpha.188
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 +39 -3
- package/dist/index.d.ts +39 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-DicwKMVV.mjs → GENERATED_HEADER-CmffnV1I.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-BPs1hq5Q.mjs → OPENRPC_VERSION-CvPG_unm.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-BiHpdo7a.mjs → SCHEMA_SNAPSHOT_FILENAME-CIiiVuU1.mjs} +6 -6
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs +2 -0
- package/dist/packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs +18 -0
- package/dist/packem_shared/{buildOpenApiDocument-BaDsKuhs.mjs → buildOpenApiDocument-DZJVlDWv.mjs} +1 -1
- package/dist/packem_shared/{emit-wC8dZkgS.mjs → emit-B8cDEy4W.mjs} +1 -1
- package/dist/packem_shared/{emitApp-BpcEHPGo.mjs → emitApp-Dwpe1b2a.mjs} +1 -1
- package/package.json +9 -9
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs +0 -2
- package/dist/packem_shared/SchemaSnapshotParseError-D_n90pDd.mjs +0 -18
package/dist/index.d.mts
CHANGED
|
@@ -65,8 +65,21 @@ interface RelationSnapshot {
|
|
|
65
65
|
kind: "many" | "one";
|
|
66
66
|
table: string;
|
|
67
67
|
}
|
|
68
|
+
/** A table's declarative `.ttl(field, { after })` auto-expiry policy. */
|
|
69
|
+
interface TtlSnapshot {
|
|
70
|
+
/** Millisecond offset added to `field` to derive the expiry; absent ⇒ `field` IS the absolute expiry (an offset of zero). */
|
|
71
|
+
after?: number;
|
|
72
|
+
/** The epoch-millisecond expiry column the DO alarm sweep reads. */
|
|
73
|
+
field: string;
|
|
74
|
+
}
|
|
68
75
|
/** Structural snapshot of one table. */
|
|
69
76
|
interface TableSnapshot {
|
|
77
|
+
/**
|
|
78
|
+
* `.commitOrdered()` — every row carries a `_commitSeq`. Always written by a
|
|
79
|
+
* current snapshot, so its absence dates the baseline rather than describing
|
|
80
|
+
* the table; see {@link recordsTableModifiers}.
|
|
81
|
+
*/
|
|
82
|
+
commitOrdered?: boolean;
|
|
70
83
|
/**
|
|
71
84
|
* Field name → {@link FieldSnapshot}, keys sorted by UTF-16 code unit (see
|
|
72
85
|
* `sortKeys` below). Declaration order was tried and abandoned: the snapshot
|
|
@@ -76,14 +89,27 @@ interface TableSnapshot {
|
|
|
76
89
|
fields: Record<string, FieldSnapshot>;
|
|
77
90
|
/** Index name → {@link IndexSnapshot}. */
|
|
78
91
|
indexes: Record<string, IndexSnapshot>;
|
|
92
|
+
/**
|
|
93
|
+
* `.memory()` — the table is emptied on every Durable Object cold start.
|
|
94
|
+
* Always written by a current snapshot; see {@link recordsTableModifiers}.
|
|
95
|
+
*/
|
|
96
|
+
memory?: boolean;
|
|
79
97
|
/** Relation accessor name → {@link RelationSnapshot}. */
|
|
80
98
|
relations: Record<string, RelationSnapshot>;
|
|
81
99
|
/**
|
|
82
|
-
* `"root"` (default single-DO), `"global"` (
|
|
83
|
-
* `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
|
|
100
|
+
* `"root"` (default single-DO), `"global:<backend>"` (`d1` or `hyperdrive`),
|
|
101
|
+
* or `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
|
|
84
102
|
* stays a plain JSON-stable value.
|
|
103
|
+
*
|
|
104
|
+
* The backend is part of the MODE, not a detail beside it: a `.global()`
|
|
105
|
+
* table lives in D1 and a `.global({ backend: "hyperdrive" })` one in a
|
|
106
|
+
* Postgres/MySQL database reached through Hyperdrive — two different physical
|
|
107
|
+
* stores, and switching between them moves no rows. A snapshot written before
|
|
108
|
+
* that was encoded says bare `"global"`; see {@link shardModeChange}.
|
|
85
109
|
*/
|
|
86
110
|
shardMode: string;
|
|
111
|
+
/** `.ttl(...)`, or absent when the table declares none. Only meaningful once {@link recordsTableModifiers} holds. */
|
|
112
|
+
ttl?: TtlSnapshot;
|
|
87
113
|
}
|
|
88
114
|
/** A deterministic structural view of the whole schema at one point in time. */
|
|
89
115
|
interface SchemaSnapshot {
|
|
@@ -156,7 +182,7 @@ interface DriftChange {
|
|
|
156
182
|
/** The table this change belongs to. Always set when `scope` is `"table"`. */
|
|
157
183
|
table?: string;
|
|
158
184
|
/** A machine-readable change discriminator. */
|
|
159
|
-
type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
|
|
185
|
+
type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedCommitOrdering" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedMemoryMode" | "changedShardMode" | "changedTtlPolicy" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
|
|
160
186
|
}
|
|
161
187
|
/** The result of diffing two snapshots: every classified change. */
|
|
162
188
|
interface SchemaDrift {
|
|
@@ -2687,6 +2713,16 @@ interface CodegenResult {
|
|
|
2687
2713
|
* adds no binding or migration. Empty when the project declares no workflows.
|
|
2688
2714
|
*/
|
|
2689
2715
|
workflows: ReadonlyArray<WorkflowIR>;
|
|
2716
|
+
/**
|
|
2717
|
+
* The `_generated/` file names this run emitted, in write order, relative to
|
|
2718
|
+
* {@link CodegenResult.outputDirectory}. Conditional files appear only when
|
|
2719
|
+
* their feature is in use, and the spec artifacts only for the requested
|
|
2720
|
+
* `apiSpec` — so this is what the project actually has, not a fixed list.
|
|
2721
|
+
* Empty under `dryRun` (nothing is written). Callers report from this rather
|
|
2722
|
+
* than restating the set, which is how the CLI came to advertise three of
|
|
2723
|
+
* twelve files.
|
|
2724
|
+
*/
|
|
2725
|
+
writtenFiles: ReadonlyArray<string>;
|
|
2690
2726
|
}
|
|
2691
2727
|
/** Deduplicated, sorted names of every ERROR-level advisory in `advisories`. */
|
|
2692
2728
|
declare const errorAdvisoryNames: (advisories: ReadonlyArray<Pick<Finding, "level" | "name">>) => ReadonlyArray<string>;
|
package/dist/index.d.ts
CHANGED
|
@@ -65,8 +65,21 @@ interface RelationSnapshot {
|
|
|
65
65
|
kind: "many" | "one";
|
|
66
66
|
table: string;
|
|
67
67
|
}
|
|
68
|
+
/** A table's declarative `.ttl(field, { after })` auto-expiry policy. */
|
|
69
|
+
interface TtlSnapshot {
|
|
70
|
+
/** Millisecond offset added to `field` to derive the expiry; absent ⇒ `field` IS the absolute expiry (an offset of zero). */
|
|
71
|
+
after?: number;
|
|
72
|
+
/** The epoch-millisecond expiry column the DO alarm sweep reads. */
|
|
73
|
+
field: string;
|
|
74
|
+
}
|
|
68
75
|
/** Structural snapshot of one table. */
|
|
69
76
|
interface TableSnapshot {
|
|
77
|
+
/**
|
|
78
|
+
* `.commitOrdered()` — every row carries a `_commitSeq`. Always written by a
|
|
79
|
+
* current snapshot, so its absence dates the baseline rather than describing
|
|
80
|
+
* the table; see {@link recordsTableModifiers}.
|
|
81
|
+
*/
|
|
82
|
+
commitOrdered?: boolean;
|
|
70
83
|
/**
|
|
71
84
|
* Field name → {@link FieldSnapshot}, keys sorted by UTF-16 code unit (see
|
|
72
85
|
* `sortKeys` below). Declaration order was tried and abandoned: the snapshot
|
|
@@ -76,14 +89,27 @@ interface TableSnapshot {
|
|
|
76
89
|
fields: Record<string, FieldSnapshot>;
|
|
77
90
|
/** Index name → {@link IndexSnapshot}. */
|
|
78
91
|
indexes: Record<string, IndexSnapshot>;
|
|
92
|
+
/**
|
|
93
|
+
* `.memory()` — the table is emptied on every Durable Object cold start.
|
|
94
|
+
* Always written by a current snapshot; see {@link recordsTableModifiers}.
|
|
95
|
+
*/
|
|
96
|
+
memory?: boolean;
|
|
79
97
|
/** Relation accessor name → {@link RelationSnapshot}. */
|
|
80
98
|
relations: Record<string, RelationSnapshot>;
|
|
81
99
|
/**
|
|
82
|
-
* `"root"` (default single-DO), `"global"` (
|
|
83
|
-
* `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
|
|
100
|
+
* `"root"` (default single-DO), `"global:<backend>"` (`d1` or `hyperdrive`),
|
|
101
|
+
* or `"shardBy:<field>"` (partitioned). Encoded as a string so the snapshot
|
|
84
102
|
* stays a plain JSON-stable value.
|
|
103
|
+
*
|
|
104
|
+
* The backend is part of the MODE, not a detail beside it: a `.global()`
|
|
105
|
+
* table lives in D1 and a `.global({ backend: "hyperdrive" })` one in a
|
|
106
|
+
* Postgres/MySQL database reached through Hyperdrive — two different physical
|
|
107
|
+
* stores, and switching between them moves no rows. A snapshot written before
|
|
108
|
+
* that was encoded says bare `"global"`; see {@link shardModeChange}.
|
|
85
109
|
*/
|
|
86
110
|
shardMode: string;
|
|
111
|
+
/** `.ttl(...)`, or absent when the table declares none. Only meaningful once {@link recordsTableModifiers} holds. */
|
|
112
|
+
ttl?: TtlSnapshot;
|
|
87
113
|
}
|
|
88
114
|
/** A deterministic structural view of the whole schema at one point in time. */
|
|
89
115
|
interface SchemaSnapshot {
|
|
@@ -156,7 +182,7 @@ interface DriftChange {
|
|
|
156
182
|
/** The table this change belongs to. Always set when `scope` is `"table"`. */
|
|
157
183
|
table?: string;
|
|
158
184
|
/** A machine-readable change discriminator. */
|
|
159
|
-
type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedShardMode" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
|
|
185
|
+
type: "addedFieldConstraint" | "addedIndex" | "addedOptionalField" | "addedRelation" | "addedRequiredField" | "addedTable" | "changedCommitOrdering" | "changedFieldKind" | "changedFieldShape" | "changedIndex" | "changedJurisdiction" | "changedMemoryMode" | "changedShardMode" | "changedTtlPolicy" | "fieldOptionalToRequired" | "fieldRequiredToOptional" | "relaxedFieldConstraint" | "removedField" | "removedIndex" | "removedRelation" | "removedTable" | "widenedFieldShape";
|
|
160
186
|
}
|
|
161
187
|
/** The result of diffing two snapshots: every classified change. */
|
|
162
188
|
interface SchemaDrift {
|
|
@@ -2687,6 +2713,16 @@ interface CodegenResult {
|
|
|
2687
2713
|
* adds no binding or migration. Empty when the project declares no workflows.
|
|
2688
2714
|
*/
|
|
2689
2715
|
workflows: ReadonlyArray<WorkflowIR>;
|
|
2716
|
+
/**
|
|
2717
|
+
* The `_generated/` file names this run emitted, in write order, relative to
|
|
2718
|
+
* {@link CodegenResult.outputDirectory}. Conditional files appear only when
|
|
2719
|
+
* their feature is in use, and the spec artifacts only for the requested
|
|
2720
|
+
* `apiSpec` — so this is what the project actually has, not a fixed list.
|
|
2721
|
+
* Empty under `dryRun` (nothing is written). Callers report from this rather
|
|
2722
|
+
* than restating the set, which is how the CLI came to advertise three of
|
|
2723
|
+
* twelve files.
|
|
2724
|
+
*/
|
|
2725
|
+
writtenFiles: ReadonlyArray<string>;
|
|
2690
2726
|
}
|
|
2691
2727
|
/** Deduplicated, sorted names of every ERROR-level advisory in `advisories`. */
|
|
2692
2728
|
declare const errorAdvisoryNames: (advisories: ReadonlyArray<Pick<Finding, "level" | "name">>) => ReadonlyArray<string>;
|
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-C0oHwiJZ.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-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as h}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as D}from"./packem_shared/discoverFunctions-DB9G_XrW.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-S81Iv_iB.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs";import{default as y}from"./packem_shared/discoverInserts-COk-Sm_n.mjs";import{d as W}from"./packem_shared/index-D_Z8rX-f.mjs";import{default as V}from"./packem_shared/discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CTHlZ1j6.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-DkVVHe3U.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-CZh4jN4q.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-CPlxXagL.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-vJZq3yhb.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CwWRPb8N.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-DskdDbkM.mjs";import{default as xe}from"./packem_shared/discoverSchema-DoZtXwLg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-xhxu-mkS.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-BaSbufF2.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-B8cDEy4W.mjs";import{emitApp as We}from"./packem_shared/emitApp-Dwpe1b2a.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-DZJVlDWv.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-CvPG_unm.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-DtzlGawL.mjs";import{PROJECT_CONFIG_FILENAMES as ir,findProjectConfigFile as mr,loadProjectConfig as dr,readProjectConfigLiterals as fr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,createCodegenProject as nr,findTsconfig as lr,refreshCodegenProject as Sr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-CIiiVuU1.mjs";import{SchemaSnapshotParseError as Ar,buildSchemaSnapshot as ur,evaluateSchemaDrift as vr,parseSchemaSnapshot as Nr}from"./packem_shared/SchemaSnapshotParseError-lUWe6lPo.mjs";import{schemaFromIr as Cr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Mr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as _r,SDK_TARGETS as hr,generateSdk as Lr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ir,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Gr,findSolutionByMessage as Ur}from"@lunora/errors";import{isTypedSchema as Hr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Gr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,ir as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,_r as SDK_LANGUAGES,hr as SDK_TARGETS,Ae as SHAPES_FILENAME,Ar as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,ur as buildSchemaSnapshot,nr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,vr as evaluateSchemaDrift,Ur as findLunoraSolution,mr as findProjectConfigFile,lr as findTsconfig,m as formatAdvisories,Lr as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,Hr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,dr as loadProjectConfig,Nr as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,fr as readProjectConfigLiterals,tr as readProjectTarget,Ir as redact,Sr as refreshCodegenProject,sr as resolveCodegenTarget,xr as runCodegen,Cr as schemaFromIr,Pr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Mr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{G as r,U as o,o as n,e as l,a as A,b as E,c as S,d as p,f as c,g as d,h as g,p as u,i as C,q as h,j as D,k as f,l as G,m as R,n as _}from"./emit-B8cDEy4W.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./paths-C-9fwEgQ.mjs";import"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,l as emitAgents,A as emitApi,E as emitCollections,S as emitContainers,p as emitCrons,c as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,C as emitScheduler,h as emitSeed,D as emitServer,f as emitShard,G as emitVectors,R as emitWorkflows,_ as emitWranglerCronTriggers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-B8cDEy4W.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-C2s0xWQD.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 Ps,readFileSync as
|
|
2
|
-
`);throw new
|
|
1
|
+
import{existsSync as b,mkdirSync as Ps,readFileSync as _t,writeFileSync as Is,rmSync as ws}from"node:fs";import{join as E,dirname as se}from"node:path";import{performance as ye}from"node:perf_hooks";import{runAdvisor as Ts}from"@lunora/advisor";import{LunoraError as L}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as ct}from"ts-morph";import{serializeSchemaSnapshot as Cs}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{toAdvisorContext as Fs}from"./formatAdvisories-CkEu1eye.mjs";import{s as Os}from"./paths-C-9fwEgQ.mjs";import{C as ne,o as Kt,j as Rs,f as Ls,k as Ds,b as ks,c as Ms,m as _s,e as Ks,p as zs,d as $s,i as Us,l as qs,g as Bs,q as Vs,n as Ws,a as js,h as Hs}from"./emit-B8cDEy4W.mjs";import{isD1GlobalTable as zt,isHyperdriveGlobalTable as $t}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Gs}from"./AGENTS_FILENAME-B78F7DuQ.mjs";import{discoverContainers as Ys}from"./CONTAINERS_FILENAME-CQoUu7n7.mjs";import Qs from"./discoverCrons-CMu0sA8k.mjs";import{diagnosticAt as le}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ue}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as p,unwrapExpression as G,listSecurityScanFiles as Oe,objectLiteralFromCallbackBody as Ut,propertyInitializer as A,lunoraRelativePath as x,collectCallRows as w,collectSecurityCallRows as Xs,limitNameOf as qt,isContextIdentifier as Pe,handlerOf as Zs,isDatabaseAccessor as D,readTargetOf as Bt,enclosingExportName as Js}from"./listLunoraSourceFiles-D4xthUf-.mjs";import en from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as tn}from"./QUEUES_FILENAME-Q3CF3uYr.mjs";import{discoverSandboxUsage as sn}from"./discoverSandboxUsage-DskdDbkM.mjs";import nn from"./discoverStorageRulesMetadata-xhxu-mkS.mjs";import{a as S,c as k,d as Vt,e as rn}from"./classify-procedure-call-C8jbo0IJ.mjs";import{discoverWorkflows as on}from"./WORKFLOWS_FILENAME-BaSbufF2.mjs";import{gatePlatformFeatures as an,resolveCodegenTarget as cn,readTargetDiagnostics as ln}from"./DEFAULT_TARGET-DtzlGawL.mjs";import{i as R,a as K,e as v,r as un,b as dn,s as de,c as fn,f as gn,d as pn}from"./queries-CPlxXagL.mjs";import{r as fe,s as mn}from"./parse-validator-tdRHHDzh.mjs";import hn from"./discoverAuthApiCalls-DoblmzUW.mjs";import lt from"./discoverFunctions-DB9G_XrW.mjs";import{i as xn,r as vn,e as En}from"./unwrap-handler-return-CmIWbykC.mjs";import ut from"./discoverHttpRoutes-S81Iv_iB.mjs";import Sn from"./discoverHyperdriveCalls-DgAYcZRD.mjs";import yn from"./discoverInserts-COk-Sm_n.mjs";import{m as Re,a as oe,s as Wt,d as An}from"./index-D_Z8rX-f.mjs";import{e as jt}from"./exported-procedure-chains-C9FHwphy.mjs";import Nn from"./discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as bn,isDefineMutatorCallee as Pn,discoverMutators as dt}from"./MUTATORS_FILENAME-CTHlZ1j6.mjs";import In from"./discoverNondeterministicCalls-DkVVHe3U.mjs";import{discoverNotifyConfig as wn,discoverNotifyCalls as Tn}from"./NOTIFY_FILENAME-CZh4jN4q.mjs";import Cn from"./discoverR2sqlCalls-6u0OKy2N.mjs";import Fn from"./discoverRlsProcedures-vJZq3yhb.mjs";import On from"./discoverRlsMetadata-CwWRPb8N.mjs";import Rn from"./discoverSchema-DoZtXwLg.mjs";import{secretKindOf as Ln,redact as Dn,isHeuristicSecretKind as kn,isSecretishName as Mn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as _n}from"./SHAPES_FILENAME-Bvd5kgsF.mjs";import{emitApp as Kn}from"./emitApp-Dwpe1b2a.mjs";import{buildOpenApiDocument as zn,emitOpenApiModule as $n}from"./buildOpenApiDocument-DZJVlDWv.mjs";import{buildOpenRpcDocument as Un,emitOpenRpcModule as qn}from"./OPENRPC_VERSION-CvPG_unm.mjs";import{buildSchemaSnapshot as Bn}from"./SchemaSnapshotParseError-lUWe6lPo.mjs";const ft=(e,t="api")=>{const s=new Map;for(const n of e){const o=Os(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new L("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Vn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>zt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>$t(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:ne)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Wn=(e,t,s={})=>{if(t===void 0)return;const n=Vn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
|
+
`);throw new L("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${o}
|
|
4
4
|
|
|
5
|
-
Install them with your package manager, then re-run codegen.`)},jn="env.ts",Hn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return le(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Gn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&le(n.getModuleSpecifierValue())}return!1},Yn=e=>{if(i.isIdentifier(e))return Hn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Gn(t)}return!1},Qn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Yn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ce(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Xn=(e,t)=>{const s=f(t,jn);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=Qn(n);if(o.length!==0){if(o.length>1)throw ce(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},ft="ctx",jt=e=>{const t=new Set,s=new Set([ft]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==ft)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},Zn=(e,t)=>{const s=Object.fromEntries(se.map(n=>[n.key,!1]));for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=jt(o);for(const c of se)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(se.every(c=>s[c.key]))break}return s},Ht="identity.ts",Jn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return le(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},er=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&le(n.getModuleSpecifierValue())}return!1},tr=e=>{if(i.isIdentifier(e))return Jn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&er(t)}return!1},sr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!tr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw ce(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},nr=(e,t)=>{const s=f(t,Ht);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=sr(n);if(o.length!==0){if(o.length>1)throw ce(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},rr=(e,t)=>{const s=H(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return H(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},or=e=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!i.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||H(s)?.getText()!=="false"}),ir=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=jt(o).has("secrets")),s.durableStreams||(s.durableStreams=o.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(i.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>or(rr(o,u)))})),s.durableStreams&&s.secrets)break}return s},ar="createWorker",cr="extend",gt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,pt=e=>{const t=[],s=gt(N(e,"backupCron"));s!==void 0&&t.push(s);const n=N(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=gt(o.getNameNode());r!==void 0&&t.push(r)}return t},lr=e=>{const t=y(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===ar)return i.isObjectLiteralExpression(s)?pt(s):[];if(t!==cr||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=$t(s.getBody());return n===void 0?[]:pt(n)},ur=(e,t)=>{const s=[];for(const{filePath:n}of Te(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...lr(r))}return[...new Set(s)]},Gt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Gt(e.inner)},dr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=Gt(n);return o!==void 0&&t.has(o)}))},fr=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new D("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 D("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=o.get(r.className);if(u!==void 0)throw new D("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})}},gr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=nr(s,t),a=Xn(s,t),c=on(s,t),u=tn(s,t),d=Gs(s,t);fr(c,d);const v=Ys(s,t),x=nn(s,t),P=Qs(s,t,c,d),_=ur(s,t),p=ir(s,t),T=sn(s,t),O=Zn(s,t);O.browser=O.browser||T.usesSandboxBrowser;const U=an(O,cn(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(g=>g.commitOrdered===!0),cronTriggers:P.length>0,crossShardFanout:o.tables.some(g=>typeof g.shardMode=="object"),durableStreams:p.durableStreams,globalTables:o.tables.some(g=>g.shardMode==="global"),queues:u.length>0,relationGraph:dr(o),secrets:p.secrets,vectorStore:o.vectorIndexes.length>0}),A=U.usage,R=U.signals.vectorStore!==!1,$=en(n),V=$??new Set,Q=V.has("lunorash");Wn(o,$,{hasVectors:R,scheduler:A.scheduler||P.length>0,storage:A.storage||x.rules.length>0||Object.keys(_t(o)).length>0,usage:A});const K=b(f(t,"flags.ts")),C=b(f(t,"notify.ts"));return{agents:d,containers:v,crons:P,dataModelContent:Ls(o),declaredDependencies:$,dependencies:V,entryCronTriggers:_,env:a,featureUsage:A,hasFlags:K,hasNotify:C,identity:r,platformGate:{...U,diagnostics:[...ln(n,e.target),...U.diagnostics]},queues:u,serverContent:Rs({agents:d,containers:v,env:a,hasAccessFacade:A.access,hasAi:A.ai,hasAnalytics:A.analytics,hasBrowser:A.browser,hasVectors:R,hasFlags:K,hasHyperdrive:A.hyperdrive,hasImages:A.images,hasKv:A.kv,hasNotify:C,hasPayments:A.payments,hasPipelines:A.pipelines,hasR2sql:A.r2sql,hasX402:A.x402,identity:r,queues:u,schema:o,storageRuleBuckets:x.rules.map(g=>g.bucket),useUmbrella:Q,workflows:c}),storageRulesMetadata:x,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer||T.usesSandboxFs,useUmbrella:Q,workflows:c}},Yt=new Set(["delete","get","head","options","patch","post","put"]),pr=new Set(["handler","stream"]),mr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,mt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),hr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Yt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},xr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||Yt.has(n.getName()))break;s=n.getExpression()}return hr(s)},vr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(mt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&mt.has(s.getText()))return!0}return!1},Er=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!pr.has(n.getName()))return;const o=xr(s);if(!o||!mr.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&vr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Sr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Er(o,t);r&&s.push(r)}return s},yr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Sr(o,E(t,n)))}return s},Ar=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Nr=(e,t)=>{if(!Ar(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)||z(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},br=(e,t)=>I(e,t,Nr),Pr=new Set(["generateText","streamText"]),Ir=new Set(["messages","prompt","system"]),wr=[{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"]}],Tr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of wr)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Cr=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Tr(t);if(s!==void 0)return s}},Fr=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Or=e=>{if(un(e))return!0;const t=Fr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Rr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Ir.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Or(s))return!0}return!1},Lr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());if(o===void 0||!Pr.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=Cr(c),a!==void 0))break;a!==void 0&&s.push({exportName:S(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Rr(r)})}return s},Dr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Lr(o,E(t,n)))}return s},kr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Mr=(e,t)=>{if(!kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!L(s)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},_r=(e,t)=>I(e,t,Mr),Fe=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=de(s.getExpression());return n===void 0||Fe(n,t)})}finally{t.delete(e)}},Kr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:de(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:Fe(o)}},zr=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?de(r):void 0;a===void 0?s=!0:(t.push(a),s||=Fe(a))}n=o.getExpression()}return{objects:t,opaque:s}},Oe=(e,t)=>t?zr(t):Kr(e),Qt=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=de(s.getExpression());return n===void 0?[]:Qt(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},$r=e=>e.flatMap(t=>Qt(t,new Set)),Ur=new Set(["check","length","max"]),be=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},qr=e=>[e,...e.getDescendants()].filter(t=>be(t)!==void 0),Br=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(Ur.has(s.getName()))return!0;t=n}},Vr=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=qr(r),c=o.getName();a.some(u=>be(u)==="any")?t.push(c):a.some(u=>be(u)==="string"&&!Br(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Wr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=M(s);if(n?.visibility!=="public")return;const{objects:o}=Oe(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=Vr(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},jr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Wr(o,t);r&&s.push(r)}return s},Hr=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...jr(o,E(t,n)))}return s},Se=e=>e?.getKind()===l.TrueKeyword,Gr=e=>e?.getKind()===l.FalseKeyword,Yr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Qr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Xr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&y(t.getExpression())==="scim"),Zr=e=>e!==void 0&&i.isCallExpression(e)&&Qr.has(y(e.getExpression())??""),Jr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),eo=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:Se(N(t,"disableCSRFCheck")),emailPasswordEnabled:Se(N(s,"enabled")),requireEmailVerification:Se(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Xr(N(e,"plugins"))&&Zr(N(e,"database")),secureCookiesDisabled:Gr(N(t,"useSecureCookies")),sessionFreshAgeZero:Yr(N(n,"freshAge")),trustedOriginsWildcard:Jr(N(e,"trustedOrigins"))}},to=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),so=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?eo(s):to();return{exportName:S(e),file:t,line:e.getStartLineNumber(),...o}},no=(e,t)=>Xs(e,t,so),ro=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},oo=(e,t,s)=>{const n=ro(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!L(o)||z(o))&&!(s.requireUnmodifiedReach===!0&&!dn(o)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:n}},io=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=oo(o,t,s);r&&n.push(r)}return n},fe=(e,t,s)=>{const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...io(r,E(t,o),s))}return n},ao=new Set(["content","pdf","scrape","screenshot"]),co=(e,t)=>fe(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ao}),lo=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),uo=new Set(["RateLimiter"]),fo=new Set(["extend"]),ht="lunora",go=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Xt=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},Pe=e=>e&&i.isObjectLiteralExpression(e)?Xt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},po=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&$t(t.getBody());return s?Xt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},mo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=y(n.getExpression());o!==void 0&&(lo.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...Pe(n.getArguments()[0])}):fo.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...po(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=y(n.getExpression());o===void 0||!uo.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...Pe(n.getArguments()[0])})}return s},ho=(e,t)=>{for(const s of go){const n=f(t,s);if(!b(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===ht&&r.push({callee:ht,file:s,line:a.getStartLineNumber(),...Pe(a.getArguments()[0])});return r}return[]},xo=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Te(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...mo(r,n))}return s.push(...ho(e,te(t))),s},xt="ctx.containers.",vo=e=>{if(!e.startsWith(xt))return!1;const t=e.slice(xt.length);return t.length>0&&!t.includes(".")},Eo=(e,t)=>fe(e,t,{argIndex:0,matchReceiver:vo,methods:new Set(["get"])}),So=new Set(["allow","deny","setAllowed"]),yo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Ao=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!yo(e)))return{detail:"enableInternet: true",exportName:S(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},No=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!So.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:S(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},bo=(e,t)=>Ao(e,t)??No(e,t),Po=(e,t)=>I(e,t,bo),Io=new Set(["defineExportSink","r2Sink","webhookExportSink"]),wo=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Io.has(s)?s:void 0},To=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Co=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Te(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=wo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?To(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Fo=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Oo=new Set(["dbRateLimit","rateLimit"]),Ro=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Lo=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=Fo.get(s);if(n!==void 0)return{callee:s,exportName:S(e),failOpen:Ro(e.getArguments()[n]),file:t,limitName:Oo.has(s)?Ut(e):"",line:e.getStartLineNumber()}},Do=(e,t)=>I(e,t,Lo),ko=new Set(["boolean","number","object","string"]),Mo=e=>{const t=e.getName();if(!ko.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Ne(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Ne(n.getExpression()))return t},_o=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=Mo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},Ko=(e,t)=>{const s=new Map;for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=_o(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},zo=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=M(t);if(s?.kind!=="query")return;const n=Zs(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},vt=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},$o=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=vt(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=vt(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},Uo=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=$o(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},qo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=zo(o);r&&s.push(...Uo(r,t))}return s},Bo=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...qo(o,E(t,n)))}return s},Vo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Ne(t.getExpression())},Wo=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},jo=(e,t)=>{if(!Vo(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=Wo(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:S(e),file:t,key:o,line:e.getStartLineNumber()}},Ho=(e,t)=>I(e,t,jo),Go=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 o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||xn(r))return;const a=e.getSourceFile().getFilePath();return vn(o,e,a)?En(o,e,a,0,new Set):r},Yo=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Qo=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Xo=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))Yo(a)&&s.push({file:r,indexName:Qo(a),line:a.getStartLineNumber()})}return s},G=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Zt=e=>{const t=e.getArguments()[0],s=G(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&i.isPropertyAssignment(n)?G(n.getInitializer()):void 0},Zo=new Set(["delete","get","head","options","patch","post","put"]),Jo=new Set(["handler","stream"]),ei=new Set(["runAction","runMutation"]),ti=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Y=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,Jt=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if((s.getPropertyNameNode()?.getText()??s.getNameNode().getText())===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},Et=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:Jt(s,"ctx")},St=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:Jt(s,"request")},yt=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(ei.has(a)&&Y(c,t))return a;if(ti.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&Y(c.getExpression(),t))return`db.${a}`}},At=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Y(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Y(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},si=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ni=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Y(n.getExpression(),t)},ri=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],es=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:ri(s)},oi=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?es(t,a.getText()):[]}return[]},ii=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=es(s,t.getText());return n.length>0?n:oi(t,s)},Nt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>ni(o,t)&&ii(o).some(r=>si.test(r)))},ai=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Jo.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(Zo.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},ci=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=G(e.getArguments()[0]),u=c&&Et(c,!0);if(!c||u===void 0||Nt(c,St(c,!0)))return;const d=yt(c,u);return d===void 0?void 0:{exportName:S(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:At(c,u),sideEffect:d}}const n=ai(e);if(n===void 0)return;const o=G(e.getArguments()[0]),r=o&&Et(o,!1);if(!o||r===void 0||Nt(o,St(o,!1)))return;const a=yt(o,r);return a===void 0?void 0:{exportName:S(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:At(o,r),sideEffect:a}},li=(e,t)=>I(e,t,ci),ui=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),di=new Set(["append","set"]),ts=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",bt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>ui.has(y(n.getExpression())??"")&&gn(n,t)),fi=(e,t)=>{if(bt(e,t))return!0;const s=ue(e);return s!==void 0&&bt(s,t)},Ie=(e,t)=>fn(e,t)&&!fi(e,t),gi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=ue(e);return t!==void 0&&i.isNewExpression(t)&&y(t.getExpression())==="Headers"},oe=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=ue(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Re=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Ie(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:ts(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Ie(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=oe(n.getExpression());o!==void 0&&Re(o,t,s)}},ss=(e,t)=>{const s=oe(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=oe(n.getInitializer());o!==void 0&&Re(o,"response-init",t)},pi=(e,t)=>{const s=y(e.getExpression());if(s==="Response")ss(e.getArguments()[1],t);else if(s==="Headers"){const n=oe(e.getArguments()[0]);n!==void 0&&Re(n,"headers-ctor",t)}},mi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){ss(e.getArguments()[1],t);return}if(di.has(n)&&gi(o)){const r=e.getArguments()[1];r!==void 0&&Ie(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:ts(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},hi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))pi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))mi(s,t)},xi=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=G(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return hi(n,{exportName:S(e),relativePath:t,requestName:r.getText(),rows:a}),a},vi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...xi(n,t));return s},Ei=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vi(o,E(t,n)))}return s},Si=new Set(["auth","context.auth","ctx.auth"]),yi="userId",Ai=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Ni=(e,t)=>{const s=f(t,Ht);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(y(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Ai(r):void 0}},Pt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Si.has(e.getExpression().getText())?e:void 0},bi=e=>{if(i.isPropertyAccessExpression(e)&&Pt(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&Pt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Pi=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=bi(o);r!==void 0&&n.push({declared:r===yi||s.has(r),exportName:S(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Ii=(e,t)=>{const s=Ni(e,t);if(s===void 0)return[];const n=[];for(const o of h(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Pi(r,E(t,o),s))}return n},wi=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!L(n)||z(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber()}},Ti=(e,t)=>I(e,t,wi),Ci=new Set(["delete","get","getRaw","getWithMetadata","put"]),Fi=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return fe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Ci}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Oi=new Set(["queue","send"]),It=new Set(["bcc","cc","to"]),Ri=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Oi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Li=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return It.has(t.getName())&&L(n)&&!z(n)}if(!i.isPropertyAssignment(t)||!It.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&L(s)&&!z(s)}):!1,Di=(e,t)=>{const s=Ri(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Li(n)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},ki=(e,t)=>I(e,t,Di),Mi=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,_i=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Mi(e):!0,ns=(e,t=!1)=>{for(const s of e.getProperties()){if(_i(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||ns(n,!0))return!0}return!1},Ki=(e,t)=>{for(const s of h(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of Wt(n))for(const r of Ce(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||ns(a)))return!0}}return!1},zi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=re(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=re(a);c!==void 0&&s.push({column:c,strategy:Vt(a),table:o})}}return s},$i=(e,t)=>{const s=new Map;for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Wt(o))for(const a of Ce(r))for(const c of zi(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Ui=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=re(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=re(u);if(d===void 0)continue;const v=Vt(u);v!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:v,table:a})}}return o},qi=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?M(s):void 0;return n?.receiver?Ce(n.receiver).flatMap(o=>Ui(o,e.getName(),t)):[]},Bi=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...qi(c,r))}return s},Vi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return k(s)},Wi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ji=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Pn(s.getExpression())?s:void 0},Hi=e=>{const t=ji(e),s=t===void 0?void 0:Wi(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Vi(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Gi=e=>e.getVariableDeclarations().flatMap(t=>Hi(t)),Yi=(e,t)=>{const s=f(t,bn);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Gi(n)},Qi=new Set(["delete","get","patch"]),Xi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Zi=new Set(["auth","identity","session","user"]),Ji=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),ea=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!k(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},ta=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},sa=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),na=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,ra=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>sa(s.getExpression(),t)&&na(s.getThenStatement())),oa=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!Qi.has(o))continue;const r=n.getExpression();if(!(k(r)||i.isPropertyAccessExpression(r)&&k(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},ia=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},aa=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>ia(s)==="ctx")),ca=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Ji.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),la=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Xi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Zi.has(t.getName()))return!0}return aa(e)||ca(e)},ua=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=M(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=Zt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Bt(n.receiver,"use","rls"),a=la(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const v=ea(d);if(v===void 0)continue;const x=ta(d);if(x===void 0||c.has(x)||!ra(o,x))continue;const P=oa(o,x);P!==void 0&&(c.add(x),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:P,table:v,usesRls:r,visibility:n.visibility}))}return u},da=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ua(c,r))}return s},fa=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ga=new Set(["insert","insertManyUnsafe","patch","replace"]),pa=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ga.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},ma=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},ha=(e,t,s,n)=>{const o=[];for(const r of e.getProperties()){let a,c;i.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):i.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!fa.has(a))&&L(c)&&!z(c)&&o.push({exportName:S(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return o},xa=(e,t)=>{const s=pa(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?ma(n,s).flatMap(o=>ha(o,s,e,t)):[]},va=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of xa(o,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Ea=(e,t,s=[])=>{const n=[],o=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of h(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=E(t,r);n.push(...va(a,c,u=>o.get(`${c}:${u}`)))}return n},Sa=["providerSubscriptionId","state"],ya=["providerEventId","processedAt"],wt=(e,t)=>t.every(s=>s in e.shape),Aa=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&wt(t,Sa)&&wt(s,ya)},Na=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ba=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Pa=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ba(t.getInitializer()):void 0},Ia=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Na.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?Pa(n):void 0;return{callee:s,exportName:S(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},wa=(e,t)=>I(e,t,Ia),Ta=new Set(["defineQueue","defineWorkflow"]),Ca=new Set(["run","runAction","runMutation","runQuery"]),Fa=new Set(["api","internal"]),Oa=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Ra=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},rs=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},os=(e,t)=>e===t||e.startsWith(`${t}.`),is=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Tt=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},as=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Tt(s));return i.isIdentifier(e)&&Tt(e)&&t.push(e),t},La=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Da=e=>{const t=rs(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 o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ka=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Da(e),o=new Set,r=a=>is(a).some(c=>n.some(u=>os(c.getText(),u)))?!0:as(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of La(a))o.add(u)}return{names:o,prefixes:n}},Ma=(e,t)=>is(e).some(s=>t.prefixes.some(n=>os(s.getText(),n)))?!0:as(e).some(s=>t.names.has(s.getText())),_a=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!Fa.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Ka=(e,t,s)=>{const n=rs(e,0);if(n===void 0)return[];const o=ka(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Ca.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!Ma(u,o))continue;const d=_a(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:S(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},za=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Oa(n);if(o===void 0||!Ta.has(o))continue;const r=Ra(n);r!==void 0&&s.push(...Ka(r,o==="defineQueue"?"queue":"workflow",t))}return s},$a=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...za(o,E(t,n)))}return s},Ct={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Ft=new Set(["account","credential","member","passkey","session","user"]),Ua=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),qa=e=>{const s=Ua(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Ft.has(s)||Ft.has(n)},Ba=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Va=(e,t)=>{const{objects:s,opaque:n}=Oe(e,t);return $r(s).some(o=>Ba(o))?!0:n?void 0:!1},Wa=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},ja=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},ne={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Ha=e=>{const t=ja(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Wa(t);return{...ne,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ct?{...ne,[Ct[s]]:!0}:ne},Ga=e=>{const t={...ne};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=Ha(o);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},Ya=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Qa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ya.has(t.getName()))return!1;const s=t.getExpression();if(!k(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:qa(o.getLiteralText())},Xa=new Set(["create","runAfter","runAt","send","sendBatch"]),Za=new Set(["queues","scheduler","workflows"]),Ja=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Xa.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Za.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},ec=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return k(s)},cs=new Set(["generateObject","generateText","streamObject","streamText"]),tc=e=>{const t=y(e.getExpression());return t!==void 0&&cs.has(t)},sc=e=>{const t=y(e.getExpression());if(t===void 0||!cs.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},nc=new Set(["log","span","trace"]),rc=new Set(["ai"]),oc=new Set(["email","mail"]),ic=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),ye=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),ac=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),cc=new Set(["every","filter","flatMap","forEach","map","some"]),lc=new Set(["all","allSettled","race"]),uc=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(cc.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&lc.has(n))return t},dc=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ac.has(t.getKind())){const s=uc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},fc=e=>{let t=e;for(;;){const s=t.getParent();if(!i.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(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},gc=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},pc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!ic.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=gc(n);r&&(t=!0,!dc(r)&&!fc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},mc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Ot="lunora-advisor-exempt",hc=/^[\s*/]+/u,xc=/[\w-]/u,vc=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.`)},jn="env.ts",Hn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Gn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ue(n.getModuleSpecifierValue())}return!1},Yn=e=>{if(i.isIdentifier(e))return Hn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Gn(t)}return!1},Qn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Yn(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw le(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Xn=(e,t)=>{const s=E(t,jn);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=Qn(n);if(o.length!==0){if(o.length>1)throw le(n,`lunora/env.ts declares ${o.length.toString()} defineEnv() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},gt="ctx",Ht=e=>{const t=new Set,s=new Set([gt]),n=r=>{if(i.isObjectBindingPattern(r))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&t.add(c)}};for(const r of e.getDescendantsOfKind(l.BindingElement)){if((r.getPropertyNameNode()?.getText()??r.getName())!==gt)continue;const a=r.getNameNode();i.isIdentifier(a)?s.add(a.getText()):n(a)}const o=r=>i.isIdentifier(r)&&s.has(r.getText());for(const r of e.getDescendantsOfKind(l.PropertyAccessExpression))o(r.getExpression())&&t.add(r.getName());for(const r of e.getDescendantsOfKind(l.VariableDeclaration)){const a=r.getInitializer();a!==void 0&&o(a)&&n(r.getNameNode())}return t},Zn=(e,t)=>{const s=Object.fromEntries(ne.map(n=>[n.key,!1]));for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(o.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Ht(o);for(const c of ne)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(ne.every(c=>s[c.key]))break}return s},Gt="identity.ts",Jn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return ue(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},er=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ue(n.getModuleSpecifierValue())}return!1},tr=e=>{if(i.isIdentifier(e))return Jn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&er(t)}return!1},sr=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!tr(n.getExpression()))continue;const r=s.getNameNode();if(!i.isIdentifier(r))throw le(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},nr=(e,t)=>{const s=E(t,Gt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),o=sr(n);if(o.length!==0){if(o.length>1)throw le(n,`lunora/identity.ts declares ${o.length.toString()} defineIdentity() contracts (${o.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return o[0]}},rr=(e,t)=>{const s=G(t);if(s===void 0||!i.isIdentifier(s))return s;const n=s.getText();return G(e.getDescendantsOfKind(l.VariableDeclaration).find(o=>o.getName()===n)?.getInitializer())},or=e=>e!==void 0&&i.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!i.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||G(s)?.getText()!=="false"}),ir=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Ht(o).has("secrets")),s.durableStreams||(s.durableStreams=o.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(i.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>or(rr(o,u)))})),s.durableStreams&&s.secrets)break}return s},ar="createWorker",cr="extend",pt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralValue():void 0,mt=e=>{const t=[],s=pt(A(e,"backupCron"));s!==void 0&&t.push(s);const n=A(e,"crons");if(n===void 0||!i.isObjectLiteralExpression(n))return t;for(const o of n.getProperties()){if(!i.isPropertyAssignment(o)&&!i.isMethodDeclaration(o))continue;const r=pt(o.getNameNode());r!==void 0&&t.push(r)}return t},lr=e=>{const t=S(e.getExpression()),[s]=e.getArguments();if(s===void 0)return[];if(t===ar)return i.isObjectLiteralExpression(s)?mt(s):[];if(t!==cr||!(i.isArrowFunction(s)||i.isFunctionExpression(s)))return[];const n=Ut(s.getBody());return n===void 0?[]:mt(n)},ur=(e,t)=>{const s=[];for(const{filePath:n}of Oe(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression))s.push(...lr(r))}return[...new Set(s)]},Yt=e=>{if(e.kind==="id")return e.tableName;if(!(e.kind!=="array"&&e.kind!=="optional"))return e.inner===void 0?void 0:Yt(e.inner)},dr=e=>{const t=new Set(e.tables.map(s=>s.name));return e.tables.some(s=>Object.values(s.shape).some(n=>{const o=Yt(n);return o!==void 0&&t.has(o)}))},fr=(e,t)=>{const s=new Map,n=new Map,o=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),o.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=o.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})}},gr=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:o}=e,r=nr(s,t),a=Xn(s,t),c=on(s,t),u=tn(s,t),d=Gs(s,t);fr(c,d);const h=Ys(s,t),m=nn(s,t),P=Qs(s,t,c,d),M=ur(s,t),g=ir(s,t),T=sn(s,t),F=Zn(s,t);F.browser=F.browser||T.usesSandboxBrowser;const U=an(F,cn(n,e.target),{agents:d.length>0,commitOrderedTables:o.tables.some(N=>N.commitOrdered===!0),cronTriggers:P.length>0,crossShardFanout:o.tables.some(N=>typeof N.shardMode=="object"),durableStreams:g.durableStreams,globalTables:o.tables.some(N=>N.shardMode==="global"),queues:u.length>0,relationGraph:dr(o),secrets:g.secrets,vectorStore:o.vectorIndexes.length>0}),y=U.usage,O=U.signals.vectorStore!==!1,z=en(n),W=z??new Set,X=W.has("lunorash");Wn(o,z,{hasVectors:O,scheduler:y.scheduler||P.length>0,storage:y.storage||m.rules.length>0||Object.keys(Kt(o)).length>0,usage:y});const _=b(E(t,"flags.ts")),C=b(E(t,"notify.ts"));return{agents:d,containers:h,crons:P,dataModelContent:Ls(o),declaredDependencies:z,dependencies:W,entryCronTriggers:M,env:a,featureUsage:y,hasFlags:_,hasNotify:C,identity:r,platformGate:{...U,diagnostics:[...ln(n,e.target),...U.diagnostics]},queues:u,serverContent:Rs({agents:d,containers:h,env:a,hasAccessFacade:y.access,hasAi:y.ai,hasAnalytics:y.analytics,hasBrowser:y.browser,hasVectors:O,hasFlags:_,hasHyperdrive:y.hyperdrive,hasImages:y.images,hasKv:y.kv,hasNotify:C,hasPayments:y.payments,hasPipelines:y.pipelines,hasR2sql:y.r2sql,hasX402:y.x402,identity:r,queues:u,schema:o,storageRuleBuckets:m.rules.map(N=>N.bucket),useUmbrella:X,workflows:c}),storageRulesMetadata:m,usesSandbox:T.usesSandboxBrowser||T.usesSandboxContainer||T.usesSandboxFs,useUmbrella:X,workflows:c}},Qt=new Set(["delete","get","head","options","patch","post","put"]),pr=new Set(["handler","stream"]),mr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,ht=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),hr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Qt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!i.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},xr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||Qt.has(n.getName()))break;s=n.getExpression()}return hr(s)},vr=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(ht.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&ht.has(s.getText()))return!0}return!1},Er=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=s.getExpression();if(!i.isPropertyAccessExpression(n)||!pr.has(n.getName()))return;const o=xr(s);if(!o||!mr.test(o.path))return;const r=s.getArguments()[0],a=r!==void 0&&(i.isArrowFunction(r)||i.isFunctionExpression(r))&&vr(r);return{exportName:e.getName(),file:t,method:o.method,path:o.path,usesGuard:a}},Sr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Er(o,t);r&&s.push(r)}return s},yr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Sr(o,x(t,n)))}return s},Ar=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Nr=(e,t)=>{if(!Ar(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)||K(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},br=(e,t)=>w(e,t,Nr),Pr=new Set(["generateText","streamText"]),Ir=new Set(["messages","prompt","system"]),wr=[{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"]}],Tr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const o of wr)if(o.methods.has(s)&&o.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},Cr=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=Tr(t);if(s!==void 0)return s}},Fr=e=>{const t=new Set,s=e.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r)||i.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],o=n?.getNameNode();if(o===void 0||!i.isObjectBindingPattern(o))return t;for(const r of o.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},Or=e=>{if(un(e))return!0;const t=Fr(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},Rr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!Ir.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Or(s))return!0}return!1},Lr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());if(o===void 0||!Pr.has(o))continue;const[r]=n.getArguments();if(r===void 0||!i.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(S(c.getExpression())==="tool"&&(a=Cr(c),a!==void 0))break;a!==void 0&&s.push({exportName:v(n),file:t,line:n.getStartLineNumber(),method:o,sideEffect:a,userInputDerived:Rr(r)})}return s},Dr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Lr(o,x(t,n)))}return s},kr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},Mr=(e,t)=>{if(!kr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},_r=(e,t)=>w(e,t,Mr),Le=(e,t=new Set)=>{if(t.has(e))return!0;t.add(e);try{return e.getProperties().some(s=>{if(!i.isSpreadAssignment(s))return!1;const n=fe(s.getExpression());return n===void 0||Le(n,t)})}finally{t.delete(e)}},Kr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer(),o=n===void 0?void 0:fe(n);return o===void 0?{objects:[],opaque:!0}:{objects:[o],opaque:Le(o)}},zr=e=>{const t=[];let s=!1,n=e;for(;i.isCallExpression(n);){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))break;if(o.getName()==="input"){const r=n.getArguments()[0],a=r!==void 0&&i.isExpression(r)?fe(r):void 0;a===void 0?s=!0:(t.push(a),s||=Le(a))}n=o.getExpression()}return{objects:t,opaque:s}},De=(e,t)=>t?zr(t):Kr(e),Xt=(e,t)=>{if(t.has(e))return[];t.add(e);try{return e.getProperties().flatMap(s=>{if(i.isSpreadAssignment(s)){const n=fe(s.getExpression());return n===void 0?[]:Xt(n,t)}return i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)?[s.getName()]:[]})}finally{t.delete(e)}},$r=e=>e.flatMap(t=>Xt(t,new Set)),Ur=new Set(["check","length","max"]),Ie=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!(!i.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},qr=e=>[e,...e.getDescendants()].filter(t=>Ie(t)!==void 0),Br=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!i.isCallExpression(n)||n.getExpression()!==s)return!1;if(Ur.has(s.getName()))return!0;t=n}},Vr=e=>{const t=[],s=[];for(const n of e)for(const o of n.getProperties()){if(!i.isPropertyAssignment(o))continue;const r=o.getInitializer();if(!r)continue;const a=qr(r),c=o.getName();a.some(u=>Ie(u)==="any")?t.push(c):a.some(u=>Ie(u)==="string"&&!Br(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Wr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=k(s);if(n?.visibility!=="public")return;const{objects:o}=De(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=Vr(o);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},jr=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Wr(o,t);r&&s.push(r)}return s},Hr=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...jr(o,x(t,n)))}return s},Ae=e=>e?.getKind()===l.TrueKeyword,Gr=e=>e?.getKind()===l.FalseKeyword,Yr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Qr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Xr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),Zr=e=>e!==void 0&&i.isCallExpression(e)&&Qr.has(S(e.getExpression())??""),Jr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),eo=e=>{const t=A(e,"advanced"),s=A(e,"emailAndPassword"),n=A(e,"session");return{analyzable:!0,disableCsrfCheck:Ae(A(t,"disableCSRFCheck")),emailPasswordEnabled:Ae(A(s,"enabled")),requireEmailVerification:Ae(A(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Xr(A(e,"plugins"))&&Zr(A(e,"database")),secureCookiesDisabled:Gr(A(t,"useSecureCookies")),sessionFreshAgeZero:Yr(A(n,"freshAge")),trustedOriginsWildcard:Jr(A(e,"trustedOrigins"))}},to=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),so=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(r=>i.isSpreadAssignment(r)),o=s!==void 0&&i.isObjectLiteralExpression(s)&&!n?eo(s):to();return{exportName:v(e),file:t,line:e.getStartLineNumber(),...o}},no=(e,t)=>Xs(e,t,so),ro=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},oo=(e,t,s)=>{const n=ro(e.getExpression(),s);if(n===void 0)return;const o=e.getArguments()[s.argIndex];if(!(!o||!R(o)||K(o))&&!(s.requireUnmodifiedReach===!0&&!dn(o)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:n}},io=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression)){const r=oo(o,t,s);r&&n.push(r)}return n},ge=(e,t,s)=>{const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...io(r,x(t,o),s))}return n},ao=new Set(["content","pdf","scrape","screenshot"]),co=(e,t)=>ge(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:ao}),lo=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),uo=new Set(["RateLimiter"]),fo=new Set(["extend"]),xt="lunora",go=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Zt=e=>{const t=[],s=[];let n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),o.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},we=e=>e&&i.isObjectLiteralExpression(e)?Zt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},po=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&Ut(t.getBody());return s?Zt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},mo=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=S(n.getExpression());o!==void 0&&(lo.has(o)?s.push({callee:o,file:t,line:n.getStartLineNumber(),...we(n.getArguments()[0])}):fo.has(o)&&s.push({callee:o,file:t,line:n.getStartLineNumber(),...po(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const o=S(n.getExpression());o===void 0||!uo.has(o)||s.push({callee:o,file:t,line:n.getStartLineNumber(),...we(n.getArguments()[0])})}return s},ho=(e,t)=>{for(const s of go){const n=E(t,s);if(!b(n))continue;const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of o.getDescendantsOfKind(l.CallExpression))S(a.getExpression())===xt&&r.push({callee:xt,file:s,line:a.getStartLineNumber(),...we(a.getArguments()[0])});return r}return[]},xo=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Oe(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);s.push(...mo(r,n))}return s.push(...ho(e,se(t))),s},vt="ctx.containers.",vo=e=>{if(!e.startsWith(vt))return!1;const t=e.slice(vt.length);return t.length>0&&!t.includes(".")},Eo=(e,t)=>ge(e,t,{argIndex:0,matchReceiver:vo,methods:new Set(["get"])}),So=new Set(["allow","deny","setAllowed"]),yo=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},Ao=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!yo(e)))return{detail:"enableInternet: true",exportName:v(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},No=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!So.has(s.getName()))return;const n=s.getExpression();if(!(!i.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:v(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},bo=(e,t)=>Ao(e,t)??No(e,t),Po=(e,t)=>w(e,t,bo),Io=new Set(["defineExportSink","r2Sink","webhookExportSink"]),wo=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Io.has(s)?s:void 0},To=e=>{const t=[],s=[];for(const n of e.getProperties()){if(i.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o);const r=n.getInitializer();r&&i.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n)||i.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Co=(e,t)=>{const s=[];for(const{displayPath:n,filePath:o}of Oe(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=wo(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&i.isObjectLiteralExpression(u)?To(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},Fo=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),Oo=new Set(["dbRateLimit","rateLimit"]),Ro=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},Lo=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const n=Fo.get(s);if(n!==void 0)return{callee:s,exportName:v(e),failOpen:Ro(e.getArguments()[n]),file:t,limitName:Oo.has(s)?qt(e):"",line:e.getStartLineNumber()}},Do=(e,t)=>w(e,t,Lo),ko=new Set(["boolean","number","object","string"]),Mo=e=>{const t=e.getName();if(!ko.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&Pe(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&i.isPropertyAccessExpression(n)&&n.getName()==="flags"&&Pe(n.getExpression()))return t},_o=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=Mo(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(i.isStringLiteral(n)||i.isNoSubstitutionTemplateLiteral(n)))return;const o=n.getLiteralValue();return o.length>0?{key:o,type:s}:void 0},Ko=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getDescendantsOfKind(l.CallExpression)){const a=_o(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,o])=>({key:n,type:o})).toSorted((n,o)=>n.key.localeCompare(o.key))},zo=e=>{const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const s=k(t);if(s?.kind!=="query")return;const n=Zs(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},Et=e=>{const t=e.getParent();return t&&i.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},$o=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!i.isIdentifier(t)||t.getText()!=="ctx")return;const s=Et(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=Et(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},Uo=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const o=$o(n);o!==void 0&&s.push({callee:o,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},qo=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=zo(o);r&&s.push(...Uo(r,t))}return s},Bo=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...qo(o,x(t,n)))}return s},Vo=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Pe(t.getExpression())},Wo=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},jo=(e,t)=>{if(!Vo(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const o=s.getLiteralValue(),r=Wo(n);if(!(o.length===0||r===void 0))return{defaultValue:r,exportName:v(e),file:t,key:o,line:e.getStartLineNumber()}},Ho=(e,t)=>w(e,t,jo),Go=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 o=n.getTypeAtLocation(e),r=o.getText(e);if(!r||r==="any"||r==="never"||xn(r))return;const a=e.getSourceFile().getFilePath();return vn(o,e,a)?En(o,e,a,0,new Set):r},Yo=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Qo=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Xo=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression))Yo(a)&&s.push({file:r,indexName:Qo(a),line:a.getStartLineNumber()})}return s},Y=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,Jt=e=>{const t=e.getArguments()[0],s=Y(t);if(s!==void 0)return s;if(t===void 0||!i.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&i.isPropertyAssignment(n)?Y(n.getInitializer()):void 0},Zo=new Set(["delete","get","head","options","patch","post","put"]),Jo=new Set(["handler","stream"]),ei=new Set(["runAction","runMutation"]),ti=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),Q=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,es=(e,t)=>{if(!(e===void 0||!i.isObjectBindingPattern(e))){for(const s of e.getElements())if((s.getPropertyNameNode()?.getText()??s.getNameNode().getText())===t){const o=s.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},St=(e,t)=>{const s=e.getParameters()[0]?.getNameNode();if(s!==void 0)return t?i.isIdentifier(s)?s.getText():void 0:es(s,"ctx")},yt=(e,t)=>{const s=e.getParameters()[t?1:0]?.getNameNode();return t?s!==void 0&&i.isIdentifier(s)?s.getText():void 0:es(s,"request")},At=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);i.isCallExpression(s)&&n.unshift(s);for(const o of n){const r=o.getExpression();if(!i.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(ei.has(a)&&Q(c,t))return a;if(ti.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&Q(c.getExpression(),t))return`db.${a}`}},Nt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&Q(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const o=n.getNameNode();if(!(!i.isObjectBindingPattern(o)||!Q(n.getInitializer(),t))){for(const r of o.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},si=/signature|hmac|digest|(?:^|[_-])sig(?:[_-]|$)/i,ni=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="get"&&s.getName()!=="has")return!1;const n=s.getExpression();return i.isPropertyAccessExpression(n)&&n.getName()==="headers"&&Q(n.getExpression(),t)},ri=e=>[...i.isStringLiteral(e)?[e.getLiteralText()]:[],...e.getDescendantsOfKind(l.StringLiteral).map(t=>t.getLiteralText())],ts=(e,t)=>{const s=e.getVariableDeclaration(t)?.getInitializer();return s===void 0?[]:ri(s)},oi=(e,t)=>{const s=e.getText();for(let n=e.getParent();n!==void 0;n=n.getParent()){if(!i.isArrowFunction(n)&&!i.isFunctionExpression(n)||!n.getParameters().some(c=>c.getName()===s))continue;const o=n.getParent();if(!i.isCallExpression(o))return[];const r=o.getExpression();if(!i.isPropertyAccessExpression(r))return[];const a=r.getExpression();return i.isIdentifier(a)?ts(t,a.getText()):[]}return[]},ii=e=>{const t=e.getArguments()[0];if(t===void 0)return[];if(i.isStringLiteral(t))return[t.getLiteralText()];if(!i.isIdentifier(t))return[];const s=e.getSourceFile(),n=ts(s,t.getText());return n.length>0?n:oi(t,s)},bt=(e,t)=>{if(t===void 0)return!1;const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);return i.isCallExpression(s)&&n.unshift(s),n.some(o=>ni(o,t)&&ii(o).some(r=>si.test(r)))},ai=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Jo.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))return;const o=n.getName();if(Zo.has(o)){const r=n.getExpression();return i.isIdentifier(r)&&r.getText()==="httpRoute"?o.toUpperCase():void 0}s=n.getExpression()}},ci=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=Y(e.getArguments()[0]),u=c&&St(c,!0);if(!c||u===void 0||bt(c,yt(c,!0)))return;const d=At(c,u);return d===void 0?void 0:{exportName:v(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:Nt(c,u),sideEffect:d}}const n=ai(e);if(n===void 0)return;const o=Y(e.getArguments()[0]),r=o&&St(o,!1);if(!o||r===void 0||bt(o,yt(o,!1)))return;const a=At(o,r);return a===void 0?void 0:{exportName:v(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:Nt(o,r),sideEffect:a}},li=(e,t)=>w(e,t,ci),ui=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),di=new Set(["append","set"]),ss=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",Pt=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>ui.has(S(n.getExpression())??"")&&gn(n,t)),fi=(e,t)=>{if(Pt(e,t))return!0;const s=de(e);return s!==void 0&&Pt(s,t)},Te=(e,t)=>fn(e,t)&&!fi(e,t),gi=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=de(e);return t!==void 0&&i.isNewExpression(t)&&S(t.getExpression())==="Headers"},ie=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=de(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},ke=(e,t,s)=>{for(const n of e.getProperties())if(i.isPropertyAssignment(n)){const o=n.getInitializer();o!==void 0&&Te(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:ss(n.getNameNode()),line:o.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(n)){const o=n.getNameNode();Te(o,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:o.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(n)){const o=ie(n.getExpression());o!==void 0&&ke(o,t,s)}},ns=(e,t)=>{const s=ie(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!i.isPropertyAssignment(n))return;const o=ie(n.getInitializer());o!==void 0&&ke(o,"response-init",t)},pi=(e,t)=>{const s=S(e.getExpression());if(s==="Response")ns(e.getArguments()[1],t);else if(s==="Headers"){const n=ie(e.getArguments()[0]);n!==void 0&&ke(n,"headers-ctor",t)}},mi=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName(),o=s.getExpression();if(n==="json"&&i.isIdentifier(o)&&o.getText()==="Response"){ns(e.getArguments()[1],t);return}if(di.has(n)&&gi(o)){const r=e.getArguments()[1];r!==void 0&&Te(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:ss(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},hi=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))pi(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))mi(s,t)},xi=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=Y(e.getArguments()[0]);if(n===void 0)return[];const o=n.getParameters()[1];if(o===void 0)return[];const r=o.getNameNode();if(!i.isIdentifier(r))return[];const a=[];return hi(n,{exportName:v(e),relativePath:t,requestName:r.getText(),rows:a}),a},vi=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...xi(n,t));return s},Ei=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vi(o,x(t,n)))}return s},Si=new Set(["auth","context.auth","ctx.auth"]),yi="userId",Ai=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Ni=(e,t)=>{const s=E(t,Gt);if(!b(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const o of n.getDescendantsOfKind(l.CallExpression)){if(S(o.getExpression())!=="defineIdentity")continue;const[r]=o.getArguments();return r&&i.isObjectLiteralExpression(r)?Ai(r):void 0}},It=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Si.has(e.getExpression().getText())?e:void 0},bi=e=>{if(i.isPropertyAccessExpression(e)&&It(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&It(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Pi=(e,t,s)=>{const n=[];for(const o of e.getDescendants()){const r=bi(o);r!==void 0&&n.push({declared:r===yi||s.has(r),exportName:v(o),file:t,key:r,line:o.getStartLineNumber()})}return n},Ii=(e,t)=>{const s=Ni(e,t);if(s===void 0)return[];const n=[];for(const o of p(t)){const r=e.getSourceFile(o)??e.addSourceFileAtPath(o);n.push(...Pi(r,x(t,o),s))}return n},wi=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=A(s,"key");if(!(!n||!R(n)||K(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber()}},Ti=(e,t)=>w(e,t,wi),Ci=new Set(["delete","get","getRaw","getWithMetadata","put"]),Fi=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return ge(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:Ci}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Oi=new Set(["queue","send"]),wt=new Set(["bcc","cc","to"]),Ri=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Oi.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Li=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return wt.has(t.getName())&&R(n)&&!K(n)}if(!i.isPropertyAssignment(t)||!wt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&R(s)&&!K(s)}):!1,Di=(e,t)=>{const s=Ri(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!Li(n)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},ki=(e,t)=>w(e,t,Di),Mi=e=>i.isPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?i.isComputedPropertyName(e.getNameNode()):!1,_i=e=>i.isPropertyAssignment(e)||i.isShorthandPropertyAssignment(e)||i.isMethodDeclaration(e)||i.isGetAccessorDeclaration(e)?Mi(e):!0,rs=(e,t=!1)=>{for(const s of e.getProperties()){if(_i(s))return!0;if(t)continue;if(!i.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!i.isObjectLiteralExpression(n)||rs(n,!0))return!0}return!1},Ki=(e,t)=>{for(const s of p(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:o}of jt(n))for(const r of Re(o)){const a=r.getArguments()[0];if(a!==void 0&&(!i.isObjectLiteralExpression(a)||rs(a)))return!0}}return!1},zi=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const o=oe(n);if(o===void 0||!i.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!i.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=oe(a);c!==void 0&&s.push({column:c,strategy:Wt(a),table:o})}}return s},$i=(e,t)=>{const s=new Map;for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of jt(o))for(const a of Re(r))for(const c of zi(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},Ui=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){const a=oe(r);if(a===void 0||!i.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!i.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=oe(u);if(d===void 0)continue;const h=Wt(u);h!=="custom"&&o.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:h,table:a})}}return o},qi=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?k(s):void 0;return n?.receiver?Re(n.receiver).flatMap(o=>Ui(o,e.getName(),t)):[]},Bi=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...qi(c,r))}return s},Vi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return D(s)},Wi=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ji=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return Pn(s.getExpression())?s:void 0},Hi=e=>{const t=ji(e),s=t===void 0?void 0:Wi(t);if(s===void 0)return[];const n=e.getNameNode(),o=i.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>Vi(r)).map(r=>({exportName:o,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},Gi=e=>e.getVariableDeclarations().flatMap(t=>Hi(t)),Yi=(e,t)=>{const s=E(t,bn);if(!b(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return Gi(n)},Qi=new Set(["delete","get","patch"]),Xi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Zi=new Set(["auth","identity","session","user"]),Ji=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),ea=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!D(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},ta=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const n=s.getNameNode();return i.isIdentifier(n)?n.getText():void 0},sa=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),na=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,ra=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>sa(s.getExpression(),t)&&na(s.getThenStatement())),oa=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))continue;const o=n.getName();if(!Qi.has(o))continue;const r=n.getExpression();if(!(D(r)||i.isPropertyAccessExpression(r)&&D(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&i.isIdentifier(c)&&c.getText()===t)return o}},ia=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},aa=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>ia(s)==="ctx")),ca=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Ji.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),la=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(Xi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Zi.has(t.getName()))return!0}return aa(e)||ca(e)},ua=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=k(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const o=Jt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&Vt(n.receiver,"use","rls"),a=la(o),c=new Set,u=[];for(const d of o.getDescendantsOfKind(l.CallExpression)){const h=ea(d);if(h===void 0)continue;const m=ta(d);if(m===void 0||c.has(m)||!ra(o,m))continue;const P=oa(o,m);P!==void 0&&(c.add(m),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:P,table:h,usesRls:r,visibility:n.visibility}))}return u},da=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ua(c,r))}return s},fa=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ga=new Set(["insert","insertManyUnsafe","patch","replace"]),pa=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ga.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},ma=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())i.isObjectLiteralExpression(n)&&s.push(n);return s},ha=(e,t,s,n)=>{const o=[];for(const r of e.getProperties()){let a,c;i.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):i.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!fa.has(a))&&R(c)&&!K(c)&&o.push({exportName:v(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return o},xa=(e,t)=>{const s=pa(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?ma(n,s).flatMap(o=>ha(o,s,e,t)):[]},va=(e,t,s)=>{const n=[];for(const o of e.getDescendantsOfKind(l.CallExpression))for(const r of xa(o,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Ea=(e,t,s=[])=>{const n=[],o=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of p(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=x(t,r);n.push(...va(a,c,u=>o.get(`${c}:${u}`)))}return n},Sa=["providerSubscriptionId","state"],ya=["providerEventId","processedAt"],Tt=(e,t)=>t.every(s=>s in e.shape),Aa=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&Tt(t,Sa)&&Tt(s,ya)},Na=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),ba=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Pa=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?ba(t.getInitializer()):void 0},Ia=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!Na.has(s))return;const[n]=e.getArguments(),o=n&&i.isObjectLiteralExpression(n)?Pa(n):void 0;return{callee:s,exportName:v(e),file:t,line:e.getStartLineNumber(),...o===void 0?{}:{toleranceSeconds:o}}},wa=(e,t)=>w(e,t,Ia),Ta=new Set(["defineQueue","defineWorkflow"]),Ca=new Set(["run","runAction","runMutation","runQuery"]),Fa=new Set(["api","internal"]),Oa=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Ra=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(i.isArrowFunction(n)||i.isFunctionExpression(n)))return n},os=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},is=(e,t)=>e===t||e.startsWith(`${t}.`),as=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},Ct=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},cs=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>Ct(s));return i.isIdentifier(e)&&Ct(e)&&t.push(e),t},La=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},Da=e=>{const t=os(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 o=n.getInitializer(),r=i.isVariableDeclarationList(o)?o.getDeclarations()[0]?.getNameNode():void 0;r&&i.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ka=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:Da(e),o=new Set,r=a=>as(a).some(c=>n.some(u=>is(c.getText(),u)))?!0:cs(a).some(c=>o.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of La(a))o.add(u)}return{names:o,prefixes:n}},Ma=(e,t)=>as(e).some(s=>t.prefixes.some(n=>is(s.getText(),n)))?!0:cs(e).some(s=>t.names.has(s.getText())),_a=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!i.isIdentifier(s)||!Fa.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},Ka=(e,t,s)=>{const n=os(e,0);if(n===void 0)return[];const o=ka(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Ca.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!Ma(u,o))continue;const d=_a(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},za=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Oa(n);if(o===void 0||!Ta.has(o))continue;const r=Ra(n);r!==void 0&&s.push(...Ka(r,o==="defineQueue"?"queue":"workflow",t))}return s},$a=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...za(o,x(t,n)))}return s},Ft={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Ot=new Set(["account","credential","member","passkey","session","user"]),Ua=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),qa=e=>{const s=Ua(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Ot.has(s)||Ot.has(n)},Ba=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Va=(e,t)=>{const{objects:s,opaque:n}=De(e,t);return $r(s).some(o=>Ba(o))?!0:n?void 0:!1},Wa=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},ja=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&i.isCallExpression(s)?s:void 0},re={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Ha=e=>{const t=ja(e),s=t?S(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Wa(t);return{...re,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in Ft?{...re,[Ft[s]]:!0}:re},Ga=e=>{const t={...re};let s=e;for(;i.isCallExpression(s);){const n=s.getExpression();if(!i.isPropertyAccessExpression(n))break;const o=n.getName()==="use"?s.getArguments()[0]:void 0;if(o){const r=Ha(o);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},Ya=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Qa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Ya.has(t.getName()))return!1;const s=t.getExpression();if(!D(s))return!1;const o=e.getArguments()[0];return!o||!(i.isStringLiteral(o)||i.isNoSubstitutionTemplateLiteral(o))?!1:qa(o.getLiteralText())},Xa=new Set(["create","runAfter","runAt","send","sendBatch"]),Za=new Set(["queues","scheduler","workflows"]),Ja=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Xa.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Za.has(s.getName())){const n=s.getExpression();if(i.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},ec=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return D(s)},ls=new Set(["generateObject","generateText","streamObject","streamText"]),tc=e=>{const t=S(e.getExpression());return t!==void 0&&ls.has(t)},sc=e=>{const t=S(e.getExpression());if(t===void 0||!ls.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(n=>i.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},nc=new Set(["log","span","trace"]),rc=new Set(["ai"]),oc=new Set(["email","mail"]),ic=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),Ne=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="ctx"}),ac=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),cc=new Set(["every","filter","flatMap","forEach","map","some"]),lc=new Set(["all","allSettled","race"]),uc=e=>{const t=e.getParent();if(!t||!i.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;const n=s.getName();if(cc.has(n))return t;const o=s.getExpression();if(i.isIdentifier(o)&&o.getText()==="Promise"&&lc.has(n))return t},dc=e=>{let t=e.getParent();for(;t;){if(i.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(ac.has(t.getKind())){const s=uc(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},fc=e=>{let t=e;for(;;){const s=t.getParent();if(!i.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(!i.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},gc=e=>{let t=e;for(;;){const s=t.getParent();if(i.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return i.isCallExpression(s)&&s.getExpression()===t?s:void 0}},pc=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!ic.has(n.getName()))continue;const o=n.getExpression();if(!i.isIdentifier(o)||o.getText()!=="ctx")continue;const r=gc(n);r&&(t=!0,!dc(r)&&!fc(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},mc=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const n=s.getExpression();return i.isIdentifier(n)&&n.getText()==="Error"}),Rt="lunora-advisor-exempt",hc=/^[\s*/]+/u,xc=/[\w-]/u,vc=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
|
|
6
6
|
`);for(const n of s.split(`
|
|
7
|
-
`)){const o=n.replace(hc,"");if(!o.startsWith(Ot))continue;const r=o.slice(Ot.length);if(xc.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:""}},Ec=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Sc=(e,t)=>{const s=Ec(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},yc=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Qa(u)&&(r=!0),Ja(u)&&(t=!0),ec(u)&&(o=!0),tc(u)&&(s=!0),sc(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=pc(e);return{callsMail:ye(e,oc),emitsEvent:ye(e,nc),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||ye(e,rc),throwsBareError:mc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},Ac=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=M(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?Ga(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Sc(e,s);return{...r?yc(r):{},...vc(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:Va(s,n.receiver),kind:n.kind,visibility:n.visibility}},Nc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Ac(o,t);r&&s.push(r)}return s},bc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Nc(o,E(t,n)))}return s},Pc=new Set(["dbRateLimit","rateLimit"]),Ic=e=>i.isArrowFunction(e)?e.getBody():e,wc=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Pc.has(s))return;const n=e.getArguments()[2];if(!n)return;const o=N(n,"key");if(!o)return;const r=Ic(o);if(!(!L(r)||z(r)))return{callee:s,exportName:S(e),file:t,limitName:Ut(e),line:e.getStartLineNumber()}},Tc=(e,t)=>I(e,t,wc),Cc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Fc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Cc.has(t.getName()))return;const s=t.getExpression();if(k(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&k(s.getExpression()))return s.getName()},Oc=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&k(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Rc=e=>{let t=H(e)??e;for(;i.isAwaitExpression(t);)t=H(t.getExpression())??t.getExpression();return t},ls=(e,t=!1)=>{const s=Rc(e);if(i.isIdentifier(s)){if(t)return;const n=ue(s);return n===void 0?void 0:ls(n,!0)}if(i.isCallExpression(s))return Fc(s)??Oc(s)},Lc=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Dc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=M(s);if(n?.kind!=="query")return[];const o=Zt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&rn(n.receiver,"output"),a=n.receiver!==void 0&&Bt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Lc(o)){const v=ls(d);v===void 0||c.has(v)||(c.add(v),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:v,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},kc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Dc(c,r))}return s},Mc=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},_c=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?M(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=qt(r);if(a===void 0)continue;const c=Mc(N(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},Kc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(..._c(c,r))}return s},ie=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ie(e.getLeft()),s=ie(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},zc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ie(t)!==void 0},$c=/(?:^|\/)__tests__\//u,Uc=/\.(?:spec|test)$/u,qc=e=>$c.test(e)||Uc.test(e),Bc=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Vc=(e,t,s)=>kn(e)?!qc(s)&&Mn(Bc(t)):!0,Wc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(zc(r))continue;const a=ie(r);if(a===void 0)continue;const c=Ln(a);if(c===void 0||!Vc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:Dn(a)}))}return s},jc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Wc(o,E(t,n)))}return s},Hc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?M(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=qt(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&L(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},Gc=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Hc(c,r))}return s},Yc=new Set(["query","unsafe"]),Qc=e=>{if(!i.isPropertyAccessExpression(e)||!Yc.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},Xc=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Zc=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Jc=(e,t)=>{if(!Qc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Xc(s)))return{exportName:Zc(e),file:t,line:s.getStartLineNumber()}},el=(e,t)=>I(e,t,Jc),tl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],sl=e=>{for(const[t,s]of tl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},nl=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=sl(a);c!==void 0&&s.push({file:E(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},rl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ol=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return fe(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:rl,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},il=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),al=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,cl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=al(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},ll=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=il.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},ul=(e,t)=>{const s=ll(e.getExpression());if(s!==void 0)return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s.method,...cl(e.getArguments()[s.optionsIndex])}},dl=(e,t)=>I(e,t,ul),fl=(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:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),gl=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),pl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return Oe(e,t).opaque},ml=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=M(a);c!==void 0&&pl(a,c.receiver)&&s.push(gl(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},hl=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...ml(o,E(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},xl=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),ge=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),us=e=>!e.isAny(),Le=e=>{const t=e.getType();if(!us(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:xl.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},ds=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},fs={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},vl=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),El={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."},De=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,v=d===void 0?o:vl(d),x=c===void 0?v.remediation:`${c} ${v.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${v.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${x}`:x,title:"Procedure exists at runtime but is missing from the generated API"}},Sl=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(ge(s,t,a)||!ds(r))continue;const c=Le(r);c!==void 0&&n.push(De(t,a,c,r.getStartLineNumber(),fs))}return n},yl=(e,t,s)=>{if(ge(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Le(o.getExpression());r!==void 0&&n.push(De(t,"default",r,o.getStartLineNumber(),fs))}return n},Al=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(ge(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!ds(c))continue;const u=Le(c);u!==void 0&&n.push(De(t,a,u,r.getStartLineNumber(),El))}return n},Nl=(e,t,s)=>[...Sl(e,t,s),...yl(e,t,s),...Al(e,t,s)],bl=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>ge(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Pl=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),Il=(e,t,s)=>{const n=[],o=[];for(const a of h(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=E(t,a);n.push(...Nl(c,u,s)),o.push(...bl(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!us(a.getType()))&&n.push(Pl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},wl=new Set(["when","where"]),Ae=new Set(["definePolicy","defineShape"]),Tl=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return Ae.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return Ae.has(o)?o:void 0}const s=t.getText();return Ae.has(s)?s:void 0},Cl=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,gs=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Cl(e))return"empty-object";if(i.isParenthesizedExpression(e))return gs(e.getExpression())}},ke=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Fl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>ke(t)===e),ps=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>ke(t)===e),Ol=e=>{const t=Fl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||ps(e).length>0},Rl=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>ke(t)===e),we=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",Ll=(e,t)=>we(e)||we(t),Dl=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Rt=e=>!we(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),kl=(e,t,s)=>{const n=Dl.get(e);if(n!==void 0)return Ll(t,s)?n==="positive"?"negative":"positive":Rt(t)||Rt(s)?void 0:n},j=e=>{if(i.isParenthesizedExpression(e))return j(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=kl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=j(e.getLeft()),o=j(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},Lt=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Ml=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},_l=e=>i.isReturnStatement(e)?e.getExpression()??e:e,Kl=e=>{const t=[];for(const s of ps(e)){const n=j(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Rl(e)){const n=j(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?Lt(s.getThenStatement()):Lt(s.getElseStatement())??Ml(s);o!==void 0&&t.push(_l(o))}return t},zl=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},$l=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!wl.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Ol(a))for(const c of Kl(a)){const u=gs(c);u!==void 0&&o.push({exportName:zl(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},Ul=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Tl(n);o!==void 0&&s.push(...$l(n,o,t))}return s},ql=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ul(o,E(t,n)))}return s},Bl=new Set(["query","upsert","upsertMany"]),Vl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Bl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Wl=(e,t)=>{const s=Vl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=N(n,"namespace");if(!(!o||!L(o)||z(o)))return{exportName:S(e),file:t,line:e.getStartLineNumber(),method:s}},jl=(e,t)=>I(e,t,Wl),Hl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Gl=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Yl=(e,t)=>{const s=[];for(const n of h(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=E(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Hl(a))continue;const c=Js(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Gl(a)})}}return s},Ql=".lunora-schema.json",w=(e,t)=>{b(e)&&Mt(e,"utf8")===t||Is(e,t,"utf8")},F=(e,t)=>{if(t===""){ws(e,{force:!0});return}w(e,t)},Xl=e=>{const t=f(e,"package.json");if(b(t))try{const s=JSON.parse(Mt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Zl=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},Jl=e=>{let t=b(e)?e:te(e);for(;t&&t!==te(t);){const s=f(t,"tsconfig.json");if(b(s))return s;t=te(t)}},Dt=e=>e.replaceAll("\\","/"),eu=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new D("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 o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)throw new D("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 D("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})}},ae=(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)},kt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,tu=8,su=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:v}=e;let x=ct(a,o),P=ut(a,o),_=lt(a,o);dt([...x,...P].map(p=>p.filePath)),dt(_.filter(p=>p.stream).map(p=>p.filePath),"http-stream");for(let p=1;;p+=1){const T=js({agents:t,functions:x,httpRoutes:_,mutators:P,useUmbrella:d,workflows:v}),O=Hs({agents:t,functions:x,migrations:r,mutators:P,shapes:c,useUmbrella:d,usesSandbox:u});if(p>=tu||kt(a,s,T)&&kt(a,n,O))return{apiContent:T,functions:x,functionsContent:O,httpRoutes:_,mutators:P};ae(a,s,T),ae(a,n,O),x=ct(a,o),P=ut(a,o),_=lt(a,o)}},nu=e=>{const t=Jl(e);return t?new at({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new at({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Zu=(e,t)=>{const s=h(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 o=new Set(s.map(c=>Dt(c))),r=Dt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.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)}}},Ju=e=>{const t=Zl(),s=t?Ee.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),o=f(n,"schema.ts");if(!b(o))throw new D("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??nu(n);mn(Go);const a=Rn(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:v,dependencies:x,entryCronTriggers:P,env:_,featureUsage:p,hasFlags:T,hasNotify:O,identity:U,platformGate:A,queues:R,serverContent:$,storageRulesMetadata:V,usesSandbox:Q,useUmbrella:K,workflows:C}=gr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),g=f(n,"_generated"),Me=f(g,"dataModel.ts"),_e=f(g,"server.ts"),ms=f(g,"api.ts"),hs=f(g,"functions.ts");ae(r,Me,v),ae(r,_e,$);const X=Nn(r,n),q=_n(r,n),{apiContent:Ke,functions:B,functionsContent:ze,httpRoutes:xs,mutators:$e}=su({agents:c,apiPath:ms,generatedFunctionsPath:hs,lunoraDirectory:n,migrations:X,project:r,shapes:q,useUmbrella:K,usesSandbox:Q,workflows:C}),Z=e.lint===!1?void 0:Fs({adminRoutes:yr(r,n),aiRawRuns:br(r,n),aiToolSideEffects:Dr(r,n),argumentDerivedFetches:_r(r,n),argumentValidators:Hr(r,n),authApiCalls:hn(r,n),authConfigs:no(r,n),browserUrlAccesses:co(r,n),configCalls:xo(r,n),containerKeyAccesses:Eo(r,n),containerOverrides:Po(r,n),containers:u,exportSinks:Co(r,n),staleMigrationImports:nl(r,n),failOpenGuards:Do(r,n),flagReads:Bo(r,n),flagSecurityDefaults:Ho(r,n),geoIndexUsages:Xo(r,n),httpActionGuards:li(r,n),httpHeaderWrites:Ei(r,n),hyperdriveCalls:Sn(r,n),identityClaimReads:Ii(r,n),imageDeliveryUrlAccesses:Ti(r,n),inserts:yn(r,n),kvKeyAccesses:Fi(r,n,B),mailRecipientAccesses:ki(r,n),maskProcedures:An(r,n),maskStrategies:Bi(r,n),mutatorWrites:Yi(r,n),nondeterministicCalls:In(r,n),normalizeIdAuthorizations:da(r,n),notifyCalls:Tn(r,n),notifyConfig:wn(r,n),ownerFieldWrites:Ea(r,n,B),unrestrictedWhereBranches:ql(r,n),paymentWebhooks:wa(r,n),privilegedDispatches:$a(r,n),procedureProtections:bc(r,n),queries:pn(r,n),queues:R,r2sqlCalls:Cn(r,n),ratelimitKeySelectors:Tc(r,n),rawRowReturns:kc(r,n),relationLoads:Kc(r,n),rlsProcedures:Fn(r,n),schema:a,secretLiterals:jc(r,n),shapes:q,softDeleteReads:Gc(r,n),sqlInterpolations:el(r,n),storageKeyAccesses:ol(r,n,B),storageUploads:dl(r,n),vectorNamespaceAccesses:jl(r,n),workflowCalls:Yl(r,n),workflows:C,wranglerVariables:e.wranglerVariables}),Ue=Z===void 0?[]:[...Ts(Z,{source:"static"}),...Il(r,n,{byName:new Set([...C,...R,...c,...u].map(m=>m.exportName)),byPath:new Set([...B,...$e,...q,...X].map(m=>`${m.filePath}:${m.exportName}`))}),...hl(r,n)],vs=On(r,n),qe=$i(r,n);eu(q,qe,Ki(r,n));const Es=T?Ko(r,n):[],pe=A.signals.vectorStore!==!1,W=fl(p,{containerCount:u.length,cronCount:d.length,dependencies:x,hasPaymentTables:Aa(a.tables),queueCount:R.length,storageColumnCount:Object.keys(_t(a)).length,storageRuleCount:V.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:pe,workflowCount:C.length}),Be=t?Ee.now():0,me=Bn(a,X.map(m=>m.id)),Ve=Ds({advisories:Ue.filter(m=>m.name!=="procedure_type_check_unavailable"),advisorProcedures:Z?.procedureProtections??[],agents:c,containers:u,env:_,flagKeys:Es,hasAccessFacade:p.access,hasAi:p.ai,hasAnalytics:p.analytics,hasBrowser:p.browser,hasFlags:T,hasHyperdrive:p.hyperdrive,hasImages:p.images,hasKv:p.kv,hasNotify:O,hasPayments:p.payments,hasPipelines:p.pipelines,hasR2sql:p.r2sql,hasVectors:pe,hasX402:p.x402,maskMetadata:qe,mutators:$e,queues:R,rlsMetadata:vs,schema:a,schemaSnapshot:me,shapes:q,storageRules:V,studioFeatures:W,useUmbrella:K,workflows:C}),We=ks(q,x.has("@lunora/db"),K),je=Ms(u,a.jurisdiction),He=_s(C),Ge=Ks(c),Ye=zs(R),Qe=$s(d),Ss=Us(W.scheduler),Xe=qs(a.vectorIndexes),J=Bs(a,K),Ze=Vs(x.has("@lunora/seed")),ee=e.apiSpec??"openapi",he=ee==="openapi"||ee==="both",xe=ee==="openrpc"||ee==="both",Je=Kn({emailAgents:c.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:x.has("@lunora/cloudflare-access"),hasAi:p.ai,hasAnalytics:p.analytics,hasAuth:x.has("@lunora/auth"),hasBrowser:p.browser,hasFramework:x.has("@lunora/astro")||x.has("@lunora/svelte")||x.has("@lunora/vue"),hasGlobal:a.tables.some(m=>Kt(m)),hasHyperdrive:p.hyperdrive,hasHyperdriveGlobal:a.tables.some(m=>zt(m)),hasImages:p.images,hasKv:p.kv,hasKvIntrospector:W.kv,hasNotify:O,hasPayments:p.payments,hasR2sql:p.r2sql,hasQueue:R.some(m=>m.mode==="push"),hasScheduler:W.scheduler,hasStorage:W.storage,hasVectors:pe,hasWorkflow:C.length>0,hasX402:p.x402,identity:U,jurisdiction:a.jurisdiction,tableNames:a.tables.map(m=>m.name),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:he,wantsOpenRpc:xe}),et=Xl(e.projectRoot),tt=zn({functions:B,httpRoutes:xs,version:et}),st=Un({functions:B,version:et}),nt=`${JSON.stringify(tt,void 0,2)}
|
|
8
|
-
`,
|
|
9
|
-
`,
|
|
7
|
+
`)){const o=n.replace(hc,"");if(!o.startsWith(Rt))continue;const r=o.slice(Rt.length);if(xc.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:""}},Ec=e=>{const[t]=e.getArguments();if(t){if(i.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?i.isPropertyAssignment(s)?s.getInitializer():i.isShorthandPropertyAssignment(s)?s.getNameNode():i.isMethodDeclaration(s)?s:void 0:void 0}return t}},Sc=(e,t)=>{const s=Ec(t);if(!s)return;if(i.isArrowFunction(s)||i.isFunctionExpression(s)||i.isMethodDeclaration(s))return e;if(!i.isIdentifier(s))return;const n=s.getSourceFile(),o=s.getText(),r=n.getVariableDeclaration(o)?.getInitializer();return r&&(i.isArrowFunction(r)||i.isFunctionExpression(r))?r:n.getFunction(o)},yc=e=>{let t=!1,s=!1,n=!1,o=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Qa(u)&&(r=!0),Ja(u)&&(t=!0),ec(u)&&(o=!0),tc(u)&&(s=!0),sc(u)&&(n=!0),r&&t&&o&&n)break;const{handlesErrors:a,reachesOutbound:c}=pc(e);return{callsMail:Ne(e,oc),emitsEvent:Ne(e,nc),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||Ne(e,rc),throwsBareError:mc(e),unboundedAiGeneration:n,usesInsertManyUnsafe:o,writesUserTable:r}},Ac=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const n=k(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const o=n.receiver?Ga(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Sc(e,s);return{...r?yc(r):{},...vc(e),...o,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:Va(s,n.receiver),kind:n.kind,visibility:n.visibility}},Nc=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const o of n.getDeclarations()){const r=Ac(o,t);r&&s.push(r)}return s},bc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Nc(o,x(t,n)))}return s},Pc=new Set(["dbRateLimit","rateLimit"]),Ic=e=>i.isArrowFunction(e)?e.getBody():e,wc=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!Pc.has(s))return;const n=e.getArguments()[2];if(!n)return;const o=A(n,"key");if(!o)return;const r=Ic(o);if(!(!R(r)||K(r)))return{callee:s,exportName:v(e),file:t,limitName:qt(e),line:e.getStartLineNumber()}},Tc=(e,t)=>w(e,t,wc),Cc=new Set(["findFirst","findFirstOrThrow","findMany","findUnique","get"]),Fc=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Cc.has(t.getName()))return;const s=t.getExpression();if(D(s)){const n=e.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&D(s.getExpression()))return s.getName()},Oc=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&D(s.getExpression())){const n=t.getArguments()[0];return n&&i.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},Rc=e=>{let t=G(e)??e;for(;i.isAwaitExpression(t);)t=G(t.getExpression())??t.getExpression();return t},us=(e,t=!1)=>{const s=Rc(e);if(i.isIdentifier(s)){if(t)return;const n=de(s);return n===void 0?void 0:us(n,!0)}if(i.isCallExpression(s))return Fc(s)??Oc(s)},Lc=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const o=n.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),r=n.getExpression();o===e&&r!==void 0&&s.push(r)}return s},Dc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const n=k(s);if(n?.kind!=="query")return[];const o=Jt(s);if(o===void 0)return[];const r=n.receiver!==void 0&&rn(n.receiver,"output"),a=n.receiver!==void 0&&Vt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of Lc(o)){const h=us(d);h===void 0||c.has(h)||(c.add(h),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:h,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},kc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Dc(c,r))}return s},Mc=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},_c=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?k(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Bt(r);if(a===void 0)continue;const c=Mc(A(a.options,"with"));c.length!==0&&o.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return o},Kc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(..._c(c,r))}return s},ae=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=ae(e.getLeft()),s=ae(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},zc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&ae(t)!==void 0},$c=/(?:^|\/)__tests__\//u,Uc=/\.(?:spec|test)$/u,qc=e=>$c.test(e)||Uc.test(e),Bc=e=>{const t=e.getParent();if(t!==void 0){if(i.isVariableDeclaration(t)||i.isPropertyAssignment(t)||i.isPropertySignature(t))return t.getName();if(i.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},Vc=(e,t,s)=>kn(e)?!qc(s)&&Mn(Bc(t)):!0,Wc=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],o=new Set;for(const r of n){if(zc(r))continue;const a=ae(r);if(a===void 0)continue;const c=Ln(a);if(c===void 0||!Vc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;o.has(d)||(o.add(d),s.push({file:t,kind:c,line:u,preview:Dn(a)}))}return s},jc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Wc(o,x(t,n)))}return s},Hc=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&i.isCallExpression(s)?k(s):void 0;if(!n)return[];const o=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=Bt(r);if(a===void 0)continue;const c=A(a.options,"includeDeleted");if(c===void 0)continue;const u=i.isTrueLiteral(c),d=!u&&R(c);!u&&!d||o.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return o},Gc=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Hc(c,r))}return s},Yc=new Set(["query","unsafe"]),Qc=e=>{if(!i.isPropertyAccessExpression(e)||!Yc.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},Xc=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Zc=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Jc=(e,t)=>{if(!Qc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Xc(s)))return{exportName:Zc(e),file:t,line:s.getStartLineNumber()}},el=(e,t)=>w(e,t,Jc),tl=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],sl=e=>{for(const[t,s]of tl)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},nl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of o.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=sl(a);c!==void 0&&s.push({file:x(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},rl=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ol=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return ge(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:rl,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},il=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),al=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,cl=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const o of e.getProperties()){if(i.isSpreadAssignment(o)){n=!0;continue}if(i.isPropertyAssignment(o)){const r=o.getName();t.push(r),r==="expiresInSeconds"&&(s=al(o.getInitializer()));continue}(i.isShorthandPropertyAssignment(o)||i.isMethodDeclaration(o))&&t.push(o.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},ll=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=il.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},ul=(e,t)=>{const s=ll(e.getExpression());if(s!==void 0)return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s.method,...cl(e.getArguments()[s.optionsIndex])}},dl=(e,t)=>w(e,t,ul),fl=(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:t.vectorStoreSupported&&t.vectorIndexCount>0,workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),gl=(e,t,s)=>({cacheKey:`procedure_arguments_unreadable:${e}:${t}`,categories:["SCHEMA"],description:"Codegen reads an argument record statically. One built at runtime — a factory call, or a property off a value it cannot follow — has no literal to read, so the generated `FunctionReference` carries only the arguments it could see while the runtime validator still enforces all of them.",detail:`\`${t}\` in \`${e}\` (line ${s.toString()}) declares arguments codegen could not read, so its generated type is missing some of them.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:s},name:"procedure_arguments_unreadable",remediation:`Declare the arguments as an object literal, or as a \`const\` object literal the chain names — \`const ${t}Args = { … };\` then \`.input(${t}Args)\`. Both resolve; a record returned by a call does not.`,title:"Procedure arguments are missing from the generated type"}),pl=(e,t)=>{if(t===void 0){const s=e.getArguments()[0];if(s===void 0||!i.isObjectLiteralExpression(s)||s.getProperty("args")===void 0)return!1}return De(e,t).opaque},ml=(e,t)=>{const s=[],n=(o,r)=>{const a=o.getInitializer();if(a===void 0||!i.isCallExpression(a))return;const c=k(a);c!==void 0&&pl(a,c.receiver)&&s.push(gl(t,r,a.getStartLineNumber()))};for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations())n(r,r.getName());return s},hl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n);o!==void 0&&s.push(...ml(o,x(t,n)))}return s.toSorted((n,o)=>n.cacheKey.localeCompare(o.cacheKey))},xl=new Map([["AgentDefinition",{call:"defineAgent({ … })",file:"agents"}],["ContainerDefinition",{call:"defineContainer({ … })",file:"containers"}],["QueueDefinition",{call:"defineQueue({ … })",file:"queues",note:"A dropped queue has no caller to fail — its consumer is simply never wired."}],["RegisteredAction",{call:"action.input({ … }).action(handler)"}],["RegisteredLifecycleHook",{call:"onConnect(handler)",note:"Substitute the hook you called: `onConnect`, `onDisconnect` and `onShardInit` share one type, so codegen cannot tell which you wrote. A dropped hook has no caller to fail — it silently never fires."}],["RegisteredMigration",{call:"defineMigration({ … })",note:"A dropped migration never runs, so `lunora migrate up` reports nothing to do."}],["RegisteredMutation",{call:"mutation.input({ … }).mutation(handler)"}],["RegisteredMutator",{call:"defineMutator({ … })",file:"mutators"}],["RegisteredQuery",{call:"query.input({ … }).query(handler)"}],["RegisteredReactor",{call:"onQueryChange(select, handler)",note:"A dropped reactor has no caller to fail — it silently never runs."}],["RegisteredShape",{call:"defineShape({ … })",file:"shapes"}],["RegisteredStream",{call:"query.input({ … }).stream(handler)"}],["WorkflowDefinition",{call:"defineWorkflow({ … })",file:"workflows"}]]),pe=({byName:e,byPath:t},s,n)=>t.has(`${s}:${n}`)||e.has(n),ds=e=>!e.isAny(),Me=e=>{const t=e.getType();if(!ds(t))return;const s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName(),n=s===void 0?void 0:xl.get(s);return n===void 0||s===void 0?void 0:{...n,typeName:s}},fs=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},gs={cause:"codegen recognises a registration only when the initializer is the registering call itself, and this one comes from a factory or an alias",remediation:"A factory that returns a registration cannot be read statically — inline it, or export what the factory builds."},vl=e=>({cause:`codegen reads this kind of registration only from \`lunora/${e}.ts\`, and this is a different module`,remediation:`Move it into \`lunora/${e}.ts\` — the declaration itself is fine.`}),El={cause:"the binding is exported by a separate `export { … }` statement, and codegen reads the `export` keyword on the declaration itself",remediation:"Move the keyword onto the declaration and drop the separate export statement."},_e=(e,t,s,n,o)=>{const{call:r,file:a,note:c,typeName:u}=s,d=a!==void 0&&e!==a?a:void 0,h=d===void 0?o:vl(d),m=c===void 0?h.remediation:`${c} ${h.remediation}`;return{cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally the registering call. Written any other way it exists at runtime but never reaches the generated output — `_generated/api.ts` for a procedure, the lifecycle manifest for a hook or reactor — so a caller cannot address it and a hook never fires.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${u}\` but was not registered — ${h.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:u},name:"procedure_not_registered",remediation:d===void 0?`Assign the registration directly: \`export const ${t} = ${r};\`. ${m}`:m,title:"Procedure exists at runtime but is missing from the generated API"}},Sl=(e,t,s)=>{const n=[];for(const o of e.getVariableStatements().filter(r=>r.isExported()))for(const r of o.getDeclarations()){const a=r.getName();if(pe(s,t,a)||!fs(r))continue;const c=Me(r);c!==void 0&&n.push(_e(t,a,c,r.getStartLineNumber(),gs))}return n},yl=(e,t,s)=>{if(pe(s,t,"default"))return[];const n=[];for(const o of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Me(o.getExpression());r!==void 0&&n.push(_e(t,"default",r,o.getStartLineNumber(),gs))}return n},Al=(e,t,s)=>{const n=[];for(const o of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of o.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(pe(s,t,a))continue;const c=r.getLocalTargetDeclarations().find(d=>i.isVariableDeclaration(d));if(c===void 0||!fs(c))continue;const u=Me(c);u!==void 0&&n.push(_e(t,a,u,r.getStartLineNumber(),El))}return n},Nl=(e,t,s)=>[...Sl(e,t,s),...yl(e,t,s),...Al(e,t,s)],bl=(e,t,s)=>e.getVariableStatements().filter(n=>n.isExported()).flatMap(n=>n.getDeclarations()).filter(n=>pe(s,t,n.getName())).filter(n=>{const o=n.getInitializer();return o!==void 0&&i.isCallExpression(o)&&i.isPropertyAccessExpression(o.getExpression())}).map(n=>({declaration:n,exportName:n.getName(),relativePath:t})),Pl=({exportName:e,relativePath:t})=>({cacheKey:"procedure_type_check_unavailable",categories:["SCHEMA"],description:"Codegen cross-checks every export in `lunora/` against its TYPE to catch a procedure the syntactic scan dropped — a factory-assigned export, an alias, a separate `export { … }`. That check needs the type checker to resolve `@lunora/server`; when it cannot, the check reports nothing regardless of what the code does.",detail:`Type resolution for \`lunora/\` is unavailable — the registered procedure \`${e}\` in \`${t}\` types as \`any\`, as does every other one — so codegen cannot tell you when an export is dropped from \`_generated/api.ts\`. A dropped procedure will surface as \`Property '<name>' does not exist\` at its call site instead.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:e,filePath:t},name:"procedure_type_check_unavailable",remediation:`Check what codegen sees: \`${e}\` should have a procedure type, not \`any\`. It needs a \`tsconfig.json\` at or above \`lunora/\` — the one codegen finds walking up from there, which is not necessarily the one your editor uses — resolving \`lunorash\` / \`@lunora/server\` to declarations that exist on disk (a workspace dependency has to be built first).`,title:"Codegen cannot type-check `lunora/`, so dropped procedures go unreported"}),Il=(e,t,s)=>{const n=[],o=[];for(const a of p(t)){const c=e.getSourceFile(a);if(c===void 0)continue;const u=x(t,a);n.push(...Nl(c,u,s)),o.push(...bl(c,u,s))}const[r]=o;return r!==void 0&&o.every(({declaration:a})=>!ds(a.getType()))&&n.push(Pl(r)),n.toSorted((a,c)=>a.cacheKey.localeCompare(c.cacheKey))},wl=new Set(["when","where"]),be=new Set(["definePolicy","defineShape"]),Tl=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const n=t.getName();return be.has(n)?n:void 0}if(!i.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(n)){const o=n.getNameNode().getText();return be.has(o)?o:void 0}const s=t.getText();return be.has(s)?s:void 0},Cl=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,ps=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Cl(e))return"empty-object";if(i.isParenthesizedExpression(e))return ps(e.getExpression())}},Ke=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Fl=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Ke(t)===e),ms=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Ke(t)===e),Ol=e=>{const t=Fl(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||ms(e).length>0},Rl=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>Ke(t)===e),Ce=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||i.isIdentifier(e)&&e.getText()==="undefined"?!0:i.isNumericLiteral(e)?e.getLiteralValue()===0:i.isStringLiteral(e)&&e.getLiteralValue()==="",Ll=(e,t)=>Ce(e)||Ce(t),Dl=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),Lt=e=>!Ce(e)&&(i.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),kl=(e,t,s)=>{const n=Dl.get(e);if(n!==void 0)return Ll(t,s)?n==="positive"?"negative":"positive":Lt(t)||Lt(s)?void 0:n},H=e=>{if(i.isParenthesizedExpression(e))return H(e.getExpression());if(i.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(i.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=kl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=H(e.getLeft()),o=H(e.getRight());return n===o?n:"indeterminate"}}return i.isIdentifier(e)||i.isPropertyAccessExpression(e)||i.isElementAccessExpression(e)||i.isCallExpression(e)?"positive":"indeterminate"},Dt=e=>{if(e!==void 0){if(i.isReturnStatement(e))return e;if(i.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&i.isReturnStatement(t)?t:void 0}}},Ml=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},_l=e=>i.isReturnStatement(e)?e.getExpression()??e:e,Kl=e=>{const t=[];for(const s of ms(e)){const n=H(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Rl(e)){const n=H(s.getExpression());if(n==="indeterminate")continue;const o=n==="negative"?Dt(s.getThenStatement()):Dt(s.getElseStatement())??Ml(s);o!==void 0&&t.push(_l(o))}return t},zl=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},$l=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!i.isObjectLiteralExpression(n))return[];const o=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r)||!wl.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Ol(a))for(const c of Kl(a)){const u=ps(c);u!==void 0&&o.push({exportName:zl(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return o},Ul=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const o=Tl(n);o!==void 0&&s.push(...$l(n,o,t))}return s},ql=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ul(o,x(t,n)))}return s},Bl=new Set(["query","upsert","upsertMany"]),Vl=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Bl.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Wl=(e,t)=>{const s=Vl(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const o=A(n,"namespace");if(!(!o||!R(o)||K(o)))return{exportName:v(e),file:t,line:e.getStartLineNumber(),method:s}},jl=(e,t)=>w(e,t,Wl),Hl=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},Gl=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Yl=(e,t)=>{const s=[];for(const n of p(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=x(t,n);for(const a of o.getDescendantsOfKind(l.CallExpression)){if(!Hl(a))continue;const c=Js(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:Gl(a)})}}return s},Ql=".lunora-schema.json",Fe=(e,t)=>{b(e)&&_t(e,"utf8")===t||Is(e,t,"utf8")},Xl=(e,t)=>{if(t===""){ws(e,{force:!0});return}Fe(e,t)},Zl=e=>{const t=E(e,"package.json");if(b(t))try{const s=JSON.parse(_t(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Jl=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},eu=e=>{let t=b(e)?e:se(e);for(;t&&t!==se(t);){const s=E(t,"tsconfig.json");if(b(s))return s;t=se(t)}},kt=e=>e.replaceAll("\\","/"),tu=(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 o=t.columns.length>0;for(const r of e){if(r.table===void 0){if(o)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})}},ce=(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)},Mt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,su=8,nu=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:o,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:h}=e;let m=lt(a,o),P=dt(a,o),M=ut(a,o);ft([...m,...P].map(g=>g.filePath)),ft(M.filter(g=>g.stream).map(g=>g.filePath),"http-stream");for(let g=1;;g+=1){const T=js({agents:t,functions:m,httpRoutes:M,mutators:P,useUmbrella:d,workflows:h}),F=Hs({agents:t,functions:m,migrations:r,mutators:P,shapes:c,useUmbrella:d,usesSandbox:u});if(g>=su||Mt(a,s,T)&&Mt(a,n,F))return{apiContent:T,functions:m,functionsContent:F,httpRoutes:M,mutators:P};ce(a,s,T),ce(a,n,F),m=lt(a,o),P=dt(a,o),M=ut(a,o)}},ru=e=>{const t=eu(e);return t?new ct({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new ct({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Ju=(e,t)=>{const s=p(t),n=E(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 o=new Set(s.map(c=>kt(c))),r=kt(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!o.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)}}},ed=e=>{const t=Jl(),s=t?ye.now():0,n=E(e.projectRoot,e.lunoraDirectory??"lunora"),o=E(n,"schema.ts");if(!b(o))throw new L("INTERNAL",`schema.ts not found at ${o}`);const r=e.project??ru(n);mn(Go);const a=Rn(r,o,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:h,dependencies:m,entryCronTriggers:P,env:M,featureUsage:g,hasFlags:T,hasNotify:F,identity:U,platformGate:y,queues:O,serverContent:z,storageRulesMetadata:W,usesSandbox:X,useUmbrella:_,workflows:C}=gr({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),N=E(n,"_generated"),hs=E(N,"dataModel.ts"),xs=E(N,"server.ts"),vs=E(N,"api.ts"),Es=E(N,"functions.ts");ce(r,hs,h),ce(r,xs,z);const Z=Nn(r,n),q=_n(r,n),{apiContent:ze,functions:B,functionsContent:$e,httpRoutes:Ss,mutators:Ue}=nu({agents:c,apiPath:vs,generatedFunctionsPath:Es,lunoraDirectory:n,migrations:Z,project:r,shapes:q,useUmbrella:_,usesSandbox:X,workflows:C}),J=e.lint===!1?void 0:Fs({adminRoutes:yr(r,n),aiRawRuns:br(r,n),aiToolSideEffects:Dr(r,n),argumentDerivedFetches:_r(r,n),argumentValidators:Hr(r,n),authApiCalls:hn(r,n),authConfigs:no(r,n),browserUrlAccesses:co(r,n),configCalls:xo(r,n),containerKeyAccesses:Eo(r,n),containerOverrides:Po(r,n),containers:u,exportSinks:Co(r,n),staleMigrationImports:nl(r,n),failOpenGuards:Do(r,n),flagReads:Bo(r,n),flagSecurityDefaults:Ho(r,n),geoIndexUsages:Xo(r,n),httpActionGuards:li(r,n),httpHeaderWrites:Ei(r,n),hyperdriveCalls:Sn(r,n),identityClaimReads:Ii(r,n),imageDeliveryUrlAccesses:Ti(r,n),inserts:yn(r,n),kvKeyAccesses:Fi(r,n,B),mailRecipientAccesses:ki(r,n),maskProcedures:An(r,n),maskStrategies:Bi(r,n),mutatorWrites:Yi(r,n),nondeterministicCalls:In(r,n),normalizeIdAuthorizations:da(r,n),notifyCalls:Tn(r,n),notifyConfig:wn(r,n),ownerFieldWrites:Ea(r,n,B),unrestrictedWhereBranches:ql(r,n),paymentWebhooks:wa(r,n),privilegedDispatches:$a(r,n),procedureProtections:bc(r,n),queries:pn(r,n),queues:O,r2sqlCalls:Cn(r,n),ratelimitKeySelectors:Tc(r,n),rawRowReturns:kc(r,n),relationLoads:Kc(r,n),rlsProcedures:Fn(r,n),schema:a,secretLiterals:jc(r,n),shapes:q,softDeleteReads:Gc(r,n),sqlInterpolations:el(r,n),storageKeyAccesses:ol(r,n,B),storageUploads:dl(r,n),vectorNamespaceAccesses:jl(r,n),workflowCalls:Yl(r,n),workflows:C,wranglerVariables:e.wranglerVariables}),qe=J===void 0?[]:[...Ts(J,{source:"static"}),...Il(r,n,{byName:new Set([...C,...O,...c,...u].map(f=>f.exportName)),byPath:new Set([...B,...Ue,...q,...Z].map(f=>`${f.filePath}:${f.exportName}`))}),...hl(r,n)],ys=On(r,n),Be=$i(r,n);tu(q,Be,Ki(r,n));const As=T?Ko(r,n):[],me=y.signals.vectorStore!==!1,j=fl(g,{containerCount:u.length,cronCount:d.length,dependencies:m,hasPaymentTables:Aa(a.tables),queueCount:O.length,storageColumnCount:Object.keys(Kt(a)).length,storageRuleCount:W.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:me,workflowCount:C.length}),Ve=t?ye.now():0,he=Bn(a,Z.map(f=>f.id)),We=Ds({advisories:qe.filter(f=>f.name!=="procedure_type_check_unavailable"),advisorProcedures:J?.procedureProtections??[],agents:c,containers:u,env:M,flagKeys:As,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:T,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:F,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:me,hasX402:g.x402,maskMetadata:Be,mutators:Ue,queues:O,rlsMetadata:ys,schema:a,schemaSnapshot:he,shapes:q,storageRules:W,studioFeatures:j,useUmbrella:_,workflows:C}),je=ks(q,m.has("@lunora/db"),_),He=Ms(u,a.jurisdiction),Ge=_s(C),Ye=Ks(c),Qe=zs(O),Xe=$s(d),Ns=Us(j.scheduler),Ze=qs(a.vectorIndexes),ee=Bs(a,_),Je=Vs(m.has("@lunora/seed")),te=e.apiSpec??"openapi",xe=te==="openapi"||te==="both",ve=te==="openrpc"||te==="both",et=Kn({emailAgents:c.filter(f=>f.onEmail===!0).map(f=>({bindingName:f.bindingName,exportName:f.exportName})),hasAccess:m.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:m.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:m.has("@lunora/astro")||m.has("@lunora/svelte")||m.has("@lunora/vue"),hasGlobal:a.tables.some(f=>zt(f)),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(f=>$t(f)),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:j.kv,hasNotify:F,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:O.some(f=>f.mode==="push"),hasScheduler:j.scheduler,hasStorage:j.storage,hasVectors:me,hasWorkflow:C.length>0,hasX402:g.x402,identity:U,jurisdiction:a.jurisdiction,tableNames:a.tables.map(f=>f.name),useUmbrella:_,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(f=>f.voice===!0&&f.voiceBindingName!==void 0).map(f=>({bindingName:f.voiceBindingName,exportName:f.exportName})),wantsOpenApi:xe,wantsOpenRpc:ve}),tt=Zl(e.projectRoot),st=zn({functions:B,httpRoutes:Ss,version:tt}),nt=Un({functions:B,version:tt}),rt=`${JSON.stringify(st,void 0,2)}
|
|
8
|
+
`,ot=`${JSON.stringify(nt,void 0,2)}
|
|
9
|
+
`,it=$n(st),at=qn(nt),Ee=E(n,Ql),bs=b(Ee),Se=[];if(!e.dryRun){b(N)||Ps(N,{recursive:!0});const f=($,V)=>{Fe(E(N,$),V),Se.push($)},I=($,V)=>{Xl(E(N,$),V),V!==""&&Se.push($)};f("app.ts",et),f("dataModel.ts",h),f("api.ts",ze),f("server.ts",z),f("functions.ts",$e),f("shard.ts",We),f("crons.ts",Xe),f("vectors.ts",Ze),f("drizzle.global.ts",ee.global),f("drizzle.shard.ts",ee.shard),I("containers.ts",He),I("workflows.ts",Ge),I("agents.ts",Ye),I("queues.ts",Qe),I("scheduler.ts",Ns),I("seed.ts",Je),I("collections.ts",je),I("openapi.json",xe?rt:""),I("openapi.ts",xe?it:""),I("openrpc.json",ve?ot:""),I("openrpc.ts",ve?at:""),(!bs||e.updateSchemaBaseline===!0)&&Fe(Ee,Cs(he))}if(t){const f=ye.now(),I=Math.round(f-s),$=Math.round(Ve-s),V=Math.round(f-Ve);console.error(`@lunora/codegen: codegen took ${I.toString()}ms (discovery ${$.toString()}ms, emit ${V.toString()}ms)`)}return{advisories:qe,advisorContext:J,agents:c,containers:u,cronTriggers:[...new Set([...Ws(d),...P])],generated:{agents:Ye,api:ze,app:et,collections:je,containers:He,crons:Xe,dataModel:h,drizzleGlobal:ee.global,drizzleShard:ee.shard,functions:$e,openApi:rt,openApiModule:it,openRpc:ot,openRpcModule:at,queues:Qe,seed:Je,server:z,shard:We,vectors:Ze,workflows:Ge},migrations:Z,outputDirectory:N,platformDiagnostics:y.diagnostics,queues:O,schemaSnapshot:he,schemaSnapshotPath:Ee,workflows:C,writtenFiles:Se}};export{Ql as SCHEMA_SNAPSHOT_FILENAME,ru as createCodegenProject,eu as findTsconfig,Ju as refreshCodegenProject,ed as runCodegen};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const m=(e,t=2166136261)=>{let i=t;for(let o=0;o<e.length;o+=1)i^=e.charCodeAt(o),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},S=e=>`${m(e,2166136261)}${m(e,16777619)}`,H=1;function w(e){const t={},i=Object.keys(e);i.sort();for(const o of i)t[o]=e[o];return t}const O=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,P=e=>S(O(e)),c=e=>typeof e=="object"&&e!==null,x=e=>c(e)&&c(e.fields)&&c(e.indexes)&&c(e.relations)&&typeof e.shardMode=="string",J=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(o){return{error:`baseline is not valid JSON: ${o instanceof Error?o.message:String(o)}`,status:"invalid"}}if(!c(t)||t.version!==1||!c(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[o,r]of Object.entries(t.tables))if(!x(r))return{error:`baseline table "${o}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},F=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,o)=>i===t.fields[o]),y=e=>e.unique!==void 0,p=({nullable:e,optional:t,refined:i,unique:o,...r})=>JSON.stringify(w(r)),g=e=>({form:JSON.stringify([p(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),v=e=>e.kind==="union"&&e.members?e.members.map(t=>g(t)):[g({...e,nullable:!1,optional:!1})],T=(e,t)=>{if(t.kind!=="union")return!1;const i=v(t);return v(e).every(o=>i.some(r=>r.form===o.form&&(o.refined||!r.refined)))},a=e=>{switch(e.kind){case"array":return`array(${e.of?a(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?a(e.key):"?"}, ${e.of?a(e.of):"?"})`;case"union":return(e.members??[]).map(t=>a(t)).join(" | ");default:return e.kind}},l=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),f=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),_=(e,t,i,o,r)=>{if(!(i.kind===o.kind&&(!r||p(i)===p(o))))return r&&T(i,o)?f(e,"widenedFieldShape",`field ${e}.${t} widened: ${a(i)} → ${a(o)} — every stored value stays valid`):i.kind!==o.kind?l(e,"changedFieldKind",`field ${e}.${t} changed type: ${i.kind} → ${o.kind} — add a data migration to convert existing values`):l(e,"changedFieldShape",`field ${e}.${t} changed shape: ${a(i)} → ${a(o)} — stored values were written against the old shape; add a data migration to convert them`)},j=(e,t,i,o)=>{const r=[];return i.unique!==o.unique&&r.push(o.unique===!0?l(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):f(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==o.nullable&&r.push(o.nullable===!0?f(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):l(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),i.refined!==o.refined&&r.push(o.refined===!0?l(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):f(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),r},q=(e,t,i,o)=>{const r=[],n=y(i)&&y(o),s=_(e,t,i,o,n);return s&&r.push(s),n&&r.push(...j(e,t,i,o)),i.optional&&!o.optional?r.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&o.optional&&r.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),r},E=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},A=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.fields)){const s=t.fields[r];s===void 0?o.push(E(e,r,n)):o.push(...q(e,r,s,n))}for(const r of Object.keys(t.fields))i.fields[r]===void 0&&o.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${r} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},M=(e,t,i,o)=>{for(const[r,n]of Object.entries(i.indexes)){const s=t.indexes[r];if(s===void 0){o.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${r} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${r} on ${e}`,table:e,type:"addedIndex"});continue}F(s,n)||o.push({remediation:"code",severity:"breaking",summary:`index ${r} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const r of Object.keys(t.indexes))i.indexes[r]===void 0&&o.push({remediation:"code",severity:"breaking",summary:`removed index ${r} on ${e} — a query that used \`.withIndex("${r}")\` would break`,table:e,scope:"table",type:"removedIndex"})},C=(e,t,i,o)=>{for(const r of Object.keys(i.relations))t.relations[r]===void 0&&o.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${r}`,table:e,type:"addedRelation"});for(const r of Object.keys(t.relations))i.relations[r]===void 0&&o.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${r}`,table:e,type:"removedRelation"})},$="shardBy:_unknown_",u="global",I=(e,t)=>e===u&&t.startsWith(`${u}:`)||t===u&&e.startsWith(`${u}:`),R=(e,t,i)=>{if(t===i)return i!==$?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${$}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!I(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — 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"}},b=e=>e.memory!==void 0,k=e=>e.after??0,d=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,V=(e,t,i)=>{if(t===void 0&&i===void 0)return;const o=h=>({remediation:"backfill",scope:"table",severity:"breaking",summary:h,table:e,type:"changedTtlPolicy"}),r=h=>({remediation:"none",scope:"table",severity:"safe",summary:h,table:e,type:"changedTtlPolicy"});if(i===void 0)return r(`table ${e} dropped its TTL policy — its rows are no longer swept`);if(t===void 0)return o(`table ${e} gained a TTL policy ${d(i)} — every row already past the cutoff is deleted on the next alarm sweep; add a data migration to refresh or clear "${i.field}" on the rows written before it`);if(t.field!==i.field)return o(`table ${e} moved its TTL to a different column: ${d(t)} → ${d(i)} — rows are now expired by a column they were never written against; add a data migration to populate "${i.field}"`);const n=k(t),s=k(i);return s<n?o(`table ${e} shortened its TTL: ${d(t)} → ${d(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; add a data migration to refresh "${i.field}" on the rows that must survive`):s>n?r(`table ${e} lengthened its TTL: ${d(t)} → ${d(i)}`):void 0},L=(e,t,i)=>{const o=[];return t.memory!==i.memory&&o.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode"}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&o.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering"}:{remediation:"code",scope:"table",severity:"breaking",summary:`table ${e} is no longer .commitOrdered() — new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers before deploying`,table:e,type:"changedCommitOrdering"}),o},D=(e,t,i,o)=>{const r=R(e,t.shardMode,i.shardMode);if(r&&o.push(r),b(t)&&b(i)){o.push(...L(e,t,i));const n=V(e,t.ttl,i.ttl);n&&o.push(n)}A(e,t,i,o),M(e,t,i,o),C(e,t,i,o)},B=(e,t)=>{const i=[],o=e?.tables??{};for(const[r,n]of Object.entries(t.tables)){const s=o[r];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${r}`,table:r,type:"addedTable"});continue}D(r,s,n,i)}for(const r of Object.keys(o))t.tables[r]===void 0&&i.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${r} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:r,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const r=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${r} 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:i}};export{H as SCHEMA_SNAPSHOT_VERSION,a as describeShape,q as diffExistingField,B as diffSchemaSnapshots,P as hashSchemaSnapshot,x as isValidTableSnapshot,J as parseSnapshotJson,O as serializeSchemaSnapshot,w as sortKeys};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as v,sortKeys as f,diffSchemaSnapshots as I,parseSnapshotJson as A}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{serializeSchemaSnapshot as K}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as L}from"./isD1GlobalTable-udvHAAzD.mjs";const O=e=>{const t=e.shardMode;return t==="global"?`global:${L(e)?"hyperdrive":"d1"}`:t==="root"?t:`shardBy:${t.field}`},_=(e,t)=>{const n=JSON.stringify(e),s=JSON.stringify(t);return n===s?0:n<s?-1:1},l=e=>{const t=e.kind==="optional",n=t?e.inner:void 0,s=n??e,r={kind:t?n?.kind??"unknown":e.kind,nullable:s.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:s.column?.unique===!0||e.column?.unique===!0,...j[s.kind]?.(s)};return(s.hasRefinement===!0||e.hasRefinement===!0)&&(r.refined=!0),r},N=e=>{const t={};for(const[n,s]of Object.entries(e))t[n]=l(s);return f(t)},j={array:e=>e.inner?{of:l(e.inner)}:{},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:N(e.shape)}:{},record:e=>({...e.keyType?{key:l(e.keyType)}:{},...e.valueType?{of:l(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>l(t)).toSorted(_)}:{}},D=e=>{const t={};for(const[o,a]of Object.entries(e.shape))t[o]=l(a);const n={};for(const o of e.indexes)n[o.name]={fields:[...o.fields],unique:o.unique??!1};const s={};for(const o of e.relations)s[o.name]={field:o.field,kind:o.kind,table:o.table};const r={commitOrdered:e.commitOrdered===!0,fields:f(t),indexes:f(n),memory:e.memory===!0,relations:f(s),shardMode:O(e)};return e.ttl&&(r.ttl=e.ttl.after===void 0?{field:e.ttl.field}:{after:e.ttl.after,field:e.ttl.field}),r},C=(e,t)=>{const n={};for(const r of e.tables)n[r.name]=D(r);const s=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:s,tables:f(n),version:v}};class R extends E{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const z=e=>{const t=A(e);if(t.status==="invalid")throw new R(t.error);return t.status==="ok"?t.snapshot:void 0},M={build:{allowDrift:!0,updateBaseline:!1},deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},y=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",k=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",x=e=>{const t=e===void 0?void 0:M[e];if(e===void 0||t===void 0)return`${y}
|
|
2
|
+
${k}
|
|
3
|
+
`;const n=t.updateBaseline?k:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${y}
|
|
4
|
+
${n}
|
|
5
|
+
`},p=e=>e.map(t=>` - ${t.summary}`).join(`
|
|
6
|
+
`),w=e=>e.remediation==="backfill"&&e.table!==void 0,B=/^[A-Za-z_]\w*$/u,F=e=>` lunora migrate create backfill_${e} --table ${e}`,P=(e,t,n)=>{const s=[...new Set(e.filter(o=>w(o)).map(o=>o.table))],r=[];if(s.length>0){r.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 o=s.filter(a=>B.test(a));o.length>0&&r.push(`
|
|
7
|
+
Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
|
|
8
|
+
${o.map(a=>F(a)).join(`
|
|
9
|
+
`)}
|
|
10
|
+
|
|
11
|
+
`)}return t.length>0&&r.push(` • Migration(s) ${t.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
|
|
12
|
+
`),r.push(x(n)),[`${n??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,p(e),"",`To fix:
|
|
13
|
+
${r.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
|
|
14
|
+
`)},J=e=>{const{allowDrift:t=!1,baseline:n,command:s,current:r,migrations:o}=e,a=I(n,r),u=a.changes.filter(i=>i.severity==="breaking"),b=r.migrationIds.filter(i=>!(n?.migrationIds??[]).includes(i)),m=o.filter(i=>b.includes(i.id)),c=(i,h)=>({blocked:i,changes:a.changes,newMigrationIds:b,reason:h}),T=new Set(m.filter(i=>i.table!=="").map(i=>i.table)),$=m.filter(i=>i.table==="").map(i=>i.id);if(a.changes.length===0||n===void 0)return c(!1,"");if(u.length===0)return c(!1,`schema drift detected (all additive/safe):
|
|
15
|
+
${p(a.changes)}`);const g=u.filter(i=>!w(i)||!T.has(i.table));if(g.length===0){const i=new Set(u.map(d=>d.table)),h=m.filter(d=>i.has(d.table)).map(d=>d.id);return c(!1,`breaking schema drift detected, covered by ${String(h.length)} new migration(s) (${h.join(", ")}):
|
|
16
|
+
${p(u)}`)}const S=P(g,$,s);return t?c(!1,`${S}
|
|
17
|
+
|
|
18
|
+
(overridden by --allow-schema-drift)`):c(!0,S)};export{v as SCHEMA_SNAPSHOT_VERSION,R as SchemaSnapshotParseError,C as buildSchemaSnapshot,I as diffSchemaSnapshots,J as evaluateSchemaDrift,z as parseSchemaSnapshot,K as serializeSchemaSnapshot};
|
package/dist/packem_shared/{buildOpenApiDocument-BaDsKuhs.mjs → buildOpenApiDocument-DZJVlDWv.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-B8cDEy4W.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-C2s0xWQD.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 pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-C0oHwiJZ.mjs";import{isHyperdriveGlobalTable as Nn,isD1GlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as On}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const mt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@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",requiredPackage:"@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",requiredPackage:"@lunora/bindings",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",requiredPackage:"@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 w,G as k}from"./emit-
|
|
1
|
+
import{A as w,G as k}from"./emit-B8cDEy4W.mjs";const y=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[y(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(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";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},L=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. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\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}']:[]],N=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 maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," 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>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${a}"]>>): this {
|
|
3
3
|
this.shardExtras.${a} = factory as NonNullable<ShardConfig["${a}"]>;
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.188",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
51
|
-
"@lunora/container": "1.0.0-alpha.
|
|
52
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.138",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.116",
|
|
51
|
+
"@lunora/container": "1.0.0-alpha.52",
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.39",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.32",
|
|
54
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
55
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
56
|
-
"@lunora/values": "1.0.0-alpha.
|
|
57
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.59",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.76",
|
|
56
|
+
"@lunora/values": "1.0.0-alpha.49",
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.55",
|
|
58
58
|
"jiti": "^2.7.0",
|
|
59
59
|
"quicktype-core": "^26.0.0",
|
|
60
60
|
"ts-morph": "^28.0.0"
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const p=(e,i=2166136261)=>{let t=i;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},m=e=>`${p(e,2166136261)}${p(e,16777619)}`,I=1;function g(e){const i={},t=Object.keys(e);t.sort();for(const n of t)i[n]=e[n];return i}const v=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
-
`,E=e=>m(v(e)),a=e=>typeof e=="object"&&e!==null,$=e=>a(e)&&a(e.fields)&&a(e.indexes)&&a(e.relations)&&typeof e.shardMode=="string",_=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(n){return{error:`baseline is not valid JSON: ${n instanceof Error?n.message:String(n)}`,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[n,o]of Object.entries(i.tables))if(!$(o))return{error:`baseline table "${n}" 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"}},b=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((t,n)=>t===i.fields[n]),f=e=>e.unique!==void 0,u=({nullable:e,optional:i,refined:t,unique:n,...o})=>JSON.stringify(g(o)),h=e=>({form:JSON.stringify([u(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),y=e=>e.kind==="union"&&e.members?e.members.map(i=>h(i)):[h({...e,nullable:!1,optional:!1})],S=(e,i)=>{if(i.kind!=="union")return!1;const t=y(i);return y(e).every(n=>t.some(o=>o.form===n.form&&(n.refined||!o.refined)))},d=e=>{switch(e.kind){case"array":return`array(${e.of?d(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?d(e.key):"?"}, ${e.of?d(e.of):"?"})`;case"union":return(e.members??[]).map(i=>d(i)).join(" | ");default:return e.kind}},c=(e,i,t)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:t,table:e,type:i}),l=(e,i,t)=>({remediation:"none",scope:"table",severity:"safe",summary:t,table:e,type:i}),k=(e,i,t,n,o)=>{if(!(t.kind===n.kind&&(!o||u(t)===u(n))))return o&&S(t,n)?l(e,"widenedFieldShape",`field ${e}.${i} widened: ${d(t)} → ${d(n)} — every stored value stays valid`):t.kind!==n.kind?c(e,"changedFieldKind",`field ${e}.${i} changed type: ${t.kind} → ${n.kind} — add a data migration to convert existing values`):c(e,"changedFieldShape",`field ${e}.${i} changed shape: ${d(t)} → ${d(n)} — stored values were written against the old shape; add a data migration to convert them`)},x=(e,i,t,n)=>{const o=[];return t.unique!==n.unique&&o.push(n.unique===!0?c(e,"addedFieldConstraint",`field ${e}.${i} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):l(e,"relaxedFieldConstraint",`field ${e}.${i} is no longer unique`)),t.nullable!==n.nullable&&o.push(n.nullable===!0?l(e,"relaxedFieldConstraint",`field ${e}.${i} became nullable`):c(e,"addedFieldConstraint",`field ${e}.${i} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),t.refined!==n.refined&&o.push(n.refined===!0?c(e,"addedFieldConstraint",`field ${e}.${i} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):l(e,"relaxedFieldConstraint",`field ${e}.${i} dropped its validation refinement`)),o},O=(e,i,t,n)=>{const o=[],s=f(t)&&f(n),r=k(e,i,t,n,s);return r&&o.push(r),s&&o.push(...x(e,i,t,n)),t.optional&&!n.optional?o.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&&n.optional&&o.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),o},F=(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"},j=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.fields)){const r=i.fields[o];r===void 0?n.push(F(e,o,s)):n.push(...O(e,o,r,s))}for(const o of Object.keys(i.fields))t.fields[o]===void 0&&n.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},w=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.indexes)){const r=i.indexes[o];if(r===void 0){n.push(s.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${o} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}b(r,s)||n.push({remediation:"code",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&&n.push({remediation:"code",severity:"breaking",summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` would break`,table:e,scope:"table",type:"removedIndex"})},A=(e,i,t,n)=>{for(const o of Object.keys(t.relations))i.relations[o]===void 0&&n.push({remediation:"none",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&&n.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${o}`,table:e,type:"removedRelation"})},q=(e,i,t,n)=>{i.shardMode!==t.shardMode&&n.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"}),j(e,i,t,n),w(e,i,t,n),A(e,i,t,n)},C=(e,i)=>{const t=[],n=e?.tables??{};for(const[o,s]of Object.entries(i.tables)){const r=n[o];if(r===void 0){t.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}q(o,r,s,t)}for(const o of Object.keys(n))i.tables[o]===void 0&&t.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${o} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:o,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const o=e.jurisdiction??"(none)",s=i.jurisdiction??"(none)";t.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${s} — 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{I as SCHEMA_SNAPSHOT_VERSION,d as describeShape,O as diffExistingField,C as diffSchemaSnapshots,E as hashSchemaSnapshot,$ as isValidTableSnapshot,_ as parseSnapshotJson,v as serializeSchemaSnapshot,g as sortKeys};
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as I,sortKeys as f,diffSchemaSnapshots as A,parseSnapshotJson as L}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{serializeSchemaSnapshot as V}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";const _=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,N=(e,t)=>{const s=JSON.stringify(e),i=JSON.stringify(t);return s===i?0:s<i?-1:1},l=e=>{const t=e.kind==="optional",s=t?e.inner:void 0,i=s??e,n={kind:t?s?.kind??"unknown":e.kind,nullable:i.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:i.column?.unique===!0||e.column?.unique===!0,...v[i.kind]?.(i)};return(i.hasRefinement===!0||e.hasRefinement===!0)&&(n.refined=!0),n},j=e=>{const t={};for(const[s,i]of Object.entries(e))t[s]=l(i);return f(t)},v={array:e=>e.inner?{of:l(e.inner)}:{},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:j(e.shape)}:{},record:e=>({...e.keyType?{key:l(e.keyType)}:{},...e.valueType?{of:l(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>l(t)).toSorted(N)}:{}},D=e=>{const t={};for(const[n,a]of Object.entries(e.shape))t[n]=l(a);const s={};for(const n of e.indexes)s[n.name]={fields:[...n.fields],unique:n.unique??!1};const i={};for(const n of e.relations)i[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:f(t),indexes:f(s),relations:f(i),shardMode:_(e.shardMode)}},U=(e,t)=>{const s={};for(const n of e.tables)s[n.name]=D(n);const i=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:i,tables:f(s),version:I}};class O extends E{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const C=e=>{const t=L(e);if(t.status==="invalid")throw new O(t.error);return t.status==="ok"?t.snapshot:void 0},R={build:{allowDrift:!0,updateBaseline:!1},deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},y=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",k=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",M=e=>{const t=e===void 0?void 0:R[e];if(e===void 0||t===void 0)return`${y}
|
|
2
|
-
${k}
|
|
3
|
-
`;const s=t.updateBaseline?k:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${y}
|
|
4
|
-
${s}
|
|
5
|
-
`},m=e=>e.map(t=>` - ${t.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}`,F=(e,t,s)=>{const i=[...new Set(e.filter(a=>w(a)).map(a=>a.table))],n=[];if(i.length>0){n.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 a=i.filter(r=>x.test(r));a.length>0&&n.push(`
|
|
7
|
-
Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
|
|
8
|
-
${a.map(r=>B(r)).join(`
|
|
9
|
-
`)}
|
|
10
|
-
|
|
11
|
-
`)}return t.length>0&&n.push(` • Migration(s) ${t.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
|
|
12
|
-
`),n.push(M(s)),[`${s??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,m(e),"",`To fix:
|
|
13
|
-
${n.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
|
|
14
|
-
`)},H=e=>{const{allowDrift:t=!1,baseline:s,command:i,current:n,migrations:a}=e,r=A(s,n),u=r.changes.filter(o=>o.severity==="breaking"),b=n.migrationIds.filter(o=>!(s?.migrationIds??[]).includes(o)),p=a.filter(o=>b.includes(o.id)),c=(o,h)=>({blocked:o,changes:r.changes,newMigrationIds:b,reason:h}),T=new Set(p.filter(o=>o.table!=="").map(o=>o.table)),$=p.filter(o=>o.table==="").map(o=>o.id);if(r.changes.length===0||s===void 0)return c(!1,"");if(u.length===0)return c(!1,`schema drift detected (all additive/safe):
|
|
15
|
-
${m(r.changes)}`);const g=u.filter(o=>!w(o)||!T.has(o.table));if(g.length===0){const o=new Set(u.map(d=>d.table)),h=p.filter(d=>o.has(d.table)).map(d=>d.id);return c(!1,`breaking schema drift detected, covered by ${String(h.length)} new migration(s) (${h.join(", ")}):
|
|
16
|
-
${m(u)}`)}const S=F(g,$,i);return t?c(!1,`${S}
|
|
17
|
-
|
|
18
|
-
(overridden by --allow-schema-drift)`):c(!0,S)};export{I as SCHEMA_SNAPSHOT_VERSION,O as SchemaSnapshotParseError,U as buildSchemaSnapshot,A as diffSchemaSnapshots,H as evaluateSchemaDrift,C as parseSchemaSnapshot,V as serializeSchemaSnapshot};
|