@lunora/codegen 1.0.0-alpha.81 → 1.0.0-alpha.82
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 +17 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/GENERATED_HEADER-Cphn03Kf.mjs +1 -0
- package/dist/packem_shared/{OPENRPC_VERSION-DfKtsdPS.mjs → OPENRPC_VERSION-IKkrtXye.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DBD0oti8.mjs +12 -0
- package/dist/packem_shared/SchemaSnapshotParseError-BJkhTEpi.mjs +16 -0
- package/dist/packem_shared/{buildOpenApiDocument-D46nZ7D_.mjs → buildOpenApiDocument-XeZ1ycwi.mjs} +1 -1
- package/dist/packem_shared/discoverSchema-CaTD2Sdx.mjs +1 -0
- package/dist/packem_shared/{emit-CCw5fiXq.mjs → emit-05q6XTbd.mjs} +258 -185
- package/dist/packem_shared/{emitApp-DEHN578T.mjs → emitApp-C2DhPKWE.mjs} +7 -6
- package/dist/packem_shared/readPackageDependencies-CogJX1Ia.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/GENERATED_HEADER-CR3xA8yO.mjs +0 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_FILENAME-DjpfF4p7.mjs +0 -12
- package/dist/packem_shared/SchemaSnapshotParseError-0KRzSjo4.mjs +0 -14
- package/dist/packem_shared/discoverSchema-DUl8rbP3.mjs +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -2201,6 +2201,20 @@ declare const discoverNotifyCalls: (project: Project, lunoraDirectory: string) =
|
|
|
2201
2201
|
* rather than throwing.
|
|
2202
2202
|
*/
|
|
2203
2203
|
declare const discoverNotifyConfig: (project: Project, lunoraDirectory: string) => AdvisorNotifyConfig | undefined;
|
|
2204
|
+
/**
|
|
2205
|
+
* Every package name the project declares a dependency on, read from the
|
|
2206
|
+
* `package.json` at the project root across all four dependency fields
|
|
2207
|
+
* (`dependencies`, `devDependencies`, `peerDependencies`,
|
|
2208
|
+
* `optionalDependencies`).
|
|
2209
|
+
*
|
|
2210
|
+
* Returns `undefined` — NOT an empty set — when the manifest is absent or
|
|
2211
|
+
* unparseable, which is the whole reason this exists. Studio nav gating can
|
|
2212
|
+
* treat "declares nothing" and "cannot tell" the same way, but a check that
|
|
2213
|
+
* errors on a missing package cannot: conflating them makes it fire on every
|
|
2214
|
+
* project without a root `package.json` (the codegen fixtures, an embedded
|
|
2215
|
+
* schema, a tool driving `runCodegen` directly).
|
|
2216
|
+
*/
|
|
2217
|
+
declare const readPackageDependencies: (projectRoot: string) => Set<string> | undefined;
|
|
2204
2218
|
/**
|
|
2205
2219
|
* Discover `ctx.db.query("table")…` reads under the lunora source directory and
|
|
2206
2220
|
* reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
|
|
@@ -3244,6 +3258,8 @@ interface SchemaDriftDecision {
|
|
|
3244
3258
|
declare const evaluateSchemaDrift: (options: {
|
|
3245
3259
|
allowDrift?: boolean;
|
|
3246
3260
|
baseline: SchemaSnapshot | undefined;
|
|
3261
|
+
/** The command printing the remediation, so it names only flags that command accepts. */
|
|
3262
|
+
command?: string;
|
|
3247
3263
|
current: SchemaSnapshot;
|
|
3248
3264
|
}) => SchemaDriftDecision;
|
|
3249
3265
|
/**
|
|
@@ -3275,4 +3291,4 @@ declare const secretKindOf: (value: string) => string | undefined;
|
|
|
3275
3291
|
/** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
|
|
3276
3292
|
declare const redact: (value: string) => string;
|
|
3277
3293
|
declare const VERSION = "0.0.0";
|
|
3278
|
-
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
|
3294
|
+
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
package/dist/index.d.ts
CHANGED
|
@@ -2201,6 +2201,20 @@ declare const discoverNotifyCalls: (project: Project, lunoraDirectory: string) =
|
|
|
2201
2201
|
* rather than throwing.
|
|
2202
2202
|
*/
|
|
2203
2203
|
declare const discoverNotifyConfig: (project: Project, lunoraDirectory: string) => AdvisorNotifyConfig | undefined;
|
|
2204
|
+
/**
|
|
2205
|
+
* Every package name the project declares a dependency on, read from the
|
|
2206
|
+
* `package.json` at the project root across all four dependency fields
|
|
2207
|
+
* (`dependencies`, `devDependencies`, `peerDependencies`,
|
|
2208
|
+
* `optionalDependencies`).
|
|
2209
|
+
*
|
|
2210
|
+
* Returns `undefined` — NOT an empty set — when the manifest is absent or
|
|
2211
|
+
* unparseable, which is the whole reason this exists. Studio nav gating can
|
|
2212
|
+
* treat "declares nothing" and "cannot tell" the same way, but a check that
|
|
2213
|
+
* errors on a missing package cannot: conflating them makes it fire on every
|
|
2214
|
+
* project without a root `package.json` (the codegen fixtures, an embedded
|
|
2215
|
+
* schema, a tool driving `runCodegen` directly).
|
|
2216
|
+
*/
|
|
2217
|
+
declare const readPackageDependencies: (projectRoot: string) => Set<string> | undefined;
|
|
2204
2218
|
/**
|
|
2205
2219
|
* Discover `ctx.db.query("table")…` reads under the lunora source directory and
|
|
2206
2220
|
* reduce each to a {@link QueryReadIR}. Only reads that call `.filter()` are
|
|
@@ -3244,6 +3258,8 @@ interface SchemaDriftDecision {
|
|
|
3244
3258
|
declare const evaluateSchemaDrift: (options: {
|
|
3245
3259
|
allowDrift?: boolean;
|
|
3246
3260
|
baseline: SchemaSnapshot | undefined;
|
|
3261
|
+
/** The command printing the remediation, so it names only flags that command accepts. */
|
|
3262
|
+
command?: string;
|
|
3247
3263
|
current: SchemaSnapshot;
|
|
3248
3264
|
}) => SchemaDriftDecision;
|
|
3249
3265
|
/**
|
|
@@ -3275,4 +3291,4 @@ declare const secretKindOf: (value: string) => string | undefined;
|
|
|
3275
3291
|
/** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
|
|
3276
3292
|
declare const redact: (value: string) => string;
|
|
3277
3293
|
declare const VERSION = "0.0.0";
|
|
3278
|
-
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
|
3294
|
+
export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, DEFAULT_TARGET, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type PlatformDiagnostic, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, platformMatrixIds, readPackageDependencies, readProjectTarget, redact, refreshCodegenProject, resolveCodegenTarget, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-BCEfzLT0.mjs";import{CodegenDiagnosticError as c,diagnosticAt as n}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as l,discoverAgents as E}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as A}from"./packem_shared/discoverAuthApiCalls-CYdI8pkP.mjs";import{CONTAINERS_FILENAME as v,discoverContainers as N}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as R}from"./packem_shared/discoverCrons-CwtPaymU.mjs";import{FLAGS_FILENAME as C,discoverFlags as g}from"./packem_shared/FLAGS_FILENAME-UPE377GV.mjs";import{discoverFunctions as I}from"./packem_shared/discoverFunctions-CVYkUBTm.mjs";import{default as L}from"./packem_shared/discoverHttpRoutes-DmTedJlp.mjs";import{default as T}from"./packem_shared/discoverInserts-CssZuKb6.mjs";import{default as D}from"./packem_shared/discoverMaskProcedures-DQ-4yUUK.mjs";import{default as H}from"./packem_shared/discoverMigrations-qyXaVjw1.mjs";import{MUTATORS_FILENAME as k,discoverMutators as y}from"./packem_shared/MUTATORS_FILENAME-CsAoG-d2.mjs";import{default as W}from"./packem_shared/discoverNondeterministicCalls-GNP4oKrf.mjs";import{NOTIFY_FILENAME as j,discoverNotifyCalls as w,discoverNotifyConfig as z}from"./packem_shared/NOTIFY_FILENAME-zA5OFFbv.mjs";import{default as K}from"./packem_shared/readPackageDependencies-CogJX1Ia.mjs";import{y as B}from"./packem_shared/discover-queries-Ctpk9SA-.mjs";import{QUEUES_FILENAME as X,discoverQueues as Y}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as $}from"./packem_shared/discoverR2sqlCalls-B7uqLnVS.mjs";import{discoverRlsMetadata as oe,default as re}from"./packem_shared/discoverRlsMetadata-Bt0QK8VM.mjs";import{discoverSandboxUsage as se}from"./packem_shared/discoverSandboxUsage-Bb2JzaIW.mjs";import{default as ie}from"./packem_shared/discoverSchema-CaTD2Sdx.mjs";import{SHAPES_FILENAME as de,discoverShapes as fe}from"./packem_shared/SHAPES_FILENAME-DyVUZzIk.mjs";import{default as ce}from"./packem_shared/discoverStorageRulesMetadata-VJ_uXOFe.mjs";import{WORKFLOWS_FILENAME as Se,discoverWorkflows as le}from"./packem_shared/WORKFLOWS_FILENAME-ClsYRKXp.mjs";import{w as xe,e as Ae,k as ue,S as ve,X as Ne,b as Oe,s as Re,f as Me,L as Ce,O as ge,d as he,y as Ie,Z as _e,x as Le}from"./packem_shared/emit-05q6XTbd.mjs";import{emitApp as Te}from"./packem_shared/emitApp-C2DhPKWE.mjs";import{buildOpenApiDocument as De,emitOpenApi as Ue,emitOpenApiModule as He}from"./packem_shared/buildOpenApiDocument-XeZ1ycwi.mjs";import{OPENRPC_VERSION as ke,buildOpenRpcDocument as ye,emitOpenRpc as Ge,emitOpenRpcModule as We}from"./packem_shared/OPENRPC_VERSION-IKkrtXye.mjs";import{DEFAULT_TARGET as je,platformMatrixIds as we,readProjectTarget as ze,resolveCodegenTarget as Qe}from"./packem_shared/DEFAULT_TARGET-BYPEwgZu.mjs";import{SCHEMA_SNAPSHOT_FILENAME as qe,createCodegenProject as Be,refreshCodegenProject as Je,runCodegen as Xe}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-DBD0oti8.mjs";import{SchemaSnapshotParseError as Ze,buildSchemaSnapshot as $e,evaluateSchemaDrift as eo,parseSchemaSnapshot as oo}from"./packem_shared/SchemaSnapshotParseError-BJkhTEpi.mjs";import{schemaFromIr as to}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as ao,validatorIrToJsonSchema as io}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as fo,secretKindOf as po}from"./packem_shared/redact-6jD4lAhq.mjs";import{MESSAGE_SOLUTIONS as no,findSolutionByMessage as So}from"@lunora/errors";const e="0.0.0";export{l as AGENTS_FILENAME,v as CONTAINERS_FILENAME,c as CodegenDiagnosticError,je as DEFAULT_TARGET,C as FLAGS_FILENAME,xe as GENERATED_HEADER,ao as LUNORA_ERROR_CODES,no as LUNORA_SOLUTION_RULES,k as MUTATORS_FILENAME,j as NOTIFY_FILENAME,ke as OPENRPC_VERSION,X as QUEUES_FILENAME,qe as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,de as SHAPES_FILENAME,Ze as SchemaSnapshotParseError,e as VERSION,Se as WORKFLOWS_FILENAME,De as buildOpenApiDocument,ye as buildOpenRpcDocument,$e as buildSchemaSnapshot,Be as createCodegenProject,n as diagnosticAt,s as diffSchemaSnapshots,E as discoverAgents,A as discoverAuthApiCalls,N as discoverContainers,R as discoverCrons,g as discoverFlags,I as discoverFunctions,L as discoverHttpRoutes,T as discoverInserts,D as discoverMaskProcedures,H as discoverMigrations,y as discoverMutators,W as discoverNondeterministicCalls,w as discoverNotifyCalls,z as discoverNotifyConfig,B as discoverQueries,Y as discoverQueues,$ as discoverR2sqlCalls,oe as discoverRlsMetadata,re as discoverRlsProcedures,se as discoverSandboxUsage,ie as discoverSchema,fe as discoverShapes,ce as discoverStorageRulesMetadata,le as discoverWorkflows,Ae as emitAgents,ue as emitApi,Te as emitApp,ve as emitCollections,Ne as emitContainers,Oe as emitCrons,Re as emitDataModel,Me as emitDrizzleSchema,Ce as emitFunctions,Ue as emitOpenApi,He as emitOpenApiModule,Ge as emitOpenRpc,We as emitOpenRpcModule,ge as emitServer,he as emitShard,Ie as emitVectors,_e as emitWorkflows,Le as emitWranglerCronTriggers,eo as evaluateSchemaDrift,So as findLunoraSolution,m as formatAdvisories,d as lintSchema,oo as parseSchemaSnapshot,we as platformMatrixIds,K as readPackageDependencies,ze as readProjectTarget,fo as redact,Je as refreshCodegenProject,Qe as resolveCodegenTarget,Xe as runCodegen,to as schemaFromIr,po as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,io as validatorIrToJsonSchema};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{w as r,a as o,e as n,k as l,S as p,X as S,b as d,s as g,f as u,L as C,t as E,v as c,O as A,d as D,y as f,Z as b,x as h}from"./emit-05q6XTbd.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as buildStorageColumns,n as emitAgents,l as emitApi,p as emitCollections,S as emitContainers,d as emitCrons,g as emitDataModel,u as emitDrizzleSchema,C as emitFunctions,E as emitQueues,c as emitSeed,A as emitServer,D as emitShard,f as emitVectors,b as emitWorkflows,h as emitWranglerCronTriggers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{w as a}from"./emit-05q6XTbd.mjs";import{n as s}from"./paths-BmX5O1sG.mjs";import{argsObjectSchema as i,LUNORA_ERROR_CODES as c}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const m="1.3.2",p=()=>({description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."}),u=e=>{const n=s(e.filePath),t=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:c.map((r,o)=>({code:-32e3-o,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:i(e.args)}],result:{name:"result",schema:p()},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},d=e=>{const n=e.version??"0.0.0",t=e.functions.filter(r=>r.visibility!=="internal"&&r.kind!=="stream").map(r=>u(r)).toSorted((r,o)=>r.name.localeCompare(o.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:t,openrpc:m}},R=e=>`${JSON.stringify(d(e),void 0,2)}
|
|
2
2
|
`,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{m as OPENRPC_VERSION,d as buildOpenRpcDocument,R as emitOpenRpc,O as emitOpenRpcModule};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{existsSync as E,mkdirSync as Gt,readFileSync as xt,writeFileSync as Ht,rmSync as Qt}from"node:fs";import{join as p,dirname as fe}from"node:path";import{performance as me}from"node:perf_hooks";import{runAdvisor as Xt}from"@lunora/advisor";import{LunoraError as R}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as et}from"ts-morph";import{serializeSchemaSnapshot as Zt}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as Jt}from"./formatAdvisories-BCEfzLT0.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as g,classifyProcedureCall as k,inlineHandler as Yt,procedureHandler as ht,chainUsesWrappedCall as Et,isDatabaseAccessor as C,chainHasStep as es,discoverFunctions as ts,resolveStandardSchemaType as ss}from"./discoverFunctions-CVYkUBTm.mjs";import{discoverAgents as rs}from"./AGENTS_FILENAME-BesaDYkL.mjs";import{i as w,a as O,e as h,c as S,r as ns,s as G,b as is,d as os,y as as}from"./discover-queries-Ctpk9SA-.mjs";import cs from"./discoverAuthApiCalls-CYdI8pkP.mjs";import{discoverContainers as us}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import ls from"./discoverCrons-CwtPaymU.mjs";import{diagnosticAt as H}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Q}from"./module-specifiers-8FEEiUcv.mjs";import{r as xe,a as ds,s as gs,k as ps,O as fs,L as ms,d as xs,S as hs,X as Es,Z as $s,e as ys,t as As,b as Ss,y as bs,f as Ns,v as vs,x as Ps}from"./emit-05q6XTbd.mjs";import{discoverFlagKeys as ws}from"./FLAGS_FILENAME-UPE377GV.mjs";import Is from"./discoverHttpRoutes-DmTedJlp.mjs";import Ls from"./discoverInserts-CssZuKb6.mjs";import Ts,{discoverMaskStrategies as Os,discoverMaskMetadata as Fs}from"./discoverMaskProcedures-DQ-4yUUK.mjs";import Ds from"./discoverMigrations-qyXaVjw1.mjs";import{MUTATORS_FILENAME as Cs,isDefineMutatorCallee as ks,discoverMutators as Ks}from"./MUTATORS_FILENAME-CsAoG-d2.mjs";import Rs from"./discoverNondeterministicCalls-GNP4oKrf.mjs";import{discoverNotifyConfig as js,discoverNotifyCalls as Ms}from"./NOTIFY_FILENAME-zA5OFFbv.mjs";import zs from"./readPackageDependencies-CogJX1Ia.mjs";import{discoverQueues as qs}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Bs from"./discoverR2sqlCalls-B7uqLnVS.mjs";import Vs,{discoverRlsMetadata as Us}from"./discoverRlsMetadata-Bt0QK8VM.mjs";import{discoverSandboxUsage as Ws}from"./discoverSandboxUsage-Bb2JzaIW.mjs";import _s from"./discoverSchema-CaTD2Sdx.mjs";import{secretKindOf as Gs,redact as Hs,isHeuristicSecretKind as Qs,isSecretishName as Xs}from"./redact-6jD4lAhq.mjs";import{discoverShapes as Zs}from"./SHAPES_FILENAME-DyVUZzIk.mjs";import Js from"./discoverStorageRulesMetadata-VJ_uXOFe.mjs";import{e as Ys}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as er}from"./WORKFLOWS_FILENAME-ClsYRKXp.mjs";import{emitApp as tr}from"./emitApp-C2DhPKWE.mjs";import{buildOpenApiDocument as sr,emitOpenApiModule as rr}from"./buildOpenApiDocument-XeZ1ycwi.mjs";import{buildOpenRpcDocument as nr,emitOpenRpcModule as ir}from"./OPENRPC_VERSION-IKkrtXye.mjs";import{p as or}from"./parse-validator-_jDrFxwt.mjs";import{gatePlatformFeatures as ar,resolveCodegenTarget as cr}from"./DEFAULT_TARGET-BYPEwgZu.mjs";import{buildSchemaSnapshot as ur}from"./SchemaSnapshotParseError-BJkhTEpi.mjs";const lr=e=>{const t=[],s=e.tables.filter(r=>r.shardMode==="global");return s.some(r=>r.globalBackend!=="hyperdrive")&&t.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),s.some(r=>r.globalBackend==="hyperdrive")&&t.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/vectors.ts` import `@lunora/bindings/vectors`"}),t},dr=(e,t)=>{if(t===void 0)return;const s=lr(e).filter(o=>!t.has(o.name));if(s.length===0)return;const r=s.map(o=>` - ${o.name} — ${o.reason}`).join(`
|
|
2
|
+
`),n=s.map(o=>o.name).join(" ");throw new R("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
|
+
${r}
|
|
4
|
+
|
|
5
|
+
Install them, then re-run codegen:
|
|
6
|
+
|
|
7
|
+
pnpm add ${n}
|
|
8
|
+
`)},$t=new Set(["delete","get","head","options","patch","post","put"]),gr=new Set(["handler","stream"]),pr=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,tt=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),fr=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!$t.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},mr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||$t.has(r.getName()))break;s=r.getExpression()}return fr(s)},xr=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(tt.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&tt.has(s.getText()))return!0}return!1},hr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!gr.has(r.getName()))return;const n=mr(s);if(!n||!pr.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&xr(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},Er=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=hr(n,t);o&&s.push(o)}return s},$r=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Er(n,g(t,r)))}return s},yr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Ar=(e,t)=>{if(!yr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)||O(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},Sr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ar(r,t);n&&s.push(n)}return s},br=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Sr(n,g(t,r)))}return s},Nr=new Set(["generateText","streamText"]),vr=new Set(["messages","prompt","system"]),Pr=[{methods:new Set(["delete","insert","insertManyUnsafe","patch","replace"]),prefixes:["context.db","ctx.db"]},{methods:new Set(["run","runAction","runMutation"]),prefixes:["context","ctx"]},{methods:new Set(["fetch"]),prefixes:["context","ctx"]},{methods:new Set(["queue","send"]),prefixes:["context.email","context.mail","ctx.email","ctx.mail"]}],wr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of Pr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},Ir=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=wr(t);if(s!==void 0)return s}},Lr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},Tr=e=>{if(ns(e))return!0;const t=Lr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},Or=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!vr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&Tr(s))return!0}return!1},Fr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!Nr.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(S(c.getExpression())==="tool"&&(a=Ir(c),a!==void 0))break;a!==void 0&&s.push({exportName:h(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:Or(o)})}return s},Dr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Fr(n,g(t,r)))}return s},Cr=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},kr=(e,t)=>{if(!Cr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},Kr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=kr(r,t);n&&s.push(n)}return s},Rr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Kr(n,g(t,r)))}return s},yt=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),jr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:yt(r)}},Mr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const n=r.getExpression();if(!i.isPropertyAccessExpression(n))break;if(n.getName()==="input"){const o=r.getArguments()[0];o&&i.isObjectLiteralExpression(o)?(t.push(o),s||=yt(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},At=(e,t)=>t?Mr(t):jr(e),zr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),qr=/\.check\(|\.meta\(|length|max/iu,Br=/\bv\.any\s*\(/u,Vr=/\bv\.string\s*\(/u,Ur=e=>Br.test(e),Wr=e=>Vr.test(e)&&!qr.test(e),_r=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();Ur(a)?t.push(c):Wr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Gr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=k(s);if(r?.visibility!=="public")return;const{objects:n}=At(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=_r(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Hr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Gr(n,t);o&&s.push(o)}return s},Qr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Hr(n,g(t,r)))}return s},b=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},he=e=>e?.getKind()===u.TrueKeyword,Xr=e=>e?.getKind()===u.FalseKeyword,Zr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,Jr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Yr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),en=e=>e!==void 0&&i.isCallExpression(e)&&Jr.has(S(e.getExpression())??""),tn=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),sn=e=>{const t=b(e,"advanced"),s=b(e,"emailAndPassword"),r=b(e,"session");return{analyzable:!0,disableCsrfCheck:he(b(t,"disableCSRFCheck")),emailPasswordEnabled:he(b(s,"enabled")),requireEmailVerification:he(b(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Yr(b(e,"plugins"))&&en(b(e,"database")),secureCookiesDisabled:Xr(b(t,"useSecureCookies")),sessionFreshAgeZero:Zr(b(r,"freshAge")),trustedOriginsWildcard:tn(b(e,"trustedOrigins"))}},rn=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),nn=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?sn(s):rn();return{exportName:h(e),file:t,line:e.getStartLineNumber(),...n}},on=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=nn(r,t);n&&s.push(n)}return s},an=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...on(n,g(t,r)))}return s},cn=(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},un=(e,t,s)=>{const r=cn(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!w(n)||O(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:r}},ln=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=un(n,t,s);o&&r.push(o)}return r},X=(e,t,s)=>{const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...ln(o,g(t,n),s))}return r},dn=new Set(["content","pdf","scrape","screenshot"]),gn=(e,t)=>X(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:dn}),pn=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),fn=new Set(["RateLimiter"]),mn=new Set(["extend"]),St=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},st=e=>e&&i.isObjectLiteralExpression(e)?St(e):{analyzable:!1,presentKeys:[],trueKeys:[]},xn=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},hn=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?xn(e):void 0},En=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&hn(t.getBody());return s?St(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},$n=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());n!==void 0&&(pn.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...st(r.getArguments()[0])}):mn.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...En(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=S(r.getExpression());n===void 0||!fn.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...st(r.getArguments()[0])})}return s},yn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...$n(n,g(t,r)))}return s},rt="ctx.containers.",An=e=>{if(!e.startsWith(rt))return!1;const t=e.slice(rt.length);return t.length>0&&!t.includes(".")},Sn=(e,t)=>X(e,t,{argIndex:0,matchReceiver:An,methods:new Set(["get"])}),bn=new Set(["allow","deny","setAllowed"]),Nn=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())},vn=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!Nn(e)))return{detail:"enableInternet: true",exportName:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},Pn=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!bn.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},wn=(e,t)=>vn(e,t)??Pn(e,t),In=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=wn(r,t);n&&s.push(n)}return s},Ln=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...In(n,g(t,r)))}return s},Tn="env.ts",On=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},Fn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},Dn=e=>{if(i.isIdentifier(e))return On(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&Fn(t)}return!1},Cn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!Dn(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw H(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},kn=(e,t)=>{const s=p(t,Tn);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=Cn(r);if(n.length!==0){if(n.length>1)throw H(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},Kn=new Set(["defineExportSink","r2Sink","webhookExportSink"]),Rn=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return Kn.has(s)?s:void 0},jn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Mn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=g(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=Rn(a);if(c===void 0)continue;const l=a.getArguments()[0],f=l&&i.isObjectLiteralExpression(l)?jn(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:f.analyzable,emptyKeys:f.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:f.presentKeys})}}return s},zn=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),qn=new Set(["dbRateLimit","rateLimit"]),Bn=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},Vn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},Un=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=zn.get(s);if(r!==void 0)return{callee:s,exportName:h(e),failOpen:Bn(e.getArguments()[r]),file:t,limitName:qn.has(s)?Vn(e):"",line:e.getStartLineNumber()}},Wn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Un(r,t);n&&s.push(n)}return s},_n=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Wn(n,g(t,r)))}return s},Gn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Hn=(e,t)=>{const s=Object.fromEntries(xe.map(r=>[r.key,!1]));for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Gn(n);for(const c of xe)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(xe.every(c=>s[c.key]))break}return s},Qn=["providerSubscriptionId","state"],Xn=["providerEventId","processedAt"],nt=(e,t)=>t.every(s=>s in e.shape),Zn=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&nt(t,Qn)&&nt(s,Xn)},Jn=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Yn=e=>i.isIdentifier(e)&&e.getText()==="ctx",ei=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Yn(t.getExpression())},ti=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},si=(e,t)=>{if(!ei(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=ti(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:h(e),file:t,key:n,line:e.getStartLineNumber()}},ri=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=si(r,t);n&&s.push(n)}return s},ni=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ri(n,g(t,r)))}return s},ii=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},oi=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},ai=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=g(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))ii(a)&&s.push({file:o,indexName:oi(a),line:a.getStartLineNumber()})}return s},ci=new Set(["delete","get","head","options","patch","post","put"]),ui=new Set(["handler","stream"]),li=new Set(["runAction","runMutation"]),di=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),U=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,it=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,ot=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},at=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(li.has(a)&&U(c,t))return a;if(di.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&U(c.getExpression(),t))return`db.${a}`}},ct=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&U(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!U(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},gi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ui.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(ci.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},pi=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=it(e.getArguments()[0]),l=c&&ot(c,!0);if(!c||l===void 0)return;const f=at(c,l);return f===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:ct(c,l),sideEffect:f}}const r=gi(e);if(r===void 0)return;const n=it(e.getArguments()[0]),o=n&&ot(n,!1);if(!n||o===void 0)return;const a=at(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:ct(n,o),sideEffect:a}},fi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=pi(r,t);n&&s.push(n)}return s},mi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...fi(n,g(t,r)))}return s},xi=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),hi=new Set(["append","set"]),ye=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",bt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ut=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>xi.has(ye(s.getExpression()))&&os(s,t)),Ei=(e,t)=>{if(ut(e,t))return!0;const s=G(e);return s!==void 0&&ut(s,t)},$e=(e,t)=>is(e,t)&&!Ei(e,t),$i=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=G(e);return t!==void 0&&i.isNewExpression(t)&&ye(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=G(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Ae=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&$e(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:bt(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();$e(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=W(r.getExpression());n!==void 0&&Ae(n,t,s)}},Nt=(e,t)=>{const s=W(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=W(r.getInitializer());n!==void 0&&Ae(n,"response-init",t)},yi=(e,t)=>{const s=ye(e.getExpression());if(s==="Response")Nt(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&Ae(r,"headers-ctor",t)}},Ai=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){Nt(e.getArguments()[1],t);return}if(hi.has(r)&&$i(n)){const o=e.getArguments()[1];o!==void 0&&$e(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:bt(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},Si=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))yi(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))Ai(s,t)},bi=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=Yt(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return Si(r,{exportName:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},Ni=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...bi(r,t));return s},vi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ni(n,g(t,r)))}return s},vt="identity.ts",Pi=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},wi=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},Ii=e=>{if(i.isIdentifier(e))return Pi(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&wi(t)}return!1},Li=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!Ii(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw H(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},Ti=(e,t)=>{const s=p(t,vt);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=Li(r);if(n.length!==0){if(n.length>1)throw H(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},Oi=new Set(["auth","context.auth","ctx.auth"]),Fi="userId",Di=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},Ci=(e,t)=>{const s=p(t,vt);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(S(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?Di(o):void 0}},lt=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Oi.has(e.getExpression().getText())?e:void 0},ki=e=>{if(i.isPropertyAccessExpression(e)&<(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&<(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},Ki=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=ki(n);o!==void 0&&r.push({declared:o===Fi||s.has(o),exportName:h(n),file:t,key:o,line:n.getStartLineNumber()})}return r},Ri=(e,t)=>{const s=Ci(e,t);if(s===void 0)return[];const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...Ki(o,g(t,n),s))}return r},ji=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Mi=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=ji(s);if(!(!r||!w(r)||O(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},zi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Mi(r,t);n&&s.push(n)}return s},qi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...zi(n,g(t,r)))}return s},Bi=new Set(["delete","get","getRaw","getWithMetadata","put"]),Vi=(e,t)=>X(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Bi}),Ui=new Set(["queue","send"]),dt=new Set(["bcc","cc","to"]),Wi=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ui.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},_i=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return dt.has(t.getName())&&w(r)&&!O(r)}if(!i.isPropertyAssignment(t)||!dt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!O(s)}):!1,Gi=(e,t)=>{const s=Wi(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!_i(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},Hi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Gi(r,t);n&&s.push(n)}return s},Qi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Hi(n,g(t,r)))}return s},Xi=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Zi=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()!==u.CallExpression)return;const s=t;return ks(s.getExpression())?s:void 0},Yi=e=>{const t=Ji(e),s=t===void 0?void 0:Zi(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>Xi(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},eo=e=>e.getVariableDeclarations().flatMap(t=>Yi(t)),to=(e,t)=>{const s=p(t,Cs);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return eo(r)},so=new Set(["delete","get","patch"]),ro=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),no=new Set(["auth","identity","session","user"]),io=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),oo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!C(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},ao=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},co=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),uo=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,lo=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>co(s.getExpression(),t)&&uo(s.getThenStatement())),go=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!so.has(n))continue;const o=r.getExpression();if(!(C(o)||i.isPropertyAccessExpression(o)&&C(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},po=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},fo=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>po(s)==="ctx")),mo=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>io.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),xo=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(ro.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&no.has(t.getName()))return!0}return fo(e)||mo(e)},ho=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=k(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=ht(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Et(r.receiver,"use","rls"),a=xo(n),c=new Set,l=[];for(const f of n.getDescendantsOfKind(u.CallExpression)){const $=oo(f);if($===void 0)continue;const I=ao(f);if(I===void 0||c.has(I)||!lo(n,I))continue;const K=go(n,I);K!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:f.getStartLineNumber(),mentionsOwnership:a,sinkMethod:K,table:$,usesRls:o,visibility:r.visibility}))}return l},Eo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=g(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ho(c,o))}return s},$o=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),yo=new Set(["insert","insertManyUnsafe","patch","replace"]),Ao=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!yo.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},So=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},bo=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!$o.has(a))&&w(c)&&!O(c)&&n.push({exportName:h(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},No=(e,t)=>{const s=Ao(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?So(r,s).flatMap(n=>bo(n,s,e,t)):[]},vo=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression))for(const o of No(n,t)){const a=s(o.exportName);r.push(a===void 0?o:{...o,visibility:a})}return r},Po=(e,t,s=[])=>{const r=[],n=new Map(s.map(o=>[`${o.filePath}:${o.exportName}`,o.visibility]));for(const o of d(t)){const a=e.getSourceFile(o)??e.addSourceFileAtPath(o),c=g(t,o);r.push(...vo(a,c,l=>n.get(`${c}:${l}`)))}return r},wo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Io=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,Lo=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?Io(t.getInitializer()):void 0},To=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!wo.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?Lo(o):void 0;s.push({callee:n,exportName:h(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},Oo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...To(n,g(t,r)))}return s},Fo=new Set(["defineQueue","defineWorkflow"]),Do=new Set(["run","runAction","runMutation","runQuery"]),Co=new Set(["api","internal"]),ko=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Ko=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},Pt=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},wt=(e,t)=>e===t||e.startsWith(`${t}.`),It=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},gt=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},Lt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>gt(s));return i.isIdentifier(e)&>(e)&&t.push(e),t},Ro=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},jo=e=>{const t=Pt(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},Mo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:jo(e),n=new Set,o=a=>It(a).some(c=>r.some(l=>wt(c.getText(),l)))?!0:Lt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of Ro(a))n.add(l)}return{names:n,prefixes:r}},zo=(e,t)=>It(e).some(s=>t.prefixes.some(r=>wt(s.getText(),r)))?!0:Lt(e).some(s=>t.names.has(s.getText())),qo=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!Co.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},Bo=(e,t,s)=>{const r=Pt(e,0);if(r===void 0)return[];const n=Mo(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Do.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!zo(l,n))continue;const f=qo(a.getArguments()[0]);f!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:h(a),line:a.getStartLineNumber(),targetExport:f.exportName,targetFile:f.file})}return o},Vo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ko(r);if(n===void 0||!Fo.has(n))continue;const o=Ko(r);o!==void 0&&s.push(...Bo(o,n==="defineQueue"?"queue":"workflow",t))}return s},Uo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Vo(n,g(t,r)))}return s},pt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},Wo=/account|credential|member|passkey|session|user/iu,_o=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},Go=(e,t)=>{const{objects:s,opaque:r}=At(e,t);return zr(s).some(n=>_o(n))?!0:r?void 0:!1},Se=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Ho=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Qo=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},V={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Xo=e=>{const t=Qo(e),s=t?Se(t):void 0;if(t&&s==="protectPublic"){const r=Ho(t);return{...V,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in pt?{...V,[pt[s]]:!0}:V},Zo=e=>{const t={...V};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=Xo(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},Jo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insert")return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!!(r&&i.isStringLiteral(r)&&Wo.test(r.getLiteralText()))},Yo=new Set(["create","runAfter","runAt","send","sendBatch"]),ea=new Set(["queues","scheduler","workflows"]),ta=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Yo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&ea.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},sa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Tt=new Set(["generateObject","generateText","streamObject","streamText"]),ra=e=>{const t=Se(e);return t!==void 0&&Tt.has(t)},na=e=>{const t=Se(e);if(t===void 0||!Tt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},ia=new Set(["log","span","trace"]),oa=new Set(["ai"]),aa=new Set(["email","mail"]),ca=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),B=(e,t)=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),ua=e=>e.getDescendantsOfKind(u.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),ft="lunora-advisor-exempt",la=/^[\s*/]+/u,da=/[\w-]/u,ga=e=>{const t=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
|
|
9
|
+
`);for(const s of t.split(`
|
|
10
|
+
`)){const r=s.replace(la,"");if(!r.startsWith(ft))continue;const n=r.slice(ft.length);if(da.test(n.charAt(0)))continue;const o=n.indexOf("--");return{exempt:!0,exemptReason:(o===-1?"":n.slice(o+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},pa=e=>{let t=!1,s=!1,r=!1,n=!1,o=!1;for(const a of e.getDescendantsOfKind(u.CallExpression))if(Jo(a)&&(o=!0),ta(a)&&(t=!0),sa(a)&&(n=!0),ra(a)&&(s=!0),na(a)&&(r=!0),o&&t&&n&&r)break;return{callsMail:B(e,aa),emitsEvent:B(e,ia),fanOut:t,handlesErrors:e.getDescendantsOfKind(u.TryStatement).length>0,reachesOutbound:B(e,ca),runsAiGeneration:s||B(e,oa),throwsBareError:ua(e),unboundedAiGeneration:r,usesInsertManyUnsafe:n,writesUserTable:o}},fa=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=k(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?Zo(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1};return{...pa(e),...ga(e),...n,exportName:e.getName(),file:t,hasEmailArg:Go(s,r.receiver),kind:r.kind,visibility:r.visibility}},ma=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=fa(n,t);o&&s.push(o)}return s},xa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ma(n,g(t,r)))}return s},ha=new Set(["dbRateLimit","rateLimit"]),Ea=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},$a=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},ya=e=>i.isArrowFunction(e)?e.getBody():e,Aa=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!ha.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=Ea(r);if(!n)return;const o=ya(n);if(!(!w(o)||O(o)))return{callee:s,exportName:h(e),file:t,limitName:$a(e),line:e.getStartLineNumber()}},Sa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Aa(r,t);n&&s.push(n)}return s},ba=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Sa(n,g(t,r)))}return s},Na=new Set(["findFirst","findFirstOrThrow","findMany","get"]),va=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Na.has(t.getName()))return;const s=t.getExpression();if(C(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&C(s.getExpression()))return s.getName()},Pa=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&C(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},wa=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},Ot=(e,t=!1)=>{const s=wa(e);if(i.isIdentifier(s)){if(t)return;const r=G(s);return r===void 0?void 0:Ot(r,!0)}if(i.isCallExpression(s))return va(s)??Pa(s)},Ia=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},La=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=k(s);if(r?.kind!=="query")return[];const n=ht(s);if(n===void 0)return[];const o=r.receiver!==void 0&&es(r.receiver,"output"),a=r.receiver!==void 0&&Et(r.receiver,"use","mask"),c=new Set,l=[];for(const f of Ia(n)){const $=Ot(f);$===void 0||c.has($)||(c.add($),l.push({exportName:e.getName(),file:t,line:f.getStartLineNumber(),table:$,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},Ta=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=g(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...La(c,o))}return s},Oa=new Set(["findFirst","findFirstOrThrow","findMany"]),Fa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Oa.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Da=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},Ca=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},ka=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?k(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Fa(o);if(a===void 0)continue;const c=Da(Ca(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},Ka=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=g(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ka(c,o))}return s},_=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=_(e.getLeft()),s=_(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Ra=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&_(t)!==void 0},ja=/(?:^|\/)__tests__\//u,Ma=/\.(?:spec|test)$/u,za=e=>ja.test(e)||Ma.test(e),qa=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()===u.EqualsToken)return t.getLeft().getText()}},Ba=(e,t,s)=>Qs(e)?!za(s)&&Xs(qa(t)):!0,Va=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(Ra(o))continue;const a=_(o);if(a===void 0)continue;const c=Gs(a);if(c===void 0||!Ba(c,o,t))continue;const l=o.getStartLineNumber(),f=`${String(l)}:${c}`;n.has(f)||(n.add(f),s.push({file:t,kind:c,line:l,preview:Hs(a)}))}return s},Ua=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Va(n,g(t,r)))}return s},Wa=new Set(["findFirst","findFirstOrThrow","findMany"]),_a=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Wa.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Ga=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},Ha=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?k(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=_a(o);if(a===void 0)continue;const c=Ga(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),f=!l&&w(c);!l&&!f||n.push({exportName:e.getName(),file:t,fromArgs:f,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},Qa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=g(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ha(c,o))}return s},Xa=new Set(["query","unsafe"]),Za=e=>{if(!i.isPropertyAccessExpression(e)||!Xa.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"},Ja=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Ya=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",ec=(e,t)=>{if(!Za(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ja(s)))return{exportName:Ya(e),file:t,line:s.getStartLineNumber()}},tc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ec(r,t);n&&s.push(n)}return s},sc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...tc(n,g(t,r)))}return s},rc=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),nc=(e,t)=>X(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:rc}),ic=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),oc=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,ac=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=oc(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},cc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=ic.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},uc=(e,t)=>{const s=cc(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...ac(e.getArguments()[s.optionsIndex])}},lc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=uc(r,t);n&&s.push(n)}return s},dc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...lc(n,g(t,r)))}return s},gc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),be=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&gc.has(s)?s:void 0},Ft=e=>{const t=e.getInitializer();return t===void 0?!1:i.isCallExpression(t)||i.isIdentifier(t)||i.isPropertyAccessExpression(t)},Dt={cause:"codegen recognises a procedure only when the initializer is a builder chain, and this one is produced by a call or an alias",remediation:"A factory that returns a procedure cannot be read statically — inline it, or export the chain the factory builds."},pc={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."},Ne=(e,t,s,r,n)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${r.toString()}) has type \`${s}\` but was not registered — ${n.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:r,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${n.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),fc=(e,t,s)=>{const r=[];for(const n of e.getVariableStatements().filter(o=>o.isExported()))for(const o of n.getDeclarations()){const a=o.getName();if(s.has(`${t}:${a}`)||!Ft(o))continue;const c=be(o);c!==void 0&&r.push(Ne(t,a,c,o.getStartLineNumber(),Dt))}return r},mc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const r=[];for(const n of e.getExportAssignments().filter(o=>!o.isExportEquals())){const o=be(n.getExpression());o!==void 0&&r.push(Ne(t,"default",o,n.getStartLineNumber(),Dt))}return r},xc=(e,t,s)=>{const r=[];for(const n of e.getExportDeclarations().filter(o=>o.getModuleSpecifier()===void 0))for(const o of n.getNamedExports()){const a=o.getAliasNode()?.getText()??o.getName();if(s.has(`${t}:${a}`))continue;const c=o.getLocalTargetDeclarations().find(f=>i.isVariableDeclaration(f));if(c===void 0||!Ft(c))continue;const l=be(c);l!==void 0&&r.push(Ne(t,a,l,o.getStartLineNumber(),pc))}return r},hc=(e,t,s)=>[...fc(e,t,s),...mc(e,t,s),...xc(e,t,s)],Ec=(e,t,s)=>{const r=new Set(s.map(o=>`${o.filePath}:${o.exportName}`)),n=[];for(const o of d(t)){const a=e.getSourceFile(o);a!==void 0&&n.push(...hc(a,g(t,o),r))}return n.toSorted((o,a)=>o.cacheKey.localeCompare(a.cacheKey))},$c=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),yc=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return Ee.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return Ee.has(n)?n:void 0}const s=t.getText();return Ee.has(s)?s:void 0},Ac=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,Ct=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Ac(e))return"empty-object";if(i.isParenthesizedExpression(e))return Ct(e.getExpression())}},kt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Kt=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>kt(t)===e),Rt=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>kt(t)===e),Sc=e=>{const t=Kt(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Rt(e).length>0},bc=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Kt(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Rt(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},Nc=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},vc=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!$c.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Sc(a))for(const c of bc(a)){const l=Ct(c);l!==void 0&&n.push({exportName:Nc(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},Pc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=yc(r);n!==void 0&&s.push(...vc(r,n,t))}return s},wc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Pc(n,g(t,r)))}return s},Ic=new Set(["query","upsert","upsertMany"]),Lc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(Ic.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},Tc=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Oc=(e,t)=>{const s=Lc(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=Tc(r);if(!(!n||!w(n)||O(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},Fc=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Oc(r,t);n&&s.push(n)}return s},Dc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Fc(n,g(t,r)))}return s},Cc=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"},kc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Kc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=g(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!Cc(a))continue;const c=Ys(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:kc(a)})}}return s},Rc=".lunora-schema.json",A=(e,t)=>{E(e)&&xt(e,"utf8")===t||Ht(e,t,"utf8")},P=(e,t)=>{if(t===""){Qt(e,{force:!0});return}A(e,t)},jc=e=>{const t=p(e,"package.json");if(E(t))try{const s=JSON.parse(xt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},Mc=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},zc=e=>{let t=E(e)?e:fe(e);for(;t&&t!==fe(t);){const s=p(t,"tsconfig.json");if(E(s))return s;t=fe(t)}},mt=e=>e.replaceAll("\\","/"),qc=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new R("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new R("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new R("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},Bc=e=>{const t=zc(e);return t?new et({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new et({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},Ou=(e,t)=>{const s=d(t),r=p(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>mt(c))),o=mt(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},Fu=e=>{const t=Mc(),s=t?me.now():0,r=p(e.projectRoot,e.lunoraDirectory??"lunora"),n=p(r,"schema.ts");if(!E(n))throw new R("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??Bc(r);or(ss);const a=_s(o,n,e.projectRoot),c=ts(o,r),l=Is(o,r),f=Ds(o,r),$=Zs(o,r),I=Ks(o,r),K=Ti(o,r),ve=kn(o,r),N=er(o,r),F=qs(o,r),v=rs(o,r);qc(N,v);const Z=ls(o,r,N,v),D=us(o,r),j=e.lint===!1?void 0:Jt({adminRoutes:$r(o,r),aiRawRuns:br(o,r),aiToolSideEffects:Dr(o,r),argumentDerivedFetches:Rr(o,r),argumentValidators:Qr(o,r),authApiCalls:cs(o,r),authConfigs:an(o,r),browserUrlAccesses:gn(o,r),configCalls:yn(o,r),containerKeyAccesses:Sn(o,r),containerOverrides:Ln(o,r),containers:D,exportSinks:Mn(o,r),failOpenGuards:_n(o,r),flagSecurityDefaults:ni(o,r),geoIndexUsages:ai(o,r),httpActionGuards:mi(o,r),httpHeaderWrites:vi(o,r),identityClaimReads:Ri(o,r),imageDeliveryUrlAccesses:qi(o,r),inserts:Ls(o,r),kvKeyAccesses:Vi(o,r),mailRecipientAccesses:Qi(o,r),maskProcedures:Ts(o,r),maskStrategies:Os(o,r),mutatorWrites:to(o,r),nondeterministicCalls:Rs(o,r),normalizeIdAuthorizations:Eo(o,r),notifyCalls:Ms(o,r),notifyConfig:js(o,r),ownerFieldWrites:Po(o,r,c),unrestrictedWhereBranches:wc(o,r),paymentWebhooks:Oo(o,r),privilegedDispatches:Uo(o,r),procedureProtections:xa(o,r),queries:as(o,r),queues:F,r2sqlCalls:Bs(o,r),ratelimitKeySelectors:ba(o,r),rawRowReturns:Ta(o,r),relationLoads:Ka(o,r),rlsProcedures:Vs(o,r),schema:a,secretLiterals:Ua(o,r),shapes:$,softDeleteReads:Qa(o,r),sqlInterpolations:sc(o,r),storageKeyAccesses:nc(o,r),storageUploads:dc(o,r),vectorNamespaceAccesses:Dc(o,r),workflowCalls:Kc(o,r),workflows:N,wranglerVariables:e.wranglerVariables}),Pe=j===void 0?[]:[...Xt(j,{source:"static"}),...Ec(o,r,c)],jt=Us(o,r),Mt=Fs(o,r),J=Js(o,r),zt=Hn(o,r),we=ar(zt,cr(e.projectRoot,e.target)),y=we.usage,Y=y.ai,ee=y.payments,Ie=y.kv,Le=y.access,te=E(p(r,"flags.ts")),qt=te?ws(o,r):[],se=E(p(r,"notify.ts")),re=y.hyperdrive,ne=Ws(o,r),Bt=ne.usesSandboxBrowser||ne.usesSandboxContainer,ie=y.browser||ne.usesSandboxBrowser,oe=y.images,ae=y.analytics,Te=y.pipelines,ce=y.r2sql,ue=y.x402,Oe=zs(e.projectRoot),L=Oe??new Set,M=Jn(y,{containerCount:D.length,cronCount:Z.length,dependencies:L,hasPaymentTables:Zn(a.tables),queueCount:F.length,storageColumnCount:Object.keys(ds(a)).length,storageRuleCount:J.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:N.length}),T=L.has("lunorash");dr(a,Oe);const Fe=t?me.now():0,De=gs(a,T),Ce=ps({agents:v,functions:c,httpRoutes:l,mutators:I,useUmbrella:T,workflows:N}),ke=fs({agents:v,containers:D,env:ve,hasAccessFacade:Le,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:Ie,hasNotify:se,hasPayments:ee,hasPipelines:Te,hasR2sql:ce,hasX402:ue,identity:K,queues:F,schema:a,storageRuleBuckets:J.rules.map(m=>m.bucket),useUmbrella:T,workflows:N}),Ke=ms({agents:v,functions:c,migrations:f,mutators:I,shapes:$,useUmbrella:T,usesSandbox:Bt}),le=ur(a,f.map(m=>m.id)),Re=xs({advisories:Pe,advisorProcedures:j?.procedureProtections??[],agents:v,containers:D,env:ve,flagKeys:qt,hasAccessFacade:Le,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:Ie,hasNotify:se,hasPayments:ee,hasPipelines:Te,hasR2sql:ce,hasX402:ue,maskMetadata:Mt,mutators:I,queues:F,rlsMetadata:jt,schema:a,schemaSnapshot:le,shapes:$,storageRules:J,studioFeatures:M,useUmbrella:T,workflows:N}),je=hs($,L.has("@lunora/db"),T),Me=Es(D,a.jurisdiction),ze=$s(N),qe=ys(v),Be=As(F),Ve=Ss(Z),Ue=bs(a.vectorIndexes),z=Ns(a,T),We=vs(L.has("@lunora/seed")),q=e.apiSpec??"openapi",de=q==="openapi"||q==="both",ge=q==="openrpc"||q==="both",_e=tr({emailAgents:v.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:L.has("@lunora/cloudflare-access"),hasAi:Y,hasAnalytics:ae,hasAuth:L.has("@lunora/auth"),hasBrowser:ie,hasFramework:L.has("@lunora/astro")||L.has("@lunora/svelte")||L.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:re,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:oe,hasKv:M.kv,hasNotify:se,hasPayments:ee,hasR2sql:ce,hasQueue:F.some(m=>m.mode==="push"),hasScheduler:M.scheduler,hasStorage:M.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:N.length>0,hasX402:ue,identity:K,jurisdiction:a.jurisdiction,useUmbrella:T,voiceAgents:v.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:de,wantsOpenRpc:ge}),Ge=jc(e.projectRoot),He=sr({functions:c,httpRoutes:l,version:Ge}),Qe=nr({functions:c,version:Ge}),Xe=`${JSON.stringify(He,void 0,2)}
|
|
11
|
+
`,Ze=`${JSON.stringify(Qe,void 0,2)}
|
|
12
|
+
`,Je=rr(He),Ye=ir(Qe),pe=p(r,Rc),Vt=E(pe),x=p(r,"_generated");if(e.dryRun||(E(x)||Gt(x,{recursive:!0}),A(p(x,"app.ts"),_e),A(p(x,"dataModel.ts"),De),A(p(x,"api.ts"),Ce),A(p(x,"server.ts"),ke),A(p(x,"functions.ts"),Ke),A(p(x,"shard.ts"),Re),A(p(x,"crons.ts"),Ve),A(p(x,"vectors.ts"),Ue),A(p(x,"drizzle.global.ts"),z.global),A(p(x,"drizzle.shard.ts"),z.shard),P(p(x,"containers.ts"),Me),P(p(x,"workflows.ts"),ze),P(p(x,"agents.ts"),qe),P(p(x,"queues.ts"),Be),P(p(x,"seed.ts"),We),P(p(x,"collections.ts"),je),P(p(x,"openapi.json"),de?Xe:""),P(p(x,"openapi.ts"),de?Je:""),P(p(x,"openrpc.json"),ge?Ze:""),P(p(x,"openrpc.ts"),ge?Ye:""),(!Vt||e.updateSchemaBaseline===!0)&&A(pe,Zt(le))),t){const m=me.now(),Ut=Math.round(m-s),Wt=Math.round(Fe-s),_t=Math.round(m-Fe);console.error(`@lunora/codegen: codegen took ${Ut.toString()}ms (discovery ${Wt.toString()}ms, emit ${_t.toString()}ms)`)}return{advisories:Pe,advisorContext:j,agents:v,containers:D,cronTriggers:Ps(Z),generated:{agents:qe,api:Ce,app:_e,collections:je,containers:Me,crons:Ve,dataModel:De,drizzleGlobal:z.global,drizzleShard:z.shard,functions:Ke,openApi:Xe,openApiModule:Je,openRpc:Ze,openRpcModule:Ye,queues:Be,seed:We,server:ke,shard:Re,vectors:Ue,workflows:ze},outputDirectory:x,platformDiagnostics:we.diagnostics,queues:F,schemaSnapshot:le,schemaSnapshotPath:pe,workflows:N}};export{Rc as SCHEMA_SNAPSHOT_FILENAME,Bc as createCodegenProject,Ou as refreshCodegenProject,Fu as runCodegen};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as g,sortKeys as m,diffSchemaSnapshots as b,parseSnapshotJson as S}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{serializeSchemaSnapshot as H}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";const w=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,k=e=>e.kind==="optional"?{kind:e.inner?.kind??"unknown",optional:!0}:{kind:e.kind,optional:!1},$=e=>{const a={};for(const[n,s]of Object.entries(e.shape))a[n]=k(s);const t={};for(const n of e.indexes)t[n.name]={fields:[...n.fields],unique:n.unique??!1};const r={};for(const n of e.relations)r[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:a,indexes:t,relations:r,shardMode:w(e.shardMode)}},x=(e,a)=>{const t={};for(const n of e.tables)t[n.name]=$(n);const r=[...a].sort();return{jurisdiction:e.jurisdiction,migrationIds:r,tables:m(t),version:g}};class v extends p{constructor(a){super("SCHEMA_SNAPSHOT_PARSE",a,{name:"SchemaSnapshotParseError"})}}const A=e=>{const a=S(e);if(a.status==="invalid")throw new v(a.error);return a.status==="ok"?a.snapshot:void 0},y={deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},h=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",f=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",I=e=>{const a=e===void 0?void 0:y[e];if(e===void 0||a===void 0)return`${h}
|
|
2
|
+
${f}
|
|
3
|
+
`;const t=a.updateBaseline?f:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${h}
|
|
4
|
+
${t}
|
|
5
|
+
`},D=e=>{const{allowDrift:a=!1,baseline:t,command:r,current:n}=e,s=b(t,n),d=s.changes.filter(i=>i.severity==="breaking"),o=n.migrationIds.filter(i=>!(t?.migrationIds??[]).includes(i));if(s.changes.length===0||t===void 0)return{blocked:!1,changes:s.changes,newMigrationIds:o,reason:""};if(d.length===0){const i=s.changes.map(u=>` - ${u.summary}`).join(`
|
|
6
|
+
`);return{blocked:!1,changes:s.changes,newMigrationIds:o,reason:`schema drift detected (all additive/safe):
|
|
7
|
+
${i}`}}const l=d.map(i=>` - ${i.summary}`).join(`
|
|
8
|
+
`);if(o.length>0)return{blocked:!1,changes:s.changes,newMigrationIds:o,reason:`breaking schema drift detected, but ${String(o.length)} new migration(s) were added (${o.join(", ")}):
|
|
9
|
+
${l}`};const c=`deploy blocked: ${String(d.length)} breaking schema change(s) detected since the last blessed schema baseline — these changes are incompatible with existing data without a migration:
|
|
10
|
+
${l}
|
|
11
|
+
|
|
12
|
+
To fix:
|
|
13
|
+
• For breaking changes: add a \`defineMigration({ id, table, up })\` in lunora/ for each affected table, then run \`lunora migrate\` (or \`lunora codegen\`) to apply and re-bless the baseline.
|
|
14
|
+
${I(r)}Docs: https://lunora.dev/docs/migrations`;return a?{blocked:!1,changes:s.changes,newMigrationIds:o,reason:`${c}
|
|
15
|
+
|
|
16
|
+
(overridden by --allow-schema-drift)`}:{blocked:!0,changes:s.changes,newMigrationIds:o,reason:c}};export{g as SCHEMA_SNAPSHOT_VERSION,v as SchemaSnapshotParseError,x as buildSchemaSnapshot,b as diffSchemaSnapshots,D as evaluateSchemaDrift,A as parseSchemaSnapshot,H as serializeSchemaSnapshot};
|
package/dist/packem_shared/{buildOpenApiDocument-D46nZ7D_.mjs → buildOpenApiDocument-XeZ1ycwi.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{w as v}from"./emit-05q6XTbd.mjs";import{n as c}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as S,objectSchema as b,argsObjectSchema as g,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const O="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie"],h=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],m=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,f=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const n=o.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(m(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(m(e.staleWhileRevalidate))}`),r.join(", ")},k=e=>e.scope==="public"?f(e.vary,...P(e),...h):f(e.vary,...h),R=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)}},j=e=>{const t=R(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},q=e=>e==="query"?"GET":"POST",l="#/components/responses/LunoraError",y=/:([A-Za-z_$][\w$]*)/gu,A=e=>[...e.matchAll(y)].map(t=>t[1]),w=e=>e.replaceAll(y,"{$1}"),N=e=>{const t=new Set(A(e.path)),r=[];for(const[o,n]of Object.entries(e.searchParams)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:n.kind!=="optional",schema:u(p)})}for(const[o,n]of Object.entries(e.params)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:n.kind!=="optional",schema:u(p)})}return r},C=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."},E=e=>{const t=c(e.filePath),r=N(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${c(e.path)}`,responses:{200:C(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:l}},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:b(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=c(e.filePath),o={additionalProperties:!1,properties:{args:g(e.args),functionPath:{const:t,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}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:t,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:{content:{"application/json":{schema:{description:"RPC result. The shape is TS-inferred from the function's return type; best-effort — any JSON."}}},description:"Successful RPC result (TypeScript-inferred return shape, documented best-effort)."},default:{$ref:l}},summary:`${e.kind}: ${t}`,tags:[r],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${t}`}},_=(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 n=k(r);return n!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:n,type:"string"}}),{headers:o}},I=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=j(t);if(r===void 0)return;const o=c(e.filePath),n=q(e.kind),p=n==="GET",a={description:`Public REST endpoint for the \`${e.kind}\` \`${t}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${c(r)}`,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).",..._(e.expose?.cache,p?"get":"post")},default:{$ref:l}},summary:`${n} ${r}`,tags:[o],"x-lunora-function-kind":e.kind};if(p){const s=Object.entries(e.args).map(([i,d])=>{const $=d.kind==="optional"?d.inner??d:d;return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:d.kind!=="optional",schema:u($)}});return s.length>0&&(a.parameters=s),{method:"get",operation:a,path:r}}return a.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:a,path:r}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const a of e.httpRoutes){const s=w(a.path),i=r[s]??{};i[a.method.toLowerCase()]=E(a),r[s]=i,o.add(c(a.filePath))}const n=e.functions.filter(a=>a.visibility!=="internal"&&a.kind!=="stream");for(const a of n){const{operation:s,pathKey:i}=L(a);r[i]={post:s},o.add(c(a.filePath))}for(const a of n){if(a.expose?.rest!==!0)continue;const s=I(a);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i,o.add(c(a.filePath))}const p=[...o].toSorted((a,s)=>a.localeCompare(s)).map(a=>({description:`Operations declared in \`lunora/${a}\`.`,name:a}));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:S,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:p}},U=e=>`${JSON.stringify(D(e),void 0,2)}
|
|
2
2
|
`,W=e=>`${v}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{D as buildOpenApiDocument,U as emitOpenApi,W as emitOpenApiModule};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{Node as s,SyntaxKind as A}from"ts-morph";import{diagnosticAt as u}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{c as j}from"./parse-validator-_jDrFxwt.mjs";import{createRequire as N}from"node:module";import{join as _}from"node:path";const O=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},z=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),f=e=>{const r=e?._meta??{},t=e?.kind??"unknown",n={column:z(r.column),kind:t};switch(t){case"array":case"optional":{n.inner=f(r.inner);break}case"id":{n.tableName=r.tableName;break}case"literal":{n.literalValue=O(r.value);break}case"object":{const i=r.shape??{};n.shape=Object.fromEntries(Object.entries(i).map(([o,a])=>[o,f(a)]));break}case"record":{n.valueType=f(r.valueValidator),r.keyValidator!==void 0&&(n.keyType=f(r.keyValidator));break}case"storage":{typeof r.bucket=="string"&&(n.bucket=r.bucket);break}case"union":{const i=r.members??[];n.members=i.map(o=>f(o));break}}return n},M=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",D=(e,r)=>{const t=[];e.relationMap&&Object.keys(e.relationMap).length>0&&t.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&t.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&t.push("vector indexes"),t.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${r}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},B=(e,r)=>{const t=e.shape??{},n=(e.indexes??[]).map(i=>({fields:i.fields,name:i.name,...i.unique?{unique:!0}:{}}));return D(e,r),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:n,name:r,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(i=>({field:i.field,...i.filterFields?{filterFields:i.filterFields}:{},...i.language===void 0?{}:{language:i.language},...i.staged===void 0?{}:{staged:i.staged},...i.strategy===void 0?{}:{strategy:i.strategy},name:i.name})),shape:Object.fromEntries(Object.entries(t).map(([i,o])=>[i,f(o)])),shardMode:M(e.shardMode),vectorIndexes:[]}},F=e=>{const{key:r,tables:t}=e;if(typeof r!="string"||typeof t!="object"||t===null)return;const n=Object.entries(t).map(([a,l])=>B(l,a)),i=e.vectorIndexes??{},o=Object.entries(i??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:n,bareVectorIndexes:o,key:r}},q=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e)){const r=e.getExpression();return s.isIdentifier(r)?r.getText():void 0}},C=e=>{const r=q(e);if(r===void 0)return;const t=s.isPropertyAccessExpression(e)?e.getName():void 0,n=t===void 0?[]:[t];for(const i of e.getSourceFile().getImportDeclarations()){const o=i.getModuleSpecifierValue();for(const a of i.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===r)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:n};if(i.getDefaultImport()?.getText()===r)return{importedName:"default",moduleSpecifier:o,propertyPath:n};if(i.getNamespaceImport()?.getText()===r&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},R=(e,r)=>{let t=e[r.importedName];for(const n of r.propertyPath){if(typeof t!="object"||t===null)return;t=t[n]}return t},V=(e,r)=>{const t=C(e);if(t)try{const n=N(_(r,"noop.cjs")),i=n.resolve(t.moduleSpecifier),o=n(i),a=R(o,t);return typeof a!="object"||a===null?void 0:F(a)}catch{return}},J=new Set(["cosine","dot-product","euclidean"]),U=new Set(["cascade","restrict","set null"]),v=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),K=(e,r)=>{if(v.has(e))throw u(r,`table name "${e}" is reserved — it collides with a \`ctx.db\` member (one of ${[...v].map(t=>`"${t}"`).join(", ")}). Rename the table.`)},d=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isStringLiteral(n))return n.getLiteralText()}},m=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isNumericLiteral(n))return Number(n.getLiteralText())}},Q=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&(s.isTrueLiteral(n)||s.isFalseLiteral(n)))return n.getLiteralValue()}},h=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isArrayLiteralExpression(n))return n.getElements().filter(i=>s.isStringLiteral(i)).map(i=>i.getLiteralText())}},L=e=>e&&J.has(e)?e:void 0,X=e=>e&&U.has(e)?e:void 0,G=e=>{if(!s.isArrowFunction(e))return;let r=e.getBody();if(s.isParenthesizedExpression(r))r=r.getExpression();else if(s.isBlock(r)){const t=r.getStatements().find(n=>s.isReturnStatement(n));r=t&&s.isReturnStatement(t)?t.getExpression()??r:r}return s.isObjectLiteralExpression(r)?r:void 0},H=e=>{if(!s.isPropertyAssignment(e))return;const r=e.getInitializer();if(!r||!s.isCallExpression(r))return;const t=r.getExpression();if(!s.isPropertyAccessExpression(t))return;const n=t.getName();if(n!=="one"&&n!=="many")return;const[i,o]=r.getArguments(),a=i&&s.isStringLiteral(i)?i.getLiteralText():"_unknown_";let l="_unknown_",c="_id",g;return o&&s.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,g=n==="one"?X(d(o,"onDelete")):void 0),{field:l,kind:n,name:e.getName(),onDelete:g,references:c,table:a}},W=e=>{const r=G(e);if(!r)return[];const t=[];for(const n of r.getProperties()){const i=H(n);i&&t.push(i)}return t},x=e=>e&&s.isStringLiteral(e)?e.getLiteralText():"_unnamed_",Y=(e,r,t)=>{if(!r.includes("."))return;const[n="",...i]=r.split("."),o=`${n}${i.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw u(e,`index "${t}" indexes the nested path ${JSON.stringify(r)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`)},Z=e=>{if(!e||!s.isObjectLiteralExpression(e))return!1;const r=e.getProperty("unique");if(!r||!s.isPropertyAssignment(r))return!1;const t=r.getInitializer();if(t===void 0)return!1;if(!s.isTrueLiteral(t)&&!s.isFalseLiteral(t))throw u(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return s.isTrueLiteral(t)},ee=e=>{const[r,t,n]=e,i=Z(n),o=x(r),a=t&&s.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!s.isStringLiteral(c))throw u(c,`index "${o}" lists a non-literal field (${JSON.stringify(c.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(c=>s.isStringLiteral(c));for(const c of l)Y(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:i}},te=e=>{const[r,t]=e;let n="_unknown_",i,o,a,l;return t&&s.isObjectLiteralExpression(t)&&(n=d(t,"field")??n,i=h(t,"filterFields"),o=d(t,"language"),a=Q(t,"staged"),l=d(t,"strategy")),{field:n,filterFields:i,language:o,name:x(r),staged:a,strategy:l}},re=e=>{const[r,t]=e;let n="_unknown_",i;return t&&s.isObjectLiteralExpression(t)&&(n=d(t,"field")??n,i=m(t,"precision")),{field:n,name:x(r),precision:i}},ne=e=>{const[r,t]=e,n=r&&s.isStringLiteral(r)?r.getLiteralText():"_unknown_";let i;return t&&s.isObjectLiteralExpression(t)&&(i=m(t,"after")),{after:i,field:n}},ie=e=>{if(!s.isObjectLiteralExpression(e))return;const r=d(e,"field");return r===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:r}},se=e=>{const[r,t]=e;let n=[],i;if(t&&s.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&s.isPropertyAssignment(o)){const a=o.getInitializer();a&&s.isArrayLiteralExpression(a)&&(n=a.getElements().map(l=>ie(l)).filter(l=>l!==void 0))}i=h(t,"partitionBy")}return{name:x(r),partitionBy:i,sortBy:n}},oe=(e,r)=>{const[t,n]=e,i=t&&s.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!n||!s.isObjectLiteralExpression(n)))return{dimensions:m(n,"dimensions"),field:i,metadata:h(n,"metadata"),metric:L(d(n,"metric")),name:d(n,"index")??"_unnamed_",table:r}},ae=e=>{const r=e[0];return r&&s.isObjectLiteralExpression(r)&&d(r,"backend")==="hyperdrive"?"hyperdrive":"d1"},le=e=>{if(e&&s.isObjectLiteralExpression(e)){const r=e.getProperty("field");if(r&&s.isPropertyAssignment(r)){const t=r.getInitializer();if(t&&s.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},p=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isStringLiteral(n))return n.getLiteralText()}},ce=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&s.isArrayLiteralExpression(n)){const i=n.getElements().filter(o=>s.isStringLiteral(o)).map(o=>o.getLiteralText());return i.length>0?i:void 0}}},de=e=>{const r=e[0];return!r||!s.isObjectLiteralExpression(r)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:p(r,"binding")??"",columns:ce(r,"columns"),hasReconcile:r.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:r.getProperty("softDeleteColumn")!==void 0,hasTenantBy:r.getProperty("tenantBy")!==void 0,idColumn:p(r,"idColumn"),mode:p(r,"mode"),query:p(r,"query")}},ue=(e,r,t,n)=>{switch(r){case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(re(t));break}case"global":{e.shardMode="global",e.globalBackend=ae(t);break}case"index":{e.indexes.push(ee(t));break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(se(t));break}case"relations":{const i=t[0];i&&e.relations.push(...W(i));break}case"searchIndex":{e.searchIndexes.push(te(t));break}case"shardBy":{const i=t[0];e.shardMode={field:i&&s.isStringLiteral(i)?i.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:le(t[0])};break}case"source":{e.externalSource=de(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=ne(t);break}case"vectorize":{const i=oe(t,n);i&&e.vectorIndexes.push(i);break}}},E=["__vocab","_config","_content","_data","_docsize","_idx"],ge=(e,r,t)=>{const n=new Set(t.map(i=>i.name));for(const i of t)for(const o of E){const a=`${i.name}${o}`;if(!n.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${i.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw u(e,`table "${r}" declares search indexes "${i.name}" and "${a}", whose generated FTS5 tables collide: "${i.name}" already owns "${r}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${E.join(", ")}.`)}},P=(e,r)=>{const t={externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let n={},i=e;for(;s.isCallExpression(i);){const o=i.getExpression(),a=i.getArguments();if(s.isPropertyAccessExpression(o))ue(t,o.getName(),a,r),i=o.getExpression();else if(s.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&s.isObjectLiteralExpression(l))n=j(l);else if(l)throw u(l,`table "${r}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${r}\` / \`Insert_${r}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in n)&&(n={...n,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),ge(e,r,t.searchIndexes),{externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,name:r,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:n,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},fe=e=>{const r=e.getProperty("source");if(r&&s.isPropertyAssignment(r)){const t=r.getInitializer();if(t&&s.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},pe=e=>{if(!s.isPropertyAssignment(e))return;const r=e.getInitializer();if(!r||!s.isCallExpression(r))return;const t=r.getExpression();if(!s.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const n=r.getArguments()[0];if(!n||!s.isObjectLiteralExpression(n))return;const i=e.getNameNode(),o=s.isStringLiteral(i)?i.getLiteralText():i.getText();return{dimensions:m(n,"dimensions"),metric:L(d(n,"metric")),name:o,table:fe(n)}},S=e=>{const r=[];for(const t of e.getProperties()){const n=pe(t);n&&r.push(n)}return r},I=(e,r)=>`${e}_${r}`,y=(e,r,t)=>t.has(e)?I(r,e):e,me=(e,r,t)=>{const n=I(r,e.name);return{...e,extensionKey:r,name:n,relations:e.relations.map(i=>({...i,table:y(i.table,r,t)})),vectorIndexes:e.vectorIndexes.map(i=>({...i,table:y(i.table,r,t)}))}},xe=e=>{if(s.isVariableDeclaration(e)||s.isPropertyAssignment(e))return e.getInitializer();if(s.isShorthandPropertyAssignment(e))return e.getNameNode()},be=(e,r)=>{const t=e.getProperty(r);if(t&&s.isPropertyAssignment(t))return t.getInitializer()},ye=e=>{if(!s.isCallExpression(e))return!1;const r=e.getExpression();return s.isIdentifier(r)&&r.getText()==="defineSchemaExtension"},he=e=>{if(s.isIdentifier(e))return e;if(s.isPropertyAccessExpression(e)){const r=e.getExpression();return s.isIdentifier(r)?r:void 0}},Ie=e=>{if(s.isObjectLiteralExpression(e))return e;if(s.isCallExpression(e)){const r=e.getExpression();let t;if(s.isIdentifier(r)?t=r.getText():s.isPropertyAccessExpression(r)&&(t=r.getName()),t==="definePlugin"){const n=e.getArguments()[1];return n&&s.isObjectLiteralExpression(n)?n:void 0}}},ke=(e,r)=>{const t=xe(e);if(t){if(s.isPropertyAccessExpression(r)){const n=Ie(t);return n?be(n,r.getName()):void 0}return t}},ve=e=>{let r=e,t=0;for(;r&&t<32;){if(t+=1,ye(r))return r;const n=he(r),i=n&&s.isIdentifier(n)?n.getSymbol():void 0,o=(i?.getAliasedSymbol()?.getDeclarations()??i?.getDeclarations()??[])[0];if(!o)return;const a=o.getSourceFile();if(a.isInNodeModules()||a.isDeclarationFile())return;r=ke(o,r)}},Ee=e=>{const[r,t]=e.getArguments();if(!(!r||!s.isStringLiteral(r))&&!(!t||!s.isObjectLiteralExpression(t)))return{key:r.getLiteralText(),options:t}},Le=e=>{const r=e.getProperty("tables");if(!r||!s.isPropertyAssignment(r))return[];const t=r.getInitializer();if(!t||!s.isObjectLiteralExpression(t))return[];const n=[];for(const i of t.getProperties()){if(!s.isPropertyAssignment(i))continue;const o=i.getInitializer();o&&n.push(P(o,i.getName()))}return n},Pe=e=>{const r=e.getProperty("vectorIndexes");if(!r||!s.isPropertyAssignment(r))return[];const t=r.getInitializer();return!t||!s.isObjectLiteralExpression(t)?[]:S(t)},w=(e,r,t)=>{const n=new Set(r.map(a=>a.name)),i=r.map(a=>me(a,e,n)),o=t.map(a=>({...a,name:I(e,a.name),table:y(a.table,e,n)}));return{tables:i,vectorIndexes:o}},Se=(e,r)=>w(e,Le(r),Pe(r)),we=(e,r)=>{const t=e.getArguments()[0];if(!t)return;const n=ve(t);if(!n){if(r!==void 0){const o=V(t,r);if(o)return w(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${r===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const i=Ee(n);if(!i){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Se(i.key,i.options)},Te=e=>{const r=[];let t=e;for(;;){const n=t.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;n.getName()==="extend"&&r.push(i),t=i}return r},T=(e,r,t,n,i)=>{let o=e;for(;;){const a=o.getParent();if(!a||!s.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!s.isCallExpression(l))break;if(a.getName()===r){const c=l.getArguments()[0];if(!c||!s.isStringLiteral(c))throw u(l,`\`.${r}(...)\` expects a string literal (${i})`);const g=c.getLiteralText();if(!n.has(g))throw u(c,`unknown ${t} ${JSON.stringify(g)} — expected ${i}`);return g}o=l}},$e=new Set(["eu","fedramp","us"]),Ae=e=>T(e,"jurisdiction","jurisdiction",$e,'"eu", "us", or "fedramp"'),je=new Set(["required"]),Ne=e=>T(e,"rls","rls mode",je,'"required"'),_e=e=>{const r=[];for(const t of e.getProperties()){if(!s.isPropertyAssignment(t))continue;const n=t.getInitializer();if(n){const i=t.getName();K(i,t.getNameNode()),r.push(P(n,i))}}return r},Oe=(e,r,t)=>{const n=new Set(r.map(o=>o.name)),i=[];for(const o of Te(e)){const a=we(o,t);if(a){for(const l of a.tables){if(n.has(l.name))throw u(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);n.add(l.name),r.push(l)}i.push(...a.vectorIndexes)}}return i},Ce=(e,r,t)=>{const n=e.addSourceFileAtPath(r).getDescendantsOfKind(A.CallExpression).find(b=>{const k=b.getExpression();return s.isIdentifier(k)&&k.getText()==="defineSchema"});if(!n)throw new $("INTERNAL",`defineSchema() not found in ${r}`);const i=n.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))throw u(n,"defineSchema() expects an object literal");const o=_e(i),a=n.getArguments()[1],l=a&&s.isObjectLiteralExpression(a)?S(a):[],c=Oe(n,o,t),g=[...o.flatMap(b=>b.vectorIndexes),...l,...c];return{jurisdiction:Ae(n),rlsMode:Ne(n),tables:o,vectorIndexes:g}};export{Ce as default};
|