@lunora/codegen 1.0.0-alpha.154 → 1.0.0-alpha.155

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 CHANGED
@@ -1402,6 +1402,14 @@ interface KvKeyAccessIR {
1402
1402
  line: number;
1403
1403
  /** The `ctx.kv` method invoked: `get` / `getRaw` / `getWithMetadata` / `put` / `delete`. */
1404
1404
  method: string;
1405
+ /**
1406
+ * Visibility of the enclosing procedure. `internal` procedures have no
1407
+ * untrusted caller by construction — see `owner_field_from_args_not_auth`'s
1408
+ * identical split — so `kv_unscoped_user_key_idor` drops the finding to
1409
+ * INFO rather than ERROR there. `undefined` when the access sits outside any
1410
+ * registered procedure the feeder could attribute it to.
1411
+ */
1412
+ visibility?: "internal" | "public";
1405
1413
  }
1406
1414
  /**
1407
1415
  * One `ctx.db` write (`insert` / `replace` / `patch` / `insertManyUnsafe`) that sets
@@ -3164,6 +3172,14 @@ interface EmitShardOptions {
3164
3172
  hasPipelines?: boolean;
3165
3173
  /** A `lunora/` source reads `ctx.r2sql` (R2 SQL) — wires `ctx.r2sql` onto the ActionCtx only. */
3166
3174
  hasR2sql?: boolean;
3175
+ /**
3176
+ * The target platform supports a vector store. `false` withholds the whole
3177
+ * Vectorize wiring — the `@lunora/bindings/vectors` imports, the
3178
+ * `createVectorSyncHook` write hook and `vectors` on the runtime ctx — even
3179
+ * when the schema declares an index, mirroring what `emitServer` and
3180
+ * `emitApp` withhold from the type surface for the same verdict.
3181
+ */
3182
+ hasVectors?: boolean;
3167
3183
  /** A `lunora/` source reads `ctx.x402` — wires the agent-wallet pay rail onto the ActionCtx only. */
3168
3184
  hasX402?: boolean;
3169
3185
  maskMetadata?: MaskMetadataIR;
@@ -3189,7 +3205,7 @@ interface EmitShardOptions {
3189
3205
  useUmbrella?: boolean;
3190
3206
  workflows?: ReadonlyArray<WorkflowIR>;
3191
3207
  }
3192
- declare const emitShard: ({ advisories, advisorProcedures, agents, containers, env, flagKeys, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasX402, maskMetadata, mutators, queues, rlsMetadata, schema, schemaSnapshot, shapes, storageRules, studioFeatures, useUmbrella, workflows }: EmitShardOptions) => string;
3208
+ declare const emitShard: ({ advisories, advisorProcedures, agents, containers, env, flagKeys, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasVectors, hasX402, maskMetadata, mutators, queues, rlsMetadata, schema, schemaSnapshot, shapes, storageRules, studioFeatures, useUmbrella, workflows }: EmitShardOptions) => string;
3193
3209
  /**
3194
3210
  * Emit drizzle `sqliteTable` definitions for the project schema, split into
3195
3211
  * `global` (D1-backed) and `shard` (DO-SQLite-backed) buckets. Tables marked
@@ -3304,8 +3320,15 @@ interface EmitAppOptions {
3304
3320
  hasScheduler: boolean;
3305
3321
  /** App uses `@lunora/storage` → emit `.storage()` (DO `ctx.storage` + studio file browser). */
3306
3322
  hasStorage: boolean;
3307
- /** Schema declares vector indexes → emit `.vectors()` (the Vectorize index map backing `ctx.vectors`). */
3308
- hasVectors: boolean;
3323
+ /**
3324
+ * The target platform supports a vector store — the gate's verdict, NOT the
3325
+ * app's declaration, on the same convention `emitServer` and `emitShard`
3326
+ * take it: `.vectors()` is emitted only when this AND
3327
+ * {@link EmitAppOptions.vectorIndexCount} are both set. Defaults to `true` so
3328
+ * a caller that does not gate (tests, fixtures) is unchanged; the index count
3329
+ * alone then decides, as it did before the gate existed.
3330
+ */
3331
+ hasVectors?: boolean;
3309
3332
  /** App declares Cloudflare Workflows (`defineWorkflow`) → wire `options.workflowsClient` so the studio's workflow-instance proxy can reach the CF REST API. */
3310
3333
  hasWorkflow: boolean;
3311
3334
  /** App uses `@lunora/x402/pay` / `ctx.x402` → emit `.x402()` (wire the agent-wallet pay rail). */
@@ -3324,6 +3347,8 @@ interface EmitAppOptions {
3324
3347
  tableNames: ReadonlyArray<string>;
3325
3348
  /** Project depends on the unscoped `lunorash` umbrella → import the runtime via `lunorash/runtime` instead of `@lunora/runtime`. */
3326
3349
  useUmbrella: boolean;
3350
+ /** Number of `.vectorize()` / `defineVectorIndex(...)` indexes the schema declares — the app-side half of {@link EmitAppOptions.hasVectors}. Defaults to `0`. */
3351
+ vectorIndexCount?: number;
3327
3352
  /**
3328
3353
  * Voice-enabled agents (`defineAgent({ voice: … })`) → wire
3329
3354
  * `options.voiceAgents`, mapping each agent's export name to its `VOICE_*`
@@ -3355,7 +3380,7 @@ interface EmitAppOptions {
3355
3380
  * it can import the add-on packages the app installed (`@lunora/auth`,
3356
3381
  * `@lunora/storage`, …) directly.
3357
3382
  */
3358
- declare const emitApp: (options: EmitAppOptions) => string;
3383
+ declare const emitApp: (rawOptions: EmitAppOptions) => string;
3359
3384
  /** Inputs the OpenAPI emitter needs from a codegen run. */
3360
3385
  interface OpenApiEmitInput {
3361
3386
  functions: ReadonlyArray<FunctionIR>;
package/dist/index.d.ts CHANGED
@@ -1402,6 +1402,14 @@ interface KvKeyAccessIR {
1402
1402
  line: number;
1403
1403
  /** The `ctx.kv` method invoked: `get` / `getRaw` / `getWithMetadata` / `put` / `delete`. */
1404
1404
  method: string;
1405
+ /**
1406
+ * Visibility of the enclosing procedure. `internal` procedures have no
1407
+ * untrusted caller by construction — see `owner_field_from_args_not_auth`'s
1408
+ * identical split — so `kv_unscoped_user_key_idor` drops the finding to
1409
+ * INFO rather than ERROR there. `undefined` when the access sits outside any
1410
+ * registered procedure the feeder could attribute it to.
1411
+ */
1412
+ visibility?: "internal" | "public";
1405
1413
  }
1406
1414
  /**
1407
1415
  * One `ctx.db` write (`insert` / `replace` / `patch` / `insertManyUnsafe`) that sets
@@ -3164,6 +3172,14 @@ interface EmitShardOptions {
3164
3172
  hasPipelines?: boolean;
3165
3173
  /** A `lunora/` source reads `ctx.r2sql` (R2 SQL) — wires `ctx.r2sql` onto the ActionCtx only. */
3166
3174
  hasR2sql?: boolean;
3175
+ /**
3176
+ * The target platform supports a vector store. `false` withholds the whole
3177
+ * Vectorize wiring — the `@lunora/bindings/vectors` imports, the
3178
+ * `createVectorSyncHook` write hook and `vectors` on the runtime ctx — even
3179
+ * when the schema declares an index, mirroring what `emitServer` and
3180
+ * `emitApp` withhold from the type surface for the same verdict.
3181
+ */
3182
+ hasVectors?: boolean;
3167
3183
  /** A `lunora/` source reads `ctx.x402` — wires the agent-wallet pay rail onto the ActionCtx only. */
3168
3184
  hasX402?: boolean;
3169
3185
  maskMetadata?: MaskMetadataIR;
@@ -3189,7 +3205,7 @@ interface EmitShardOptions {
3189
3205
  useUmbrella?: boolean;
3190
3206
  workflows?: ReadonlyArray<WorkflowIR>;
3191
3207
  }
3192
- declare const emitShard: ({ advisories, advisorProcedures, agents, containers, env, flagKeys, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasX402, maskMetadata, mutators, queues, rlsMetadata, schema, schemaSnapshot, shapes, storageRules, studioFeatures, useUmbrella, workflows }: EmitShardOptions) => string;
3208
+ declare const emitShard: ({ advisories, advisorProcedures, agents, containers, env, flagKeys, hasAccessFacade, hasAi, hasAnalytics, hasBrowser, hasFlags, hasHyperdrive, hasImages, hasKv, hasNotify, hasPayments, hasPipelines, hasR2sql, hasVectors, hasX402, maskMetadata, mutators, queues, rlsMetadata, schema, schemaSnapshot, shapes, storageRules, studioFeatures, useUmbrella, workflows }: EmitShardOptions) => string;
3193
3209
  /**
3194
3210
  * Emit drizzle `sqliteTable` definitions for the project schema, split into
3195
3211
  * `global` (D1-backed) and `shard` (DO-SQLite-backed) buckets. Tables marked
@@ -3304,8 +3320,15 @@ interface EmitAppOptions {
3304
3320
  hasScheduler: boolean;
3305
3321
  /** App uses `@lunora/storage` → emit `.storage()` (DO `ctx.storage` + studio file browser). */
3306
3322
  hasStorage: boolean;
3307
- /** Schema declares vector indexes → emit `.vectors()` (the Vectorize index map backing `ctx.vectors`). */
3308
- hasVectors: boolean;
3323
+ /**
3324
+ * The target platform supports a vector store — the gate's verdict, NOT the
3325
+ * app's declaration, on the same convention `emitServer` and `emitShard`
3326
+ * take it: `.vectors()` is emitted only when this AND
3327
+ * {@link EmitAppOptions.vectorIndexCount} are both set. Defaults to `true` so
3328
+ * a caller that does not gate (tests, fixtures) is unchanged; the index count
3329
+ * alone then decides, as it did before the gate existed.
3330
+ */
3331
+ hasVectors?: boolean;
3309
3332
  /** App declares Cloudflare Workflows (`defineWorkflow`) → wire `options.workflowsClient` so the studio's workflow-instance proxy can reach the CF REST API. */
3310
3333
  hasWorkflow: boolean;
3311
3334
  /** App uses `@lunora/x402/pay` / `ctx.x402` → emit `.x402()` (wire the agent-wallet pay rail). */
@@ -3324,6 +3347,8 @@ interface EmitAppOptions {
3324
3347
  tableNames: ReadonlyArray<string>;
3325
3348
  /** Project depends on the unscoped `lunorash` umbrella → import the runtime via `lunorash/runtime` instead of `@lunora/runtime`. */
3326
3349
  useUmbrella: boolean;
3350
+ /** Number of `.vectorize()` / `defineVectorIndex(...)` indexes the schema declares — the app-side half of {@link EmitAppOptions.hasVectors}. Defaults to `0`. */
3351
+ vectorIndexCount?: number;
3327
3352
  /**
3328
3353
  * Voice-enabled agents (`defineAgent({ voice: … })`) → wire
3329
3354
  * `options.voiceAgents`, mapping each agent's export name to its `VOICE_*`
@@ -3355,7 +3380,7 @@ interface EmitAppOptions {
3355
3380
  * it can import the add-on packages the app installed (`@lunora/auth`,
3356
3381
  * `@lunora/storage`, …) directly.
3357
3382
  */
3358
- declare const emitApp: (options: EmitAppOptions) => string;
3383
+ declare const emitApp: (rawOptions: EmitAppOptions) => string;
3359
3384
  /** Inputs the OpenAPI emitter needs from a codegen run. */
3360
3385
  interface OpenApiEmitInput {
3361
3386
  functions: ReadonlyArray<FunctionIR>;
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-CWESEYLi.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CRdh_pOr.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-BvqYMy81.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-B5Qmjmyk.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as h}from"./packem_shared/CONTAINERS_FILENAME-BssQL6eI.mjs";import{default as L}from"./packem_shared/discoverCrons-c0ig327z.mjs";import{FLAGS_FILENAME as I,discoverFlags as F}from"./packem_shared/FLAGS_FILENAME-Bn_wWM4d.mjs";import{default as P}from"./packem_shared/discoverFunctions-DeuEs6Ce.mjs";import{default as G}from"./packem_shared/discoverHttpRoutes-zWSSyyOj.mjs";import{default as b}from"./packem_shared/discoverHyperdriveCalls-C6kV2CPz.mjs";import{default as y}from"./packem_shared/discoverInserts-BB7o_8pU.mjs";import{d as j}from"./packem_shared/index-BsVoa-4F.mjs";import{default as V}from"./packem_shared/discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-DHX1qUP5.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-B07wjsd2.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-BH0djo6F.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-D8DheHbi.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CIfuMMG3.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-CuHe5smg.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-DXdr9YHi.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CXWVNLk4.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-BJHLHZR_.mjs";import{default as xe}from"./packem_shared/discoverSchema-D5XGH2wu.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-DhZ3JkkH.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-CSqONfHS.mjs";import{G as Me,e as he,a as _e,b as Le,c as Te,d as Ie,f as Fe,g as De,h as Pe,i as Ue,j as Ge,k as He,l as be,m as ke}from"./packem_shared/emit-Dsr5DNpc.mjs";import{emitApp as We}from"./packem_shared/emitApp-kFg_xYlc.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-ZdoDQXmt.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as qe,emitOpenRpc as Be,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-BAgBIsQM.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-lPq34YeN.mjs";import{SCHEMA_SNAPSHOT_FILENAME as or,createCodegenProject as tr,findTsconfig as sr,refreshCodegenProject as ar,runCodegen as ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-S3Ey8df4.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as fr,evaluateSchemaDrift as pr,parseSchemaSnapshot as cr}from"./packem_shared/SchemaSnapshotParseError-yrVM8bTa.mjs";import{schemaFromIr as lr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as xr,validatorIrToJsonSchema as Er}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as ur,SDK_TARGETS as vr,generateSdk as Nr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Or,secretKindOf as Rr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Mr,findSolutionByMessage as hr}from"@lunora/errors";import{isTypedSchema as Lr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,Xe as DEFAULT_TARGET,I as FLAGS_FILENAME,Me as GENERATED_HEADER,xr as LUNORA_ERROR_CODES,Mr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,we as OPENRPC_VERSION,se as QUEUES_FILENAME,or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ur as SDK_LANGUAGES,vr as SDK_TARGETS,Ae as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,qe as buildOpenRpcDocument,fr as buildSchemaSnapshot,tr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,R as discoverAuthApiCalls,h as discoverContainers,L as discoverCrons,F as discoverFlags,P as discoverFunctions,G as discoverHttpRoutes,b as discoverHyperdriveCalls,y as discoverInserts,j as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Re as discoverWorkflows,he as emitAgents,_e as emitApi,We as emitApp,Le as emitCollections,Te as emitContainers,Ie as emitCrons,Fe as emitDataModel,De as emitDrizzleSchema,Pe as emitFunctions,Ve as emitOpenApi,ze as emitOpenApiModule,Be as emitOpenRpc,Je as emitOpenRpcModule,Ue as emitServer,Ge as emitShard,He as emitVectors,be as emitWorkflows,ke as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,pr as evaluateSchemaDrift,hr as findLunoraSolution,sr as findTsconfig,m as formatAdvisories,Nr as generateSdk,Lr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,cr as parseSchemaSnapshot,Ze as platformMatrixIds,ee as readPackageDependencies,$e as readProjectTarget,Or as redact,ar as refreshCodegenProject,er as resolveCodegenTarget,ir as runCodegen,lr as schemaFromIr,Rr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Er as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-CRdh_pOr.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-BvqYMy81.mjs";import{default as R}from"./packem_shared/discoverAuthApiCalls-B5Qmjmyk.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as h}from"./packem_shared/CONTAINERS_FILENAME-BssQL6eI.mjs";import{default as L}from"./packem_shared/discoverCrons-c0ig327z.mjs";import{FLAGS_FILENAME as I,discoverFlags as F}from"./packem_shared/FLAGS_FILENAME-Bn_wWM4d.mjs";import{default as P}from"./packem_shared/discoverFunctions-DeuEs6Ce.mjs";import{default as G}from"./packem_shared/discoverHttpRoutes-zWSSyyOj.mjs";import{default as b}from"./packem_shared/discoverHyperdriveCalls-C6kV2CPz.mjs";import{default as y}from"./packem_shared/discoverInserts-BB7o_8pU.mjs";import{d as j}from"./packem_shared/index-BsVoa-4F.mjs";import{default as V}from"./packem_shared/discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-DHX1qUP5.mjs";import{default as B}from"./packem_shared/discoverNondeterministicCalls-B07wjsd2.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-BH0djo6F.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-D8DheHbi.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-CIfuMMG3.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-CuHe5smg.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-DXdr9YHi.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CXWVNLk4.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-BJHLHZR_.mjs";import{default as xe}from"./packem_shared/discoverSchema-C4znXEB-.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-DhZ3JkkH.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{WORKFLOWS_FILENAME as Oe,discoverWorkflows as Re}from"./packem_shared/WORKFLOWS_FILENAME-CSqONfHS.mjs";import{G as Me,e as he,a as _e,b as Le,c as Te,d as Ie,f as Fe,g as De,h as Pe,i as Ue,j as Ge,k as He,l as be,m as ke}from"./packem_shared/emit-B6ud4F_z.mjs";import{emitApp as We}from"./packem_shared/emitApp-BSxrIa6e.mjs";import{buildOpenApiDocument as Ke,emitOpenApi as Ve,emitOpenApiModule as ze}from"./packem_shared/buildOpenApiDocument-DIboMAh6.mjs";import{OPENRPC_VERSION as we,buildOpenRpcDocument as qe,emitOpenRpc as Be,emitOpenRpcModule as Je}from"./packem_shared/OPENRPC_VERSION-DWdTwXvO.mjs";import{DEFAULT_TARGET as Xe,platformMatrixIds as Ze,readProjectTarget as $e,resolveCodegenTarget as er}from"./packem_shared/DEFAULT_TARGET-lPq34YeN.mjs";import{SCHEMA_SNAPSHOT_FILENAME as or,createCodegenProject as tr,findTsconfig as sr,refreshCodegenProject as ar,runCodegen as ir}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-B9OxLwqq.mjs";import{SchemaSnapshotParseError as dr,buildSchemaSnapshot as fr,evaluateSchemaDrift as pr,parseSchemaSnapshot as cr}from"./packem_shared/SchemaSnapshotParseError-yrVM8bTa.mjs";import{schemaFromIr as lr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as xr,validatorIrToJsonSchema as Er}from"./packem_shared/LUNORA_ERROR_CODES-BYg8Lpgb.mjs";import{SDK_LANGUAGES as ur,SDK_TARGETS as vr,generateSdk as Nr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Or,secretKindOf as Rr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Mr,findSolutionByMessage as hr}from"@lunora/errors";import{isTypedSchema as Lr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,Xe as DEFAULT_TARGET,I as FLAGS_FILENAME,Me as GENERATED_HEADER,xr as LUNORA_ERROR_CODES,Mr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,we as OPENRPC_VERSION,se as QUEUES_FILENAME,or as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ur as SDK_LANGUAGES,vr as SDK_TARGETS,Ae as SHAPES_FILENAME,dr as SchemaSnapshotParseError,e as VERSION,Oe as WORKFLOWS_FILENAME,Ke as buildOpenApiDocument,qe as buildOpenRpcDocument,fr as buildSchemaSnapshot,tr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,R as discoverAuthApiCalls,h as discoverContainers,L as discoverCrons,F as discoverFlags,P as discoverFunctions,G as discoverHttpRoutes,b as discoverHyperdriveCalls,y as discoverInserts,j as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,B as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Re as discoverWorkflows,he as emitAgents,_e as emitApi,We as emitApp,Le as emitCollections,Te as emitContainers,Ie as emitCrons,Fe as emitDataModel,De as emitDrizzleSchema,Pe as emitFunctions,Ve as emitOpenApi,ze as emitOpenApiModule,Be as emitOpenRpc,Je as emitOpenRpcModule,Ue as emitServer,Ge as emitShard,He as emitVectors,be as emitWorkflows,ke as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,pr as evaluateSchemaDrift,hr as findLunoraSolution,sr as findTsconfig,m as formatAdvisories,Nr as generateSdk,Lr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,cr as parseSchemaSnapshot,Ze as platformMatrixIds,ee as readPackageDependencies,$e as readProjectTarget,Or as redact,ar as refreshCodegenProject,er as resolveCodegenTarget,ir as runCodegen,lr as schemaFromIr,Rr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Er as validatorIrToJsonSchema};
@@ -1 +1 @@
1
- import"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-Dsr5DNpc.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
1
+ import"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{G as t,U as m,n as r,e as o,a as n,b as l,c as A,d as E,f as S,g,h as C,o as c,p as d,i as p,j as u,k as D,l as f,m as h}from"./emit-B6ud4F_z.mjs";import"./paths-C-9fwEgQ.mjs";export{t as GENERATED_HEADER,m as UMBRELLA_BASE_PACKAGES,r as buildStorageColumns,o as emitAgents,n as emitApi,l as emitCollections,A as emitContainers,E as emitCrons,S as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,c as emitQueues,d as emitSeed,p as emitServer,u as emitShard,D as emitVectors,f as emitWorkflows,h as emitWranglerCronTriggers};
@@ -1,3 +1,3 @@
1
- import{G as c}from"./emit-Dsr5DNpc.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
1
+ import{G as c}from"./emit-B6ud4F_z.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
2
2
  `,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
@@ -0,0 +1,9 @@
1
+ import{existsSync as P,mkdirSync as cs,readFileSync as bt,writeFileSync as ls,rmSync as us}from"node:fs";import{join as f,dirname as X}from"node:path";import{performance as ge}from"node:perf_hooks";import{runAdvisor as ds}from"@lunora/advisor";import{LunoraError as k}from"@lunora/errors";import{SyntaxKind as l,Node as o,Project as Je}from"ts-morph";import{serializeSchemaSnapshot as fs}from"./SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs";import{toAdvisorContext as ps}from"./formatAdvisories-CkEu1eye.mjs";import{s as gs}from"./paths-C-9fwEgQ.mjs";import{discoverAgents as ms}from"./AGENTS_FILENAME-CRdh_pOr.mjs";import{discoverContainers as hs}from"./CONTAINERS_FILENAME-BssQL6eI.mjs";import xs from"./discoverCrons-c0ig327z.mjs";import{diagnosticAt as re}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as ie}from"./module-specifiers-WF8iAydP.mjs";import{C as me,i as Es,f as vs,n as Ss,j as ys,b as As,c as Ns,l as bs,e as Ps,o as Is,d as ws,k as Ts,g as Cs,p as Fs,m as Os,a as Rs,h as Ls}from"./emit-B6ud4F_z.mjs";import{listLunoraSourceFiles as m,lunoraRelativePath as v,collectCallRows as w,collectSecurityCallRows as Ds,propertyInitializer as N,listSecurityScanFiles as Pt,limitNameOf as It,isContextIdentifier as ve,handlerOf as ks,isDatabaseAccessor as M,unwrapExpression as et,readTargetOf as wt,enclosingExportName as Ms}from"./listLunoraSourceFiles-BvqYMy81.mjs";import Ks from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as _s}from"./QUEUES_FILENAME-CIfuMMG3.mjs";import{discoverSandboxUsage as zs}from"./discoverSandboxUsage-BJHLHZR_.mjs";import Us from"./discoverStorageRulesMetadata-CUa2Dtb4.mjs";import{discoverWorkflows as Bs}from"./WORKFLOWS_FILENAME-CSqONfHS.mjs";import{gatePlatformFeatures as $s,resolveCodegenTarget as qs}from"./DEFAULT_TARGET-lPq34YeN.mjs";import{i as R,a as _,e as E,r as js,b as Vs,s as oe,c as Ws,f as Hs,d as Gs}from"./queries-D8DheHbi.mjs";import{a as y,c as z,d as Tt,e as Ys}from"./classify-procedure-call-CRm5Etni.mjs";import Qs from"./discoverAuthApiCalls-B5Qmjmyk.mjs";import tt from"./discoverFunctions-DeuEs6Ce.mjs";import{i as Xs,r as Zs,e as Js}from"./unwrap-handler-return-CmIWbykC.mjs";import st from"./discoverHttpRoutes-zWSSyyOj.mjs";import en from"./discoverHyperdriveCalls-C6kV2CPz.mjs";import tn from"./discoverInserts-BB7o_8pU.mjs";import{m as be,a as J,s as Ct,d as sn}from"./index-BsVoa-4F.mjs";import{e as Ft}from"./exported-procedure-chains-Cmt3Pr92.mjs";import nn from"./discoverMigrations-CQjGLKW-.mjs";import{MUTATORS_FILENAME as rn,isDefineMutatorCallee as on,discoverMutators as nt}from"./MUTATORS_FILENAME-DHX1qUP5.mjs";import an from"./discoverNondeterministicCalls-B07wjsd2.mjs";import{discoverNotifyConfig as cn,discoverNotifyCalls as ln}from"./NOTIFY_FILENAME-BH0djo6F.mjs";import un from"./discoverR2sqlCalls-CuHe5smg.mjs";import dn from"./discoverRlsProcedures-DXdr9YHi.mjs";import fn from"./discoverRlsMetadata-CXWVNLk4.mjs";import pn from"./discoverSchema-C4znXEB-.mjs";import{secretKindOf as gn,redact as mn,isHeuristicSecretKind as hn,isSecretishName as xn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as En}from"./SHAPES_FILENAME-DhZ3JkkH.mjs";import{emitApp as vn}from"./emitApp-BSxrIa6e.mjs";import{buildOpenApiDocument as Sn,emitOpenApiModule as yn}from"./buildOpenApiDocument-DIboMAh6.mjs";import{buildOpenRpcDocument as An,emitOpenRpcModule as Nn}from"./OPENRPC_VERSION-DWdTwXvO.mjs";import{s as bn}from"./parse-validator-CMV0eq2a.mjs";import{buildSchemaSnapshot as Pn}from"./SchemaSnapshotParseError-yrVM8bTa.mjs";const rt=(e,t="api")=>{const s=new Map;for(const n of e){const i=gs(n),r=s.get(i);if(r===void 0){s.set(i,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${i}" twice and the dispatch key "${i}:<fn>" would be ambiguous`:`the generated api.ts would declare "${i}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new k("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${i}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},In=(e,t=!0)=>{const s=[],n=e.tables.filter(i=>i.shardMode==="global");return n.some(i=>i.globalBackend!=="hyperdrive")&&s.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),n.some(i=>i.globalBackend==="hyperdrive")&&s.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'}),e.vectorIndexes.length>0&&t&&s.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"}),s},wn=(e,t,s=!0)=>{if(t===void 0)return;const n=In(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const i=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
2
+ `);throw new k("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
3
+ ${i}
4
+
5
+ Install them with your package manager, then re-run codegen.`)},Tn="env.ts",Cn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return ie(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(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ie(n.getModuleSpecifierValue())}return!1},On=e=>{if(o.isIdentifier(e))return Cn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&o.isIdentifier(t)&&Fn(t)}return!1},Rn=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!On(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw re(r,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},Ln=(e,t)=>{const s=f(t,Tn);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=Rn(n);if(i.length!==0){if(i.length>1)throw re(n,`lunora/env.ts declares ${i.length.toString()} defineEnv() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Ot=e=>{const t=n=>o.isIdentifier(n)&&n.getText()==="ctx",s=new Set;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression))t(n.getExpression())&&s.add(n.getName());for(const n of e.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getInitializer(),r=n.getNameNode();if(!(i===void 0||!t(i)||!o.isObjectBindingPattern(r)))for(const a of r.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Dn=(e,t)=>{const s=Object.fromEntries(me.map(n=>[n.key,!1]));for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=new Set(i.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Ot(i);for(const c of me)if(!s[c.key]){if(r.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(me.every(c=>s[c.key]))break}return s},Rt="identity.ts",kn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(o.isImportSpecifier(s))return ie(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},Mn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!o.isNamespaceImport(s))continue;const n=s.getFirstAncestorByKind(l.ImportDeclaration);return n!==void 0&&ie(n.getModuleSpecifierValue())}return!1},Kn=e=>{if(o.isIdentifier(e))return kn(e);if(o.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&o.isIdentifier(t)&&Mn(t)}return!1},_n=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const n=s.getInitializer();if(n?.getKind()!==l.CallExpression||!Kn(n.getExpression()))continue;const r=s.getNameNode();if(!o.isIdentifier(r))throw re(r,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:r.getText()})}return t},zn=(e,t)=>{const s=f(t,Rt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s),i=_n(n);if(i.length!==0){if(i.length>1)throw re(n,`lunora/identity.ts declares ${i.length.toString()} defineIdentity() contracts (${i.map(r=>r.exportName).join(", ")}); exactly one is allowed`);return i[0]}},Lt=e=>o.isParenthesizedExpression(e)?Lt(e.getExpression()):e,Un=e=>o.isObjectLiteralExpression(e)&&e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t))return t.getName()==="durable";if(!o.isPropertyAssignment(t)||t.getName()!=="durable")return!1;const s=t.getInitializer();return s===void 0||Lt(s).getText()!=="false"}),Bn=(e,t)=>{const s={durableStreams:!1,secrets:!1};for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);if(s.secrets||(s.secrets=Ot(i).has("secrets")),s.durableStreams||(s.durableStreams=i.getDescendantsOfKind(l.CallExpression).some(r=>{const a=r.getExpression();return(o.isPropertyAccessExpression(a)?a.getName():a.getText())==="stream"&&r.getArguments().some(u=>Un(u))})),s.durableStreams&&s.secrets)break}return s},$n=(e,t)=>{const s=new Map,n=new Map,i=new Map;for(const r of e)s.set(r.name,`workflow "${r.exportName}"`),n.set(r.bindingName,`workflow "${r.exportName}"`),i.set(r.className,`workflow "${r.exportName}"`);for(const r of t){const a=s.get(r.name);if(a!==void 0)throw new k("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${r.name}": produced by both ${a} and agent "${r.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=n.get(r.bindingName);if(c!==void 0)throw new k("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${r.bindingName}": produced by both ${c} and agent "${r.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const u=i.get(r.className);if(u!==void 0)throw new k("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${r.className}": produced by both ${u} and agent "${r.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},qn=e=>{const{lunoraDirectory:t,project:s,projectRoot:n,schema:i}=e,r=zn(s,t),a=Ln(s,t),c=Bs(s,t),u=_s(s,t),d=ms(s,t);$n(c,d);const S=hs(s,t),x=Us(s,t),I=xs(s,t,c,d),g=Bn(s,t),A=zs(s,t),C=Dn(s,t);C.browser=C.browser||A.usesSandboxBrowser;const L=$s(C,qs(n,e.target),{agents:d.length>0,commitOrderedTables:i.tables.some(p=>p.commitOrdered===!0),cronTriggers:I.length>0,crossShardFanout:i.tables.some(p=>typeof p.shardMode=="object"),durableStreams:g.durableStreams,globalTables:i.tables.some(p=>p.shardMode==="global"),queues:u.length>0,secrets:g.secrets,vectorStore:i.vectorIndexes.length>0}),b=L.usage,D=L.signals.vectorStore!==!1,U=Ks(n),$=U??new Set,W=$.has("lunorash");wn(i,U,D);const K=P(f(t,"flags.ts")),F=P(f(t,"notify.ts"));return{agents:d,containers:S,crons:I,dataModelContent:vs(i),declaredDependencies:U,dependencies:$,env:a,featureUsage:b,hasFlags:K,hasNotify:F,identity:r,platformGate:L,queues:u,serverContent:Es({agents:d,containers:S,env:a,hasAccessFacade:b.access,hasAi:b.ai,hasAnalytics:b.analytics,hasBrowser:b.browser,hasVectors:D,hasFlags:K,hasHyperdrive:b.hyperdrive,hasImages:b.images,hasKv:b.kv,hasNotify:F,hasPayments:b.payments,hasPipelines:b.pipelines,hasR2sql:b.r2sql,hasX402:b.x402,identity:r,queues:u,schema:i,storageRuleBuckets:x.rules.map(p=>p.bucket),useUmbrella:W,workflows:c}),storageRulesMetadata:x,usesSandbox:A.usesSandboxBrowser||A.usesSandboxContainer||A.usesSandboxFs,useUmbrella:W,workflows:c}},Dt=new Set(["delete","get","head","options","patch","post","put"]),jn=new Set(["handler","stream"]),Vn=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,it=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Wn=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Dt.has(t.getName()))return;const s=t.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpRoute")return;const n=e.getArguments()[0];if(!(!n||!o.isStringLiteral(n)))return{method:t.getName().toUpperCase(),path:n.getLiteralValue()}},Hn=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||Dt.has(n.getName()))break;s=n.getExpression()}return Wn(s)},Gn=e=>{for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression))if(it.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&it.has(s.getText()))return!0}return!1},Yn=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=s.getExpression();if(!o.isPropertyAccessExpression(n)||!jn.has(n.getName()))return;const i=Hn(s);if(!i||!Vn.test(i.path))return;const r=s.getArguments()[0],a=r!==void 0&&(o.isArrowFunction(r)||o.isFunctionExpression(r))&&Gn(r);return{exportName:e.getName(),file:t,method:i.method,path:i.path,usesGuard:a}},Qn=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Yn(i,t);r&&s.push(r)}return s},Xn=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qn(i,v(t,n)))}return s},Zn=e=>!o.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",Jn=(e,t)=>{if(!Zn(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)||_(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},er=(e,t)=>w(e,t,Jn),tr=new Set(["generateText","streamText"]),sr=new Set(["messages","prompt","system"]),nr=[{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"]}],rr=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=t.getName(),n=t.getExpression().getText();for(const i of nr)if(i.methods.has(s)&&i.prefixes.some(r=>n===r||n.startsWith(`${r}.`)))return`${n}.${s}`},ir=e=>{for(const t of e.getDescendantsOfKind(l.CallExpression)){const s=rr(t);if(s!==void 0)return s}},or=e=>{const t=new Set,s=e.getFirstAncestor(r=>o.isArrowFunction(r)||o.isFunctionExpression(r)||o.isFunctionDeclaration(r)),[n]=s?.getParameters()??[],i=n?.getNameNode();if(i===void 0||!o.isObjectBindingPattern(i))return t;for(const r of i.getElements()){const a=r.getPropertyNameNode()?.getText()??r.getName(),c=r.getNameNode();if(a==="args"&&o.isObjectBindingPattern(c))for(const u of c.getElements())t.add(u.getName())}return t},ar=e=>{if(js(e))return!0;const t=or(e);return t.size===0?!1:e.getDescendantsOfKind(l.Identifier).some(s=>t.has(s.getText()))},cr=e=>{for(const t of e.getProperties()){if(!o.isPropertyAssignment(t)||!sr.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&ar(s))return!0}return!1},lr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=y(n.getExpression());if(i===void 0||!tr.has(i))continue;const[r]=n.getArguments();if(r===void 0||!o.isObjectLiteralExpression(r))continue;let a;for(const c of r.getDescendantsOfKind(l.CallExpression))if(y(c.getExpression())==="tool"&&(a=ir(c),a!==void 0))break;a!==void 0&&s.push({exportName:E(n),file:t,line:n.getStartLineNumber(),method:i,sideEffect:a,userInputDerived:cr(r)})}return s},ur=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...lr(i,v(t,n)))}return s},dr=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return o.isIdentifier(t)&&t.getText()==="ctx"},fr=(e,t)=>{if(!dr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!R(s)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},pr=(e,t)=>w(e,t,fr),kt=e=>e.getProperties().some(t=>o.isSpreadAssignment(t)),gr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!o.isPropertyAssignment(s))return{objects:[],opaque:!0};const n=s.getInitializer();return!n||!o.isObjectLiteralExpression(n)?{objects:[],opaque:!0}:{objects:[n],opaque:kt(n)}},mr=e=>{const t=[];let s=!1,n=e;for(;o.isCallExpression(n);){const i=n.getExpression();if(!o.isPropertyAccessExpression(i))break;if(i.getName()==="input"){const r=n.getArguments()[0];r&&o.isObjectLiteralExpression(r)?(t.push(r),s||=kt(r)):s=!0}n=i.getExpression()}return{objects:t,opaque:s}},Mt=(e,t)=>t?mr(t):gr(e),hr=e=>e.flatMap(t=>t.getProperties().filter(s=>o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)).map(s=>s.getName())),xr=new Set(["check","length","max"]),Se=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(!(!o.isPropertyAccessExpression(t)||t.getExpression().getText()!=="v"))return t.getName()},Er=e=>[e,...e.getDescendants()].filter(t=>Se(t)!==void 0),vr=e=>{let t=e;for(;;){const s=t.getParent();if(!s||!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;const n=s.getParent();if(!n||!o.isCallExpression(n)||n.getExpression()!==s)return!1;if(xr.has(s.getName()))return!0;t=n}},Sr=e=>{const t=[],s=[];for(const n of e)for(const i of n.getProperties()){if(!o.isPropertyAssignment(i))continue;const r=i.getInitializer();if(!r)continue;const a=Er(r),c=i.getName();a.some(u=>Se(u)==="any")?t.push(c):a.some(u=>Se(u)==="string"&&!vr(u))&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},yr=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(n?.visibility!=="public")return;const{objects:i}=Mt(s,n.receiver),{anyArgs:r,unboundedStringArgs:a}=Sr(i);if(!(r.length===0&&a.length===0))return{anyArgs:r,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Ar=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=yr(i,t);r&&s.push(r)}return s},Nr=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ar(i,v(t,n)))}return s},he=e=>e?.getKind()===l.TrueKeyword,br=e=>e?.getKind()===l.FalseKeyword,Pr=e=>e!==void 0&&o.isNumericLiteral(e)&&e.getLiteralValue()===0,Ir=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),wr=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isCallExpression(t)&&y(t.getExpression())==="scim"),Tr=e=>e!==void 0&&o.isCallExpression(e)&&Ir.has(y(e.getExpression())??""),Cr=e=>!e||!o.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>o.isStringLiteral(t)&&t.getLiteralText()==="*"),Fr=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),n=N(e,"session");return{analyzable:!0,disableCsrfCheck:he(N(t,"disableCSRFCheck")),emailPasswordEnabled:he(N(s,"enabled")),requireEmailVerification:he(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:wr(N(e,"plugins"))&&Tr(N(e,"database")),secureCookiesDisabled:br(N(t,"useSecureCookies")),sessionFreshAgeZero:Pr(N(n,"freshAge")),trustedOriginsWildcard:Cr(N(e,"trustedOrigins"))}},Or=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Rr=(e,t)=>{if(y(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],n=s!==void 0&&o.isObjectLiteralExpression(s)&&s.getProperties().some(r=>o.isSpreadAssignment(r)),i=s!==void 0&&o.isObjectLiteralExpression(s)&&!n?Fr(s):Or();return{exportName:E(e),file:t,line:e.getStartLineNumber(),...i}},Lr=(e,t)=>Ds(e,t,Rr),Dr=(e,t)=>{if(!o.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},kr=(e,t,s)=>{const n=Dr(e.getExpression(),s);if(n===void 0)return;const i=e.getArguments()[s.argIndex];if(!(!i||!R(i)||_(i))&&!(s.requireUnmodifiedReach===!0&&!Vs(i)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:n}},Mr=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression)){const r=kr(i,t,s);r&&n.push(r)}return n},ae=(e,t,s)=>{const n=[];for(const i of m(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Mr(r,v(t,i),s))}return n},Kr=new Set(["content","pdf","scrape","screenshot"]),_r=(e,t)=>ae(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:Kr}),zr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Ur=new Set(["RateLimiter"]),Br=new Set(["extend"]),ot="lunora",$r=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Kt=e=>{const t=[],s=[];let n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),i.getInitializer()?.getKind()===l.TrueKeyword&&s.push(r);continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,presentKeys:t,trueKeys:s}},ye=e=>e&&o.isObjectLiteralExpression(e)?Kt(e):{analyzable:!1,presentKeys:[],trueKeys:[]},qr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!o.isReturnStatement(s))return;const n=s.getExpression();return n!==void 0&&o.isObjectLiteralExpression(n)?n:void 0},jr=e=>{if(o.isObjectLiteralExpression(e))return e;if(o.isParenthesizedExpression(e)){const t=e.getExpression();return o.isObjectLiteralExpression(t)?t:void 0}return o.isBlock(e)?qr(e):void 0},Vr=e=>{const t=e&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,s=t&&jr(t.getBody());return s?Kt(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},Wr=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=y(n.getExpression());i!==void 0&&(zr.has(i)?s.push({callee:i,file:t,line:n.getStartLineNumber(),...ye(n.getArguments()[0])}):Br.has(i)&&s.push({callee:i,file:t,line:n.getStartLineNumber(),...Vr(n.getArguments()[0])}))}for(const n of e.getDescendantsOfKind(l.NewExpression)){const i=y(n.getExpression());i===void 0||!Ur.has(i)||s.push({callee:i,file:t,line:n.getStartLineNumber(),...ye(n.getArguments()[0])})}return s},Hr=(e,t)=>{for(const s of $r){const n=f(t,s);if(!P(n))continue;const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=[];for(const a of i.getDescendantsOfKind(l.CallExpression))y(a.getExpression())===ot&&r.push({callee:ot,file:s,line:a.getStartLineNumber(),...ye(a.getArguments()[0])});return r}return[]},Gr=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Pt(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);s.push(...Wr(r,n))}return s.push(...Hr(e,X(t))),s},at="ctx.containers.",Yr=e=>{if(!e.startsWith(at))return!1;const t=e.slice(at.length);return t.length>0&&!t.includes(".")},Qr=(e,t)=>ae(e,t,{argIndex:0,matchReceiver:Yr,methods:new Set(["get"])}),Xr=new Set(["allow","deny","setAllowed"]),Zr=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&o.isPropertyAssignment(s)&&o.isTrueLiteral(s.getInitializerOrThrow())},Jr=(e,t)=>{const s=e.getExpression();if(!(!o.isPropertyAccessExpression(s)||s.getName()!=="start"||!Zr(e)))return{detail:"enableInternet: true",exportName:E(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},ei=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||!Xr.has(s.getName()))return;const n=s.getExpression();if(!(!o.isPropertyAccessExpression(n)||n.getName()!=="egress"))return{detail:s.getName(),exportName:E(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},ti=(e,t)=>Jr(e,t)??ei(e,t),si=(e,t)=>w(e,t,ti),ni=new Set(["defineExportSink","r2Sink","webhookExportSink"]),ri=e=>{const t=e.getExpression();if(!o.isIdentifier(t))return;const s=t.getText();return ni.has(s)?s:void 0},ii=e=>{const t=[],s=[];for(const n of e.getProperties()){if(o.isSpreadAssignment(n))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(o.isPropertyAssignment(n)){const i=n.getName();t.push(i);const r=n.getInitializer();r&&o.isStringLiteral(r)&&r.getLiteralText()===""&&s.push(i);continue}(o.isShorthandPropertyAssignment(n)||o.isMethodDeclaration(n)||o.isGetAccessorDeclaration(n))&&t.push(n.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},oi=(e,t)=>{const s=[];for(const{displayPath:n,filePath:i}of Pt(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);for(const a of r.getDescendantsOfKind(l.CallExpression)){const c=ri(a);if(c===void 0)continue;const u=a.getArguments()[0],d=u&&o.isObjectLiteralExpression(u)?ii(u):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:d.analyzable,emptyKeys:d.emptyKeys,factory:c,file:n,line:a.getStartLineNumber(),presentKeys:d.presentKeys})}}return s},ai=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),ci=new Set(["dbRateLimit","rateLimit"]),li=e=>{if(!e||!o.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&o.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===l.TrueKeyword},ui=(e,t)=>{const s=y(e.getExpression());if(s===void 0)return;const n=ai.get(s);if(n!==void 0)return{callee:s,exportName:E(e),failOpen:li(e.getArguments()[n]),file:t,limitName:ci.has(s)?It(e):"",line:e.getStartLineNumber()}},di=(e,t)=>w(e,t,ui),fi=new Set(["boolean","number","object","string"]),pi=e=>{const t=e.getName();if(!fi.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="flags"&&ve(s.getExpression()))return t;const n=s.getExpression();if(s.getName()==="details"&&o.isPropertyAccessExpression(n)&&n.getName()==="flags"&&ve(n.getExpression()))return t},gi=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t))return;const s=pi(t);if(s===void 0)return;const n=e.getArguments()[0];if(!n||!(o.isStringLiteral(n)||o.isNoSubstitutionTemplateLiteral(n)))return;const i=n.getLiteralValue();return i.length>0?{key:i,type:s}:void 0},mi=(e,t)=>{const s=new Map;for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getDescendantsOfKind(l.CallExpression)){const a=gi(r);a&&!s.has(a.key)&&s.set(a.key,a.type)}}return[...s.entries()].map(([n,i])=>({key:n,type:i})).toSorted((n,i)=>n.key.localeCompare(i.key))},hi=e=>{const t=e.getInitializer();if(!t||!o.isCallExpression(t))return;const s=z(t);if(s?.kind!=="query")return;const n=ks(t,s.receiver);return n?{exportName:e.getName(),handler:n}:void 0},ct=e=>{const t=e.getParent();return t&&o.isPropertyAccessExpression(t)&&t.getExpression()===e?t:void 0},xi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="flags")return;const t=e.getExpression();if(!o.isIdentifier(t)||t.getText()!=="ctx")return;const s=ct(e);if(!s)return"ctx.flags";if(s.getName()==="details"){const n=ct(s);return n?`ctx.flags.details.${n.getName()}`:"ctx.flags.details"}return`ctx.flags.${s.getName()}`},Ei=(e,t)=>{const s=[];for(const n of e.handler.getDescendantsOfKind(l.PropertyAccessExpression)){const i=xi(n);i!==void 0&&s.push({callee:i,exportName:e.exportName,file:t,line:n.getStartLineNumber()})}return s},vi=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=hi(i);r&&s.push(...Ei(r,t))}return s},Si=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...vi(i,v(t,n)))}return s},yi=e=>{if(!o.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="flags"&&ve(t.getExpression())},Ai=e=>{if(e?.getKind()===l.TrueKeyword)return!0;if(e?.getKind()===l.FalseKeyword)return!1},Ni=(e,t)=>{if(!yi(e.getExpression()))return;const[s,n]=e.getArguments();if(!s||!(o.isStringLiteral(s)||o.isNoSubstitutionTemplateLiteral(s)))return;const i=s.getLiteralValue(),r=Ai(n);if(!(i.length===0||r===void 0))return{defaultValue:r,exportName:E(e),file:t,key:i,line:e.getStartLineNumber()}},bi=(e,t)=>w(e,t,Ni),Pi=e=>{const t=e.getType().getProperty("~standard");if(!t)return;const s=t.getTypeAtLocation(e).getProperty("types");if(!s)return;const n=s.getTypeAtLocation(e).getNonNullableType().getProperty("output");if(!n)return;const i=n.getTypeAtLocation(e),r=i.getText(e);if(!r||r==="any"||r==="never"||Xs(r))return;const a=e.getSourceFile().getFilePath();return Zs(i,e,a)?Js(i,e,a,0,new Set):r},Ii=e=>{const t=e.getExpression();return o.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},wi=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},Ti=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression))Ii(a)&&s.push({file:r,indexName:wi(a),line:a.getStartLineNumber()})}return s},V=e=>e!==void 0&&(o.isArrowFunction(e)||o.isFunctionExpression(e))?e:void 0,_t=e=>{const t=e.getArguments()[0],s=V(t);if(s!==void 0)return s;if(t===void 0||!o.isObjectLiteralExpression(t))return;const n=t.getProperty("handler");return n!==void 0&&o.isPropertyAssignment(n)?V(n.getInitializer()):void 0},Ci=new Set(["delete","get","head","options","patch","post","put"]),Fi=new Set(["handler","stream"]),Oi=new Set(["runAction","runMutation"]),Ri=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),ee=(e,t)=>e!==void 0&&o.isIdentifier(e)&&e.getText()===t,lt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const n=s.getNameNode();if(t)return o.isIdentifier(n)?n.getText():void 0;if(o.isObjectBindingPattern(n)){for(const i of n.getElements())if((i.getPropertyNameNode()?.getText()??i.getNameNode().getText())==="ctx"){const a=i.getNameNode();return o.isIdentifier(a)?a.getText():void 0}}},ut=(e,t)=>{const s=e.getBody(),n=s.getDescendantsOfKind(l.CallExpression);o.isCallExpression(s)&&n.unshift(s);for(const i of n){const r=i.getExpression();if(!o.isPropertyAccessExpression(r))continue;const a=r.getName(),c=r.getExpression();if(Oi.has(a)&&ee(c,t))return a;if(Ri.has(a)&&o.isPropertyAccessExpression(c)&&c.getName()==="db"&&ee(c.getExpression(),t))return`db.${a}`}},dt=(e,t)=>{const s=e.getBody();for(const n of s.getDescendantsOfKind(l.PropertyAccessExpression))if(n.getName()==="auth"&&ee(n.getExpression(),t))return!0;for(const n of s.getDescendantsOfKind(l.VariableDeclaration)){const i=n.getNameNode();if(!(!o.isObjectBindingPattern(i)||!ee(n.getInitializer(),t))){for(const r of i.getElements())if((r.getPropertyNameNode()?.getText()??r.getNameNode().getText())==="auth")return!0}}return!1},Li=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Fi.has(t.getName()))return;let s=t.getExpression();for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))return;const i=n.getName();if(Ci.has(i)){const r=n.getExpression();return o.isIdentifier(r)&&r.getText()==="httpRoute"?i.toUpperCase():void 0}s=n.getExpression()}},Di=(e,t)=>{const s=e.getExpression();if(o.isIdentifier(s)&&s.getText()==="httpAction"){const c=V(e.getArguments()[0]),u=c&&lt(c,!0);if(!c||u===void 0)return;const d=ut(c,u);return d===void 0?void 0:{exportName:E(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:dt(c,u),sideEffect:d}}const n=Li(e);if(n===void 0)return;const i=V(e.getArguments()[0]),r=i&&lt(i,!1);if(!i||r===void 0)return;const a=ut(i,r);return a===void 0?void 0:{exportName:E(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:n,readsAuth:dt(i,r),sideEffect:a}},ki=(e,t)=>w(e,t,Di),Mi=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),Ki=new Set(["append","set"]),zt=e=>e!==void 0&&(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ft=(e,t)=>(o.isCallExpression(e)?[e,...e.getDescendantsOfKind(l.CallExpression)]:e.getDescendantsOfKind(l.CallExpression)).some(n=>Mi.has(y(n.getExpression())??"")&&Hs(n,t)),_i=(e,t)=>{if(ft(e,t))return!0;const s=oe(e);return s!==void 0&&ft(s,t)},Ae=(e,t)=>Ws(e,t)&&!_i(e,t),zi=e=>{if(o.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=oe(e);return t!==void 0&&o.isNewExpression(t)&&y(t.getExpression())==="Headers"},te=e=>{if(e===void 0)return;if(o.isObjectLiteralExpression(e))return e;const t=oe(e);return t!==void 0&&o.isObjectLiteralExpression(t)?t:void 0},Pe=(e,t,s)=>{for(const n of e.getProperties())if(o.isPropertyAssignment(n)){const i=n.getInitializer();i!==void 0&&Ae(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:zt(n.getNameNode()),line:i.getStartLineNumber(),via:t})}else if(o.isShorthandPropertyAssignment(n)){const i=n.getNameNode();Ae(i,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:n.getName(),line:i.getStartLineNumber(),via:t})}else if(o.isSpreadAssignment(n)){const i=te(n.getExpression());i!==void 0&&Pe(i,t,s)}},Ut=(e,t)=>{const s=te(e);if(s===void 0)return;const n=s.getProperty("headers");if(n===void 0||!o.isPropertyAssignment(n))return;const i=te(n.getInitializer());i!==void 0&&Pe(i,"response-init",t)},Ui=(e,t)=>{const s=y(e.getExpression());if(s==="Response")Ut(e.getArguments()[1],t);else if(s==="Headers"){const n=te(e.getArguments()[0]);n!==void 0&&Pe(n,"headers-ctor",t)}},Bi=(e,t)=>{const s=e.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName(),i=s.getExpression();if(n==="json"&&o.isIdentifier(i)&&i.getText()==="Response"){Ut(e.getArguments()[1],t);return}if(Ki.has(n)&&zi(i)){const r=e.getArguments()[1];r!==void 0&&Ae(r,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:zt(e.getArguments()[0]),line:r.getStartLineNumber(),via:n==="set"?"headers-set":"headers-append"})}},$i=(e,t)=>{for(const s of e.getDescendantsOfKind(l.NewExpression))Ui(s,t);for(const s of e.getDescendantsOfKind(l.CallExpression))Bi(s,t)},qi=(e,t)=>{const s=e.getExpression();if(!o.isIdentifier(s)||s.getText()!=="httpAction")return[];const n=V(e.getArguments()[0]);if(n===void 0)return[];const i=n.getParameters()[1];if(i===void 0)return[];const r=i.getNameNode();if(!o.isIdentifier(r))return[];const a=[];return $i(n,{exportName:E(e),relativePath:t,requestName:r.getText(),rows:a}),a},ji=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression))s.push(...qi(n,t));return s},Vi=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...ji(i,v(t,n)))}return s},Wi=new Set(["auth","context.auth","ctx.auth"]),Hi="userId",Gi=e=>{const t=new Set;for(const s of e.getProperties()){if(o.isSpreadAssignment(s))return;(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s))&&t.add(s.getName())}return t},Yi=(e,t)=>{const s=f(t,Rt);if(!P(s))return;const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const i of n.getDescendantsOfKind(l.CallExpression)){if(y(i.getExpression())!=="defineIdentity")continue;const[r]=i.getArguments();return r&&o.isObjectLiteralExpression(r)?Gi(r):void 0}},pt=e=>{if(!(e===void 0||!o.isPropertyAccessExpression(e)||e.getName()!=="identity"))return Wi.has(e.getExpression().getText())?e:void 0},Qi=e=>{if(o.isPropertyAccessExpression(e)&&pt(e.getExpression())!==void 0)return e.getName();if(o.isElementAccessExpression(e)&&pt(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&o.isStringLiteral(t)?t.getLiteralValue():void 0}},Xi=(e,t,s)=>{const n=[];for(const i of e.getDescendants()){const r=Qi(i);r!==void 0&&n.push({declared:r===Hi||s.has(r),exportName:E(i),file:t,key:r,line:i.getStartLineNumber()})}return n},Zi=(e,t)=>{const s=Yi(e,t);if(s===void 0)return[];const n=[];for(const i of m(t)){const r=e.getSourceFile(i)??e.addSourceFileAtPath(i);n.push(...Xi(r,v(t,i),s))}return n},Ji=(e,t)=>{if(y(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const n=N(s,"key");if(!(!n||!R(n)||_(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber()}},eo=(e,t)=>w(e,t,Ji),to=new Set(["delete","get","getRaw","getWithMetadata","put"]),so=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return ae(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.kv"||r.startsWith("ctx.kv."),methods:to}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},no=new Set(["queue","send"]),gt=new Set(["bcc","cc","to"]),ro=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!no.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},io=e=>o.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(o.isShorthandPropertyAssignment(t)){const n=t.getNameNode();return gt.has(t.getName())&&R(n)&&!_(n)}if(!o.isPropertyAssignment(t)||!gt.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&R(s)&&!_(s)}):!1,oo=(e,t)=>{const s=ro(e.getExpression());if(s===void 0)return;const n=e.getArguments()[0];if(!(!n||!io(n)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},ao=(e,t)=>w(e,t,oo),co=e=>o.isPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?o.isComputedPropertyName(e.getNameNode()):!1,lo=e=>o.isPropertyAssignment(e)||o.isShorthandPropertyAssignment(e)||o.isMethodDeclaration(e)||o.isGetAccessorDeclaration(e)?co(e):!0,Bt=(e,t=!1)=>{for(const s of e.getProperties()){if(lo(s))return!0;if(t)continue;if(!o.isPropertyAssignment(s))return!0;const n=s.getInitializer();if(!n||!o.isObjectLiteralExpression(n)||Bt(n,!0))return!0}return!1},uo=(e,t)=>{for(const s of m(t)){const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const{receiver:i}of Ft(n))for(const r of be(i)){const a=r.getArguments()[0];if(a!==void 0&&(!o.isObjectLiteralExpression(a)||Bt(a)))return!0}}return!1},fo=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return[];const s=[];for(const n of t.getProperties()){const i=J(n);if(i===void 0||!o.isPropertyAssignment(n))continue;const r=n.getInitializer();if(!(!r||!o.isObjectLiteralExpression(r)))for(const a of r.getProperties()){const c=J(a);c!==void 0&&s.push({column:c,strategy:Ct(a),table:i})}}return s},po=(e,t)=>{const s=new Map;for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const{receiver:r}of Ft(i))for(const a of be(r))for(const c of fo(a)){const u=`${c.table}\0${c.column}`;s.has(u)||s.set(u,c)}}return{columns:[...s.values()]}},go=(e,t,s)=>{const n=e.getArguments()[0];if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){const a=J(r);if(a===void 0||!o.isPropertyAssignment(r))continue;const c=r.getInitializer();if(!(!c||!o.isObjectLiteralExpression(c)))for(const u of c.getProperties()){const d=J(u);if(d===void 0)continue;const S=Ct(u);S!=="custom"&&i.push({column:d,exportName:t,file:s,line:u.getStartLineNumber(),strategy:S,table:a})}}return i},mo=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;return n?.receiver?be(n.receiver).flatMap(i=>go(i,e.getName(),t)):[]},ho=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...mo(c,r))}return s},xo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return M(s)},Eo=e=>{const t=e.getArguments()[0];if(t===void 0||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return o.isPropertyAssignment(s)?s.getInitializer():s},vo=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==l.CallExpression)return;const s=t;return on(s.getExpression())?s:void 0},So=e=>{const t=vo(e),s=t===void 0?void 0:Eo(t);if(s===void 0)return[];const n=e.getNameNode(),i=o.isIdentifier(n)?n.getText():"";return s.getDescendantsOfKind(l.CallExpression).filter(r=>xo(r)).map(r=>({exportName:i,file:"lunora/mutators.ts",line:r.getStartLineNumber()}))},yo=e=>e.getVariableDeclarations().flatMap(t=>So(t)),Ao=(e,t)=>{const s=f(t,rn);if(!P(s))return[];const n=e.getSourceFile(s)??e.addSourceFileAtPath(s);return yo(n)},No=new Set(["delete","get","patch"]),bo=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Po=new Set(["auth","identity","session","user"]),Io=new Set([l.EqualsEqualsEqualsToken,l.EqualsEqualsToken,l.ExclamationEqualsEqualsToken,l.ExclamationEqualsToken]),wo=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!M(t.getExpression()))return;const s=e.getArguments()[0];return s&&o.isStringLiteral(s)?s.getLiteralText():""},To=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(o.isAsExpression(s)||o.isParenthesizedExpression(s)||o.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!o.isVariableDeclaration(s))return;const n=s.getNameNode();return o.isIdentifier(n)?n.getText():void 0},Co=(e,t)=>e.getDescendantsOfKind(l.Identifier).some(s=>s.getText()===t),Fo=e=>o.isThrowStatement(e)||o.isReturnStatement(e)||e.getDescendantsOfKind(l.ThrowStatement).length>0||e.getDescendantsOfKind(l.ReturnStatement).length>0,Oo=(e,t)=>e.getDescendantsOfKind(l.IfStatement).some(s=>Co(s.getExpression(),t)&&Fo(s.getThenStatement())),Ro=(e,t)=>{for(const s of e.getDescendantsOfKind(l.CallExpression)){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))continue;const i=n.getName();if(!No.has(i))continue;const r=n.getExpression();if(!(M(r)||o.isPropertyAccessExpression(r)&&M(r.getExpression())))continue;const c=s.getArguments()[0];if(c!==void 0&&o.isIdentifier(c)&&c.getText()===t)return i}},Lo=e=>{let t=e;for(;o.isPropertyAccessExpression(t)||o.isElementAccessExpression(t)||o.isNonNullExpression(t)||o.isParenthesizedExpression(t)||o.isAsExpression(t)||o.isAwaitExpression(t);)t=t.getExpression();return o.isIdentifier(t)?t.getText():void 0},Do=e=>e.getDescendantsOfKind(l.CallExpression).some(t=>t.getArguments().some(s=>Lo(s)==="ctx")),ko=e=>e.getDescendantsOfKind(l.BinaryExpression).some(t=>Io.has(t.getOperatorToken().getKind())?o.isPropertyAccessExpression(t.getLeft())||o.isPropertyAccessExpression(t.getRight()):!1),Mo=e=>{for(const t of e.getDescendantsOfKind(l.Identifier))if(bo.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(l.PropertyAccessExpression)){const s=t.getExpression();if(o.isIdentifier(s)&&s.getText()==="ctx"&&Po.has(t.getName()))return!0}return Do(e)||ko(e)},Ko=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query"&&n?.kind!=="mutation")return[];const i=_t(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Tt(n.receiver,"use","rls"),a=Mo(i),c=new Set,u=[];for(const d of i.getDescendantsOfKind(l.CallExpression)){const S=wo(d);if(S===void 0)continue;const x=To(d);if(x===void 0||c.has(x)||!Oo(i,x))continue;const I=Ro(i,x);I!==void 0&&(c.add(x),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),mentionsOwnership:a,sinkMethod:I,table:S,usesRls:r,visibility:n.visibility}))}return u},_o=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ko(c,r))}return s},zo=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),Uo=new Set(["insert","insertManyUnsafe","patch","replace"]),Bo=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(!Uo.has(t))return;const s=e.getExpression();if(!o.isPropertyAccessExpression(s)||s.getName()!=="db")return;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"?t:void 0},$o=(e,t)=>{if(t!=="insertManyUnsafe")return o.isObjectLiteralExpression(e)?[e]:[];if(!o.isArrayLiteralExpression(e))return[];const s=[];for(const n of e.getElements())o.isObjectLiteralExpression(n)&&s.push(n);return s},qo=(e,t,s,n)=>{const i=[];for(const r of e.getProperties()){let a,c;o.isPropertyAssignment(r)?(a=r.getName(),c=r.getInitializer()):o.isShorthandPropertyAssignment(r)&&(a=r.getName(),c=r.getNameNode()),!(a===void 0||c===void 0||!zo.has(a))&&R(c)&&!_(c)&&i.push({exportName:E(s),field:a,file:n,line:s.getStartLineNumber(),method:t})}return i},jo=(e,t)=>{const s=Bo(e.getExpression());if(s===void 0)return[];const n=e.getArguments()[1];return n?$o(n,s).flatMap(i=>qo(i,s,e,t)):[]},Vo=(e,t,s)=>{const n=[];for(const i of e.getDescendantsOfKind(l.CallExpression))for(const r of jo(i,t)){const a=s(r.exportName);n.push(a===void 0?r:{...r,visibility:a})}return n},Wo=(e,t,s=[])=>{const n=[],i=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));for(const r of m(t)){const a=e.getSourceFile(r)??e.addSourceFileAtPath(r),c=v(t,r);n.push(...Vo(a,c,u=>i.get(`${c}:${u}`)))}return n},Ho=["providerSubscriptionId","state"],Go=["providerEventId","processedAt"],mt=(e,t)=>t.every(s=>s in e.shape),Yo=e=>{const t=e.find(n=>n.name==="subscriptions"),s=e.find(n=>n.name==="events");return t!==void 0&&s!==void 0&&mt(t,Ho)&&mt(s,Go)},Qo=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),Xo=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,Zo=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&o.isPropertyAssignment(t)?Xo(t.getInitializer()):void 0},Jo=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Qo.has(s))return;const[n]=e.getArguments(),i=n&&o.isObjectLiteralExpression(n)?Zo(n):void 0;return{callee:s,exportName:E(e),file:t,line:e.getStartLineNumber(),...i===void 0?{}:{toleranceSeconds:i}}},ea=(e,t)=>w(e,t,Jo),ta=new Set(["defineQueue","defineWorkflow"]),sa=new Set(["run","runAction","runMutation","runQuery"]),na=new Set(["api","internal"]),ra=e=>{const t=e.getExpression();return o.isIdentifier(t)?t.getText():void 0},ia=e=>{const t=e.getArguments()[0];if(!t||!o.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!o.isPropertyAssignment(s))return;const n=s.getInitializer();if(n&&(o.isArrowFunction(n)||o.isFunctionExpression(n)))return n},$t=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&o.isIdentifier(s)?s.getText():void 0},qt=(e,t)=>e===t||e.startsWith(`${t}.`),jt=e=>{const t=e.getDescendantsOfKind(l.PropertyAccessExpression);return o.isPropertyAccessExpression(e)&&t.push(e),t},ht=e=>{const t=e.getParent();return o.isPropertyAccessExpression(t)&&t.getNameNode()===e||o.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(o.isBindingElement(t)&&t.getNameNode()===e)},Vt=e=>{const t=e.getDescendantsOfKind(l.Identifier).filter(s=>ht(s));return o.isIdentifier(e)&&ht(e)&&t.push(e),t},oa=e=>{if(!o.isVariableDeclaration(e))return[];const t=e.getNameNode();return o.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(l.BindingElement).map(s=>s.getName())},aa=e=>{const t=$t(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const n of e.getDescendantsOfKind(l.ForOfStatement)){if(n.getExpression().getText()!==`${t}.messages`)continue;const i=n.getInitializer(),r=o.isVariableDeclarationList(i)?i.getDeclarations()[0]?.getNameNode():void 0;r&&o.isIdentifier(r)&&s.push(`${r.getText()}.body`)}return s},ca=(e,t,s)=>{const n=t==="workflow"?[`${s}.params`]:aa(e),i=new Set,r=a=>jt(a).some(c=>n.some(u=>qt(c.getText(),u)))?!0:Vt(a).some(c=>i.has(c.getText()));for(const a of e.getDescendantsOfKind(l.VariableDeclaration)){const c=a.getInitializer();if(c&&r(c))for(const u of oa(a))i.add(u)}return{names:i,prefixes:n}},la=(e,t)=>jt(e).some(s=>t.prefixes.some(n=>qt(s.getText(),n)))?!0:Vt(e).some(s=>t.names.has(s.getText())),ua=e=>{if(e===void 0||!o.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;o.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const n=t.at(-1);if(!(n===void 0||!o.isIdentifier(s)||!na.has(s.getText())||t.length<2))return{exportName:n,file:t.slice(0,-1).join("/")}},da=(e,t,s)=>{const n=$t(e,0);if(n===void 0)return[];const i=ca(e,t,n),r=[];for(const a of e.getDescendantsOfKind(l.CallExpression)){const c=a.getExpression();if(!o.isPropertyAccessExpression(c)||!sa.has(c.getName())||c.getExpression().getText()!==n)continue;const u=a.getArguments()[1];if(!u||!la(u,i))continue;const d=ua(a.getArguments()[0]);d!==void 0&&r.push({dispatchKind:t,file:s,handlerExport:E(a),line:a.getStartLineNumber(),targetExport:d.exportName,targetFile:d.file})}return r},fa=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=ra(n);if(i===void 0||!ta.has(i))continue;const r=ia(n);r!==void 0&&s.push(...da(r,i==="defineQueue"?"queue":"workflow",t))}return s},pa=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...fa(i,v(t,n)))}return s},xt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstileMiddleware:"usesCaptcha"},Et=new Set(["account","credential","member","passkey","session","user"]),ga=e=>e.replaceAll(/[-_]/gu," ").replaceAll(/([a-z0-9])([A-Z])/gu,"$1 $2").split(" ").filter(Boolean).map(t=>t.toLowerCase()),ma=e=>{const s=ga(e).at(-1);if(!s)return!1;const n=s.endsWith("s")?s.slice(0,-1):s;return Et.has(s)||Et.has(n)},ha=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},xa=(e,t)=>{const{objects:s,opaque:n}=Mt(e,t);return hr(s).some(i=>ha(i))?!0:n?void 0:!1},Ea=e=>{const t=e.getArguments()[0];return!t||!o.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},va=e=>{if(o.isCallExpression(e))return e;if(!o.isIdentifier(e))return;const s=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return s&&o.isCallExpression(s)?s:void 0},Z={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Sa=e=>{const t=va(e),s=t?y(t.getExpression()):void 0;if(t&&s==="protectPublic"){const n=Ea(t);return{...Z,usesCaptcha:n.usesCaptcha,usesRateLimit:n.usesRateLimit}}return s!==void 0&&s in xt?{...Z,[xt[s]]:!0}:Z},ya=e=>{const t={...Z};let s=e;for(;o.isCallExpression(s);){const n=s.getExpression();if(!o.isPropertyAccessExpression(n))break;const i=n.getName()==="use"?s.getArguments()[0]:void 0;if(i){const r=Sa(i);t.usesCaptcha||=r.usesCaptcha,t.usesEmailGate||=r.usesEmailGate,t.usesMask||=r.usesMask,t.usesRateLimit||=r.usesRateLimit,t.usesRls||=r.usesRls}s=n.getExpression()}return t},Aa=new Set(["insert","insertMany","insertManyUnsafe","replace"]),Na=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!Aa.has(t.getName()))return!1;const s=t.getExpression();if(!M(s))return!1;const i=e.getArguments()[0];return!i||!(o.isStringLiteral(i)||o.isNoSubstitutionTemplateLiteral(i))?!1:ma(i.getLiteralText())},ba=new Set(["create","runAfter","runAt","send","sendBatch"]),Pa=new Set(["queues","scheduler","workflows"]),Ia=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!ba.has(t.getName()))return!1;let s=t.getExpression();for(;o.isCallExpression(s)||o.isElementAccessExpression(s)||o.isPropertyAccessExpression(s);){if(o.isPropertyAccessExpression(s)&&Pa.has(s.getName())){const n=s.getExpression();if(o.isIdentifier(n)&&n.getText()==="ctx")return!0}s=s.getExpression()}return!1},wa=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return M(s)},Wt=new Set(["generateObject","generateText","streamObject","streamText"]),Ta=e=>{const t=y(e.getExpression());return t!==void 0&&Wt.has(t)},Ca=e=>{const t=y(e.getExpression());if(t===void 0||!Wt.has(t))return!1;const s=e.getArguments()[0];return!s||!o.isObjectLiteralExpression(s)||s.getProperties().some(n=>o.isSpreadAssignment(n))?!1:!s.getProperty("maxOutputTokens")},Fa=new Set(["log","span","trace"]),Oa=new Set(["ai"]),Ra=new Set(["email","mail"]),La=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),xe=(e,t)=>e.getDescendantsOfKind(l.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="ctx"}),Da=new Set([l.ArrowFunction,l.FunctionDeclaration,l.FunctionExpression,l.GetAccessor,l.MethodDeclaration,l.SetAccessor]),ka=new Set(["every","filter","flatMap","forEach","map","some"]),Ma=new Set(["all","allSettled","race"]),Ka=e=>{const t=e.getParent();if(!t||!o.isCallExpression(t)||!t.getArguments().includes(e))return;const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;const n=s.getName();if(ka.has(n))return t;const i=s.getExpression();if(o.isIdentifier(i)&&i.getText()==="Promise"&&Ma.has(n))return t},_a=e=>{let t=e.getParent();for(;t;){if(o.isTryStatement(t)){const s=t.getTryBlock();if(e.getPos()>=s.getPos()&&e.getEnd()<=s.getEnd())return!0}if(Da.has(t.getKind())){const s=Ka(t);if(!s)return!1;t=s;continue}t=t.getParent()}return!1},za=e=>{let t=e;for(;;){const s=t.getParent();if(!o.isPropertyAccessExpression(s)||s.getExpression()!==t)return!1;if(s.getName()==="catch")return!0;if(s.getName()!=="then"&&s.getName()!=="finally")return!1;const n=s.getParent();if(!o.isCallExpression(n)||n.getExpression()!==s)return!1;t=n}},Ua=e=>{let t=e;for(;;){const s=t.getParent();if(o.isPropertyAccessExpression(s)&&s.getExpression()===t){t=s;continue}return o.isCallExpression(s)&&s.getExpression()===t?s:void 0}},Ba=e=>{let t=!1,s=!0;for(const n of e.getDescendantsOfKind(l.PropertyAccessExpression)){if(!La.has(n.getName()))continue;const i=n.getExpression();if(!o.isIdentifier(i)||i.getText()!=="ctx")continue;const r=Ua(n);r&&(t=!0,!_a(r)&&!za(r)&&(s=!1))}return{handlesErrors:t&&s,reachesOutbound:t}},$a=e=>e.getDescendantsOfKind(l.ThrowStatement).some(t=>{const s=t.getExpression();if(!o.isNewExpression(s))return!1;const n=s.getExpression();return o.isIdentifier(n)&&n.getText()==="Error"}),vt="lunora-advisor-exempt",qa=/^[\s*/]+/u,ja=/[\w-]/u,Va=e=>{const s=(e.getFirstAncestorByKind(l.VariableStatement)??e).getLeadingCommentRanges().map(n=>n.getText()).join(`
6
+ `);for(const n of s.split(`
7
+ `)){const i=n.replace(qa,"");if(!i.startsWith(vt))continue;const r=i.slice(vt.length);if(ja.test(r.charAt(0)))continue;const a=r.indexOf("--");return{exempt:!0,exemptReason:(a===-1?"":r.slice(a+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Wa=e=>{const[t]=e.getArguments();if(t){if(o.isObjectLiteralExpression(t)){const s=t.getProperty("handler");return s?o.isPropertyAssignment(s)?s.getInitializer():o.isShorthandPropertyAssignment(s)?s.getNameNode():o.isMethodDeclaration(s)?s:void 0:void 0}return t}},Ha=(e,t)=>{const s=Wa(t);if(!s)return;if(o.isArrowFunction(s)||o.isFunctionExpression(s)||o.isMethodDeclaration(s))return e;if(!o.isIdentifier(s))return;const n=s.getSourceFile(),i=s.getText(),r=n.getVariableDeclaration(i)?.getInitializer();return r&&(o.isArrowFunction(r)||o.isFunctionExpression(r))?r:n.getFunction(i)},Ga=e=>{let t=!1,s=!1,n=!1,i=!1,r=!1;for(const u of e.getDescendantsOfKind(l.CallExpression))if(Na(u)&&(r=!0),Ia(u)&&(t=!0),wa(u)&&(i=!0),Ta(u)&&(s=!0),Ca(u)&&(n=!0),r&&t&&i&&n)break;const{handlesErrors:a,reachesOutbound:c}=Ba(e);return{callsMail:xe(e,Ra),emitsEvent:xe(e,Fa),fanOut:t,handlesErrors:a,reachesOutbound:c,runsAiGeneration:s||xe(e,Oa),throwsBareError:$a(e),unboundedAiGeneration:n,usesInsertManyUnsafe:i,writesUserTable:r}},Ya=(e,t)=>{const s=e.getInitializer();if(!s||!o.isCallExpression(s))return;const n=z(s);if(!n||n.kind!=="query"&&n.kind!=="mutation"&&n.kind!=="action")return;const i=n.receiver?ya(n.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},r=Ha(e,s);return{...r?Ga(r):{},...Va(e),...i,analyzableBody:r!==void 0,exportName:e.getName(),file:t,hasEmailArg:xa(s,n.receiver),kind:n.kind,visibility:n.visibility}},Qa=(e,t)=>{const s=[];for(const n of e.getVariableStatements())if(n.isExported())for(const i of n.getDeclarations()){const r=Ya(i,t);r&&s.push(r)}return s},Xa=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Qa(i,v(t,n)))}return s},Za=new Set(["dbRateLimit","rateLimit"]),Ja=e=>o.isArrowFunction(e)?e.getBody():e,ec=(e,t)=>{const s=y(e.getExpression());if(s===void 0||!Za.has(s))return;const n=e.getArguments()[2];if(!n)return;const i=N(n,"key");if(!i)return;const r=Ja(i);if(!(!R(r)||_(r)))return{callee:s,exportName:E(e),file:t,limitName:It(e),line:e.getStartLineNumber()}},tc=(e,t)=>w(e,t,ec),sc=new Set(["findFirst","findFirstOrThrow","findMany","get"]),nc=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||!sc.has(t.getName()))return;const s=t.getExpression();if(M(s)){const n=e.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}if(o.isPropertyAccessExpression(s)&&M(s.getExpression()))return s.getName()},rc=e=>{let t=e;for(;o.isCallExpression(t);){const s=t.getExpression();if(!o.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&M(s.getExpression())){const n=t.getArguments()[0];return n&&o.isStringLiteral(n)?n.getLiteralText():""}t=s.getExpression()}},ic=e=>{let t=et(e)??e;for(;o.isAwaitExpression(t);)t=et(t.getExpression())??t.getExpression();return t},Ht=(e,t=!1)=>{const s=ic(e);if(o.isIdentifier(s)){if(t)return;const n=oe(s);return n===void 0?void 0:Ht(n,!0)}if(o.isCallExpression(s))return nc(s)??rc(s)},oc=e=>{const t=e.getBody();if(!o.isBlock(t))return[t];const s=[];for(const n of e.getDescendantsOfKind(l.ReturnStatement)){const i=n.getFirstAncestor(a=>o.isArrowFunction(a)||o.isFunctionExpression(a)||o.isFunctionDeclaration(a)),r=n.getExpression();i===e&&r!==void 0&&s.push(r)}return s},ac=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!o.isCallExpression(s))return[];const n=z(s);if(n?.kind!=="query")return[];const i=_t(s);if(i===void 0)return[];const r=n.receiver!==void 0&&Ys(n.receiver,"output"),a=n.receiver!==void 0&&Tt(n.receiver,"use","mask"),c=new Set,u=[];for(const d of oc(i)){const S=Ht(d);S===void 0||c.has(S)||(c.add(S),u.push({exportName:e.getName(),file:t,line:d.getStartLineNumber(),table:S,usesMask:a,usesOutput:r,visibility:n.visibility}))}return u},cc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...ac(c,r))}return s},lc=e=>{if(!e||!o.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(o.isPropertyAssignment(s)||o.isShorthandPropertyAssignment(s)||o.isMethodDeclaration(s)||o.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},uc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=wt(r);if(a===void 0)continue;const c=lc(N(a.options,"with"));c.length!==0&&i.push({exportName:e.getName(),file:t,line:r.getStartLineNumber(),parentTable:a.table,relations:c,visibility:n.visibility})}return i},dc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...uc(c,r))}return s},se=e=>{if(o.isStringLiteral(e)||o.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(o.isBinaryExpression(e)&&e.getOperatorToken().getKind()===l.PlusToken){const t=se(e.getLeft()),s=se(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},fc=e=>{let t=e,s=t.getParent();for(;s!==void 0&&o.isBinaryExpression(s)&&s.getOperatorToken().getKind()===l.PlusToken;)t=s,s=t.getParent();return t!==e&&se(t)!==void 0},pc=/(?:^|\/)__tests__\//u,gc=/\.(?:spec|test)$/u,mc=e=>pc.test(e)||gc.test(e),hc=e=>{const t=e.getParent();if(t!==void 0){if(o.isVariableDeclaration(t)||o.isPropertyAssignment(t)||o.isPropertySignature(t))return t.getName();if(o.isBinaryExpression(t)&&t.getOperatorToken().getKind()===l.EqualsToken)return t.getLeft().getText()}},xc=(e,t,s)=>hn(e)?!mc(s)&&xn(hc(t)):!0,Ec=(e,t)=>{const s=[],n=[...e.getDescendantsOfKind(l.BinaryExpression),...e.getDescendantsOfKind(l.StringLiteral),...e.getDescendantsOfKind(l.NoSubstitutionTemplateLiteral)],i=new Set;for(const r of n){if(fc(r))continue;const a=se(r);if(a===void 0)continue;const c=gn(a);if(c===void 0||!xc(c,r,t))continue;const u=r.getStartLineNumber(),d=`${String(u)}:${c}`;i.has(d)||(i.add(d),s.push({file:t,kind:c,line:u,preview:mn(a)}))}return s},vc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...Ec(i,v(t,n)))}return s},Sc=(e,t)=>{if(!o.isVariableDeclaration(e))return[];const s=e.getInitializer(),n=s&&o.isCallExpression(s)?z(s):void 0;if(!n)return[];const i=[];for(const r of e.getDescendantsOfKind(l.CallExpression)){const a=wt(r);if(a===void 0)continue;const c=N(a.options,"includeDeleted");if(c===void 0)continue;const u=o.isTrueLiteral(c),d=!u&&R(c);!u&&!d||i.push({exportName:e.getName(),file:t,fromArgs:d,hardcodedTrue:u,line:r.getStartLineNumber(),table:a.table,visibility:n.visibility})}return i},yc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Sc(c,r))}return s},Ac=new Set(["query","unsafe"]),Nc=e=>{if(!o.isPropertyAccessExpression(e)||!Ac.has(e.getName()))return!1;const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return o.isIdentifier(s)&&s.getText()==="ctx"},bc=e=>o.isBinaryExpression(e)||o.isTemplateExpression(e),Pc=e=>e.getFirstAncestorByKind(l.VariableDeclaration)?.getName()??"<module>",Ic=(e,t)=>{if(!Nc(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!bc(s)))return{exportName:Pc(e),file:t,line:s.getStartLineNumber()}},wc=(e,t)=>w(e,t,Ic),Tc=[["convex",["convex","@convex-dev/"]],["supabase",["@supabase/"]],["firebase",["firebase","@firebase/","firebase-admin"]]],Cc=e=>{for(const[t,s]of Tc)for(const n of s)if(e===n||e.startsWith(n.endsWith("/")?n:`${n}/`))return t},Fc=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);for(const r of i.getImportDeclarations()){const a=r.getModuleSpecifierValue(),c=Cc(a);c!==void 0&&s.push({file:v(t,n),line:r.getStartLineNumber(),moduleSpecifier:a,platform:c})}}return s},Oc=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),Rc=(e,t,s=[])=>{const n=new Map(s.map(r=>[`${r.filePath}:${r.exportName}`,r.visibility]));return ae(e,t,{argIndex:0,matchReceiver:r=>r==="ctx.storage"||r.startsWith("ctx.storage."),methods:Oc,requireUnmodifiedReach:!0}).map(r=>{const a=n.get(`${r.file}:${r.exportName}`);return a===void 0?r:{...r,visibility:a}})},Lc=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),Dc=e=>e&&o.isNumericLiteral(e)?Number(e.getText()):void 0,kc=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!o.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,n=!1;for(const i of e.getProperties()){if(o.isSpreadAssignment(i)){n=!0;continue}if(o.isPropertyAssignment(i)){const r=i.getName();t.push(r),r==="expiresInSeconds"&&(s=Dc(i.getInitializer()));continue}(o.isShorthandPropertyAssignment(i)||o.isMethodDeclaration(i))&&t.push(i.getName())}return{analyzable:!n,expiresInSeconds:s,presentKeys:t}},Mc=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName(),s=Lc.get(t);if(s===void 0)return;const n=e.getExpression().getText();return n==="ctx.storage"||n.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Kc=(e,t)=>{const s=Mc(e.getExpression());if(s!==void 0)return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s.method,...kc(e.getArguments()[s.optionsIndex])}},_c=(e,t)=>w(e,t,Kc),zc=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:t.vectorStoreSupported&&(e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings")),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Uc=new Set(["RegisteredAction","RegisteredMutation","RegisteredQuery"]),Ie=e=>{const t=e.getType(),s=t.getAliasSymbol()?.getName()??t.getSymbol()?.getName();return s!==void 0&&Uc.has(s)?s:void 0},Gt=e=>{const t=e.getInitializer();return t===void 0?!1:o.isCallExpression(t)||o.isIdentifier(t)||o.isPropertyAccessExpression(t)},Yt={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."},Bc={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."},we=(e,t,s,n,i)=>({cacheKey:`procedure_not_registered:${e}:${t}`,categories:["SCHEMA"],description:"Codegen registers an export only when the declaration carries `export` and its initializer is literally a builder chain. A procedure written any other way exists at runtime but never reaches `_generated/api.ts`, so no caller can address it.",detail:`\`${t}\` in \`${e}\` (line ${n.toString()}) has type \`${s}\` but was not registered — ${i.cause}.`,facing:"INTERNAL",level:"WARN",metadata:{exportName:t,filePath:e,line:n,typeName:s},name:"procedure_not_registered",remediation:`Assign the builder chain directly: \`export const ${t} = query.input({ … }).query(handler);\`. ${i.remediation}`,title:"Procedure exists at runtime but is missing from the generated API"}),$c=(e,t,s)=>{const n=[];for(const i of e.getVariableStatements().filter(r=>r.isExported()))for(const r of i.getDeclarations()){const a=r.getName();if(s.has(`${t}:${a}`)||!Gt(r))continue;const c=Ie(r);c!==void 0&&n.push(we(t,a,c,r.getStartLineNumber(),Yt))}return n},qc=(e,t,s)=>{if(s.has(`${t}:default`))return[];const n=[];for(const i of e.getExportAssignments().filter(r=>!r.isExportEquals())){const r=Ie(i.getExpression());r!==void 0&&n.push(we(t,"default",r,i.getStartLineNumber(),Yt))}return n},jc=(e,t,s)=>{const n=[];for(const i of e.getExportDeclarations().filter(r=>r.getModuleSpecifier()===void 0))for(const r of i.getNamedExports()){const a=r.getAliasNode()?.getText()??r.getName();if(s.has(`${t}:${a}`))continue;const c=r.getLocalTargetDeclarations().find(d=>o.isVariableDeclaration(d));if(c===void 0||!Gt(c))continue;const u=Ie(c);u!==void 0&&n.push(we(t,a,u,r.getStartLineNumber(),Bc))}return n},Vc=(e,t,s)=>[...$c(e,t,s),...qc(e,t,s),...jc(e,t,s)],Wc=(e,t,s)=>{const n=new Set(s.map(r=>`${r.filePath}:${r.exportName}`)),i=[];for(const r of m(t)){const a=e.getSourceFile(r);a!==void 0&&i.push(...Vc(a,v(t,r),n))}return i.toSorted((r,a)=>r.cacheKey.localeCompare(a.cacheKey))},Hc=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),Gc=e=>{if(!o.isCallExpression(e))return;const t=e.getExpression();if(o.isPropertyAccessExpression(t)){const n=t.getName();return Ee.has(n)?n:void 0}if(!o.isIdentifier(t))return;for(const n of t.getSymbol()?.getDeclarations()??[])if(o.isImportSpecifier(n)){const i=n.getNameNode().getText();return Ee.has(i)?i:void 0}const s=t.getText();return Ee.has(s)?s:void 0},Yc=e=>o.isObjectLiteralExpression(e)&&e.getProperties().length===0,Qt=e=>{if(e!==void 0){if(o.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===l.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(Yc(e))return"empty-object";if(o.isParenthesizedExpression(e))return Qt(e.getExpression())}},Te=e=>e.getAncestors().find(t=>o.isArrowFunction(t)||o.isFunctionExpression(t)||o.isFunctionDeclaration(t)),Qc=e=>e.getDescendantsOfKind(l.ReturnStatement).filter(t=>Te(t)===e),Xt=e=>e.getDescendantsOfKind(l.ConditionalExpression).filter(t=>Te(t)===e),Xc=e=>{const t=Qc(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(l.IfStatement)!==void 0)||Xt(e).length>0},Zc=e=>e.getDescendantsOfKind(l.IfStatement).filter(t=>Te(t)===e),Ne=e=>e.getKind()===l.NullKeyword||e.getKind()===l.FalseKeyword||o.isIdentifier(e)&&e.getText()==="undefined"?!0:o.isNumericLiteral(e)?e.getLiteralValue()===0:o.isStringLiteral(e)&&e.getLiteralValue()==="",Jc=(e,t)=>Ne(e)||Ne(t),el=new Map([[l.EqualsEqualsEqualsToken,"positive"],[l.EqualsEqualsToken,"positive"],[l.ExclamationEqualsEqualsToken,"negative"],[l.ExclamationEqualsToken,"negative"]]),St=e=>!Ne(e)&&(o.isLiteralExpression(e)||e.getKind()===l.TrueKeyword),tl=(e,t,s)=>{const n=el.get(e);if(n!==void 0)return Jc(t,s)?n==="positive"?"negative":"positive":St(t)||St(s)?void 0:n},j=e=>{if(o.isParenthesizedExpression(e))return j(e.getExpression());if(o.isPrefixUnaryExpression(e)&&e.getOperatorToken()===l.ExclamationToken)return"negative";if(o.isBinaryExpression(e)){const t=e.getOperatorToken().getKind(),s=tl(t,e.getLeft(),e.getRight());if(s!==void 0)return s;if(t===l.AmpersandAmpersandToken||t===l.BarBarToken){const n=j(e.getLeft()),i=j(e.getRight());return n===i?n:"indeterminate"}}return o.isIdentifier(e)||o.isPropertyAccessExpression(e)||o.isElementAccessExpression(e)||o.isCallExpression(e)?"positive":"indeterminate"},yt=e=>{if(e!==void 0){if(o.isReturnStatement(e))return e;if(o.isBlock(e)){const t=e.getStatements().at(-1);return t!==void 0&&o.isReturnStatement(t)?t:void 0}}},sl=e=>{if(e.getElseStatement()!==void 0)return;const t=e.getNextSiblingIfKind(l.ReturnStatement);return t!==void 0&&t.getNextSibling()===void 0?t:void 0},nl=e=>o.isReturnStatement(e)?e.getExpression()??e:e,rl=e=>{const t=[];for(const s of Xt(e)){const n=j(s.getCondition());n==="positive"?t.push(s.getWhenFalse()):n==="negative"&&t.push(s.getWhenTrue())}for(const s of Zc(e)){const n=j(s.getExpression());if(n==="indeterminate")continue;const i=n==="negative"?yt(s.getThenStatement()):yt(s.getElseStatement())??sl(s);i!==void 0&&t.push(nl(i))}return t},il=e=>{for(const t of e.getAncestors())if(o.isVariableDeclaration(t)){const s=t.getNameNode();if(o.isIdentifier(s))return s.getText()}return"<anonymous>"},ol=(e,t,s)=>{if(!o.isCallExpression(e))return[];const[n]=e.getArguments();if(!n||!o.isObjectLiteralExpression(n))return[];const i=[];for(const r of n.getProperties()){if(!o.isPropertyAssignment(r)||!Hc.has(r.getName()))continue;const a=r.getInitializer();if(!(!a||!(o.isArrowFunction(a)||o.isFunctionExpression(a)))&&Xc(a))for(const c of rl(a)){const u=Qt(c);u!==void 0&&i.push({exportName:il(e),file:s,form:u,key:r.getName(),line:c.getStartLineNumber(),owner:t})}}return i},al=(e,t)=>{const s=[];for(const n of e.getDescendantsOfKind(l.CallExpression)){const i=Gc(n);i!==void 0&&s.push(...ol(n,i,t))}return s},cl=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n);s.push(...al(i,v(t,n)))}return s},ll=new Set(["query","upsert","upsertMany"]),ul=e=>{if(!o.isPropertyAccessExpression(e))return;const t=e.getName();if(ll.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},dl=(e,t)=>{const s=ul(e.getExpression());if(s===void 0)return;const n=e.getArguments()[1];if(!n)return;const i=N(n,"namespace");if(!(!i||!R(i)||_(i)))return{exportName:E(e),file:t,line:e.getStartLineNumber(),method:s}},fl=(e,t)=>w(e,t,dl),pl=e=>{const t=e.getExpression();if(!o.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return o.isPropertyAccessExpression(s)?s.getName()==="workflows":o.isIdentifier(s)&&s.getText()==="workflows"},gl=e=>{const t=e.getArguments()[0];return t&&o.isStringLiteral(t)?t.getLiteralText():""},ml=(e,t)=>{const s=[];for(const n of m(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),r=v(t,n);for(const a of i.getDescendantsOfKind(l.CallExpression)){if(!pl(a))continue;const c=Ms(a);c!==""&&s.push({exportName:c,file:r,line:a.getStartLineNumber(),workflow:gl(a)})}}return s},hl=".lunora-schema.json",T=(e,t)=>{P(e)&&bt(e,"utf8")===t||ls(e,t,"utf8")},O=(e,t)=>{if(t===""){us(e,{force:!0});return}T(e,t)},xl=e=>{const t=f(e,"package.json");if(P(t))try{const s=JSON.parse(bt(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},El=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},vl=e=>{let t=P(e)?e:X(e);for(;t&&t!==X(t);){const s=f(t,"tsconfig.json");if(P(s))return s;t=X(t)}},At=e=>e.replaceAll("\\","/"),Sl=(e,t,s)=>{if(s&&e.length>0){const r=e.map(a=>`"${a.exportName}"`).join(", ");throw new k("MASK_UNSUPPORTED",`This project declares a \`mask(...)\` policy whose argument isn't a plain object literal (e.g. \`mask(sharedPolicies)\` referencing a hoisted variable), or contains a spread (\`...shared\`) or computed key (\`[name]:\`) codegen can't enumerate, so codegen can't tell which columns it masks. Because the project also declares replication shape(s) (${r}), codegen can't verify none of them replicate a table that policy masks — inline every table and column as literal keys so codegen can verify it, or remove the affected shape(s).`,{status:422})}const n=new Map;for(const r of t.columns){const a=n.get(r.table)??[];a.push(r.column),n.set(r.table,a)}const i=t.columns.length>0;for(const r of e){if(r.table===void 0){if(i)throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" has a non-literal \`table\` (a variable or expression, not a string literal), so codegen can't statically verify it doesn't replicate a table that masks a column. This project masks at least one column elsewhere, so the combination can't be proven safe — change "${r.exportName}"'s \`table\` to a plain string literal so codegen can verify it, or remove the mask(s) on the table it targets.`,{status:422});continue}const a=n.get(r.table);if(a===void 0)continue;const c=a.map(u=>`"${u}"`).join(", ");throw new k("MASK_UNSUPPORTED",`defineShape "${r.exportName}" replicates table "${r.table}", which masks column(s) ${c} on at least one procedure. A shape runs no procedure, so \`.use(mask(...))\` never applies to its replicated rows — remove the shape, unmask the table, or wait for shape-masking support.`,{status:422})}},ne=(e,t,s)=>{const n=e.getSourceFile(t);if(n===void 0){e.createSourceFile(t,s,{overwrite:!0});return}n.getFullText()!==s&&n.replaceWithText(s)},Nt=(e,t,s)=>e.getSourceFile(t)?.getFullText()===s,yl=8,Al=e=>{const{agents:t,apiPath:s,generatedFunctionsPath:n,lunoraDirectory:i,migrations:r,project:a,shapes:c,usesSandbox:u,useUmbrella:d,workflows:S}=e;let x=tt(a,i),I=nt(a,i),g=st(a,i);rt([...x,...I].map(A=>A.filePath)),rt(g.filter(A=>A.stream).map(A=>A.filePath),"http-stream");for(let A=1;;A+=1){const C=Rs({agents:t,functions:x,httpRoutes:g,mutators:I,useUmbrella:d,workflows:S}),L=Ls({agents:t,functions:x,migrations:r,mutators:I,shapes:c,useUmbrella:d,usesSandbox:u});if(A>=yl||Nt(a,s,C)&&Nt(a,n,L))return{apiContent:C,functions:x,functionsContent:L,httpRoutes:g,mutators:I};ne(a,s,C),ne(a,n,L),x=tt(a,i),I=nt(a,i),g=st(a,i)}},Nl=e=>{const t=vl(e);return t?new Je({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Je({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},xu=(e,t)=>{const s=m(t),n=f(t,"schema.ts");P(n)&&s.push(n);for(const c of s){const u=e.getSourceFile(c);u===void 0?e.addSourceFileAtPath(c):u.refreshFromFileSystemSync()}const i=new Set(s.map(c=>At(c))),r=At(t),a=`${r}/`;for(const c of e.getSourceFiles()){const u=c.getFilePath();(u===r||u.startsWith(a))&&!i.has(u)&&e.removeSourceFile(c)}for(const c of e.getSourceFiles()){const u=c.getFilePath();if(!(u===r||u.startsWith(a)||u.includes("/node_modules/")))try{c.refreshFromFileSystemSync()}catch{e.removeSourceFile(c)}}},Eu=e=>{const t=El(),s=t?ge.now():0,n=f(e.projectRoot,e.lunoraDirectory??"lunora"),i=f(n,"schema.ts");if(!P(i))throw new k("INTERNAL",`schema.ts not found at ${i}`);const r=e.project??Nl(n);bn(Pi);const a=pn(r,i,e.projectRoot),{agents:c,containers:u,crons:d,dataModelContent:S,dependencies:x,env:I,featureUsage:g,hasFlags:A,hasNotify:C,identity:L,platformGate:b,queues:D,serverContent:U,storageRulesMetadata:$,usesSandbox:W,useUmbrella:K,workflows:F}=qn({lunoraDirectory:n,project:r,projectRoot:e.projectRoot,schema:a,target:e.target}),p=f(n,"_generated"),Ce=f(p,"dataModel.ts"),Fe=f(p,"server.ts"),Zt=f(p,"api.ts"),Jt=f(p,"functions.ts");ne(r,Ce,S),ne(r,Fe,U);const ce=nn(r,n),q=En(r,n),{apiContent:Oe,functions:B,functionsContent:Re,httpRoutes:es,mutators:ts}=Al({agents:c,apiPath:Zt,generatedFunctionsPath:Jt,lunoraDirectory:n,migrations:ce,project:r,shapes:q,useUmbrella:K,usesSandbox:W,workflows:F}),H=e.lint===!1?void 0:ps({adminRoutes:Xn(r,n),aiRawRuns:er(r,n),aiToolSideEffects:ur(r,n),argumentDerivedFetches:pr(r,n),argumentValidators:Nr(r,n),authApiCalls:Qs(r,n),authConfigs:Lr(r,n),browserUrlAccesses:_r(r,n),configCalls:Gr(r,n),containerKeyAccesses:Qr(r,n),containerOverrides:si(r,n),containers:u,exportSinks:oi(r,n),staleMigrationImports:Fc(r,n),failOpenGuards:di(r,n),flagReads:Si(r,n),flagSecurityDefaults:bi(r,n),geoIndexUsages:Ti(r,n),httpActionGuards:ki(r,n),httpHeaderWrites:Vi(r,n),hyperdriveCalls:en(r,n),identityClaimReads:Zi(r,n),imageDeliveryUrlAccesses:eo(r,n),inserts:tn(r,n),kvKeyAccesses:so(r,n,B),mailRecipientAccesses:ao(r,n),maskProcedures:sn(r,n),maskStrategies:ho(r,n),mutatorWrites:Ao(r,n),nondeterministicCalls:an(r,n),normalizeIdAuthorizations:_o(r,n),notifyCalls:ln(r,n),notifyConfig:cn(r,n),ownerFieldWrites:Wo(r,n,B),unrestrictedWhereBranches:cl(r,n),paymentWebhooks:ea(r,n),privilegedDispatches:pa(r,n),procedureProtections:Xa(r,n),queries:Gs(r,n),queues:D,r2sqlCalls:un(r,n),ratelimitKeySelectors:tc(r,n),rawRowReturns:cc(r,n),relationLoads:dc(r,n),rlsProcedures:dn(r,n),schema:a,secretLiterals:vc(r,n),shapes:q,softDeleteReads:yc(r,n),sqlInterpolations:wc(r,n),storageKeyAccesses:Rc(r,n,B),storageUploads:_c(r,n),vectorNamespaceAccesses:fl(r,n),workflowCalls:ml(r,n),workflows:F,wranglerVariables:e.wranglerVariables}),Le=H===void 0?[]:[...ds(H,{source:"static"}),...Wc(r,n,B)],ss=fn(r,n),De=po(r,n);Sl(q,De,uo(r,n));const ns=A?mi(r,n):[],le=b.signals.vectorStore!==!1,G=zc(g,{containerCount:u.length,cronCount:d.length,dependencies:x,hasPaymentTables:Yo(a.tables),queueCount:D.length,storageColumnCount:Object.keys(Ss(a)).length,storageRuleCount:$.rules.length,vectorIndexCount:a.vectorIndexes.length,vectorStoreSupported:le,workflowCount:F.length}),ke=t?ge.now():0,ue=Pn(a,ce.map(h=>h.id)),Me=ys({advisories:Le,advisorProcedures:H?.procedureProtections??[],agents:c,containers:u,env:I,flagKeys:ns,hasAccessFacade:g.access,hasAi:g.ai,hasAnalytics:g.analytics,hasBrowser:g.browser,hasFlags:A,hasHyperdrive:g.hyperdrive,hasImages:g.images,hasKv:g.kv,hasNotify:C,hasPayments:g.payments,hasPipelines:g.pipelines,hasR2sql:g.r2sql,hasVectors:le,hasX402:g.x402,maskMetadata:De,mutators:ts,queues:D,rlsMetadata:ss,schema:a,schemaSnapshot:ue,shapes:q,storageRules:$,studioFeatures:G,useUmbrella:K,workflows:F}),Ke=As(q,x.has("@lunora/db"),K),_e=Ns(u,a.jurisdiction),ze=bs(F),Ue=Ps(c),Be=Is(D),$e=ws(d),qe=Ts(a.vectorIndexes),Y=Cs(a,K),je=Fs(x.has("@lunora/seed")),Q=e.apiSpec??"openapi",de=Q==="openapi"||Q==="both",fe=Q==="openrpc"||Q==="both",Ve=vn({emailAgents:c.filter(h=>h.onEmail===!0).map(h=>({bindingName:h.bindingName,exportName:h.exportName})),hasAccess:x.has("@lunora/cloudflare-access"),hasAi:g.ai,hasAnalytics:g.analytics,hasAuth:x.has("@lunora/auth"),hasBrowser:g.browser,hasFramework:x.has("@lunora/astro")||x.has("@lunora/svelte")||x.has("@lunora/vue"),hasGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend!=="hyperdrive"),hasHyperdrive:g.hyperdrive,hasHyperdriveGlobal:a.tables.some(h=>h.shardMode==="global"&&h.globalBackend==="hyperdrive"),hasImages:g.images,hasKv:g.kv,hasKvIntrospector:G.kv,hasNotify:C,hasPayments:g.payments,hasR2sql:g.r2sql,hasQueue:D.some(h=>h.mode==="push"),hasScheduler:G.scheduler,hasStorage:G.storage,hasVectors:le,hasWorkflow:F.length>0,hasX402:g.x402,identity:L,jurisdiction:a.jurisdiction,tableNames:a.tables.map(h=>h.name),useUmbrella:K,vectorIndexCount:a.vectorIndexes.length,voiceAgents:c.filter(h=>h.voice===!0&&h.voiceBindingName!==void 0).map(h=>({bindingName:h.voiceBindingName,exportName:h.exportName})),wantsOpenApi:de,wantsOpenRpc:fe}),We=xl(e.projectRoot),He=Sn({functions:B,httpRoutes:es,version:We}),Ge=An({functions:B,version:We}),Ye=`${JSON.stringify(He,void 0,2)}
8
+ `,Qe=`${JSON.stringify(Ge,void 0,2)}
9
+ `,Xe=yn(He),Ze=Nn(Ge),pe=f(n,hl),rs=P(pe);if(e.dryRun||(P(p)||cs(p,{recursive:!0}),T(f(p,"app.ts"),Ve),T(Ce,S),T(f(p,"api.ts"),Oe),T(Fe,U),T(f(p,"functions.ts"),Re),T(f(p,"shard.ts"),Me),T(f(p,"crons.ts"),$e),T(f(p,"vectors.ts"),qe),T(f(p,"drizzle.global.ts"),Y.global),T(f(p,"drizzle.shard.ts"),Y.shard),O(f(p,"containers.ts"),_e),O(f(p,"workflows.ts"),ze),O(f(p,"agents.ts"),Ue),O(f(p,"queues.ts"),Be),O(f(p,"seed.ts"),je),O(f(p,"collections.ts"),Ke),O(f(p,"openapi.json"),de?Ye:""),O(f(p,"openapi.ts"),de?Xe:""),O(f(p,"openrpc.json"),fe?Qe:""),O(f(p,"openrpc.ts"),fe?Ze:""),(!rs||e.updateSchemaBaseline===!0)&&T(pe,fs(ue))),t){const h=ge.now(),is=Math.round(h-s),os=Math.round(ke-s),as=Math.round(h-ke);console.error(`@lunora/codegen: codegen took ${is.toString()}ms (discovery ${os.toString()}ms, emit ${as.toString()}ms)`)}return{advisories:Le,advisorContext:H,agents:c,containers:u,cronTriggers:Os(d),generated:{agents:Ue,api:Oe,app:Ve,collections:Ke,containers:_e,crons:$e,dataModel:S,drizzleGlobal:Y.global,drizzleShard:Y.shard,functions:Re,openApi:Ye,openApiModule:Xe,openRpc:Qe,openRpcModule:Ze,queues:Be,seed:je,server:U,shard:Me,vectors:qe,workflows:ze},migrations:ce,outputDirectory:p,platformDiagnostics:b.diagnostics,queues:D,schemaSnapshot:ue,schemaSnapshotPath:pe,workflows:F}};export{hl as SCHEMA_SNAPSHOT_FILENAME,Nl as createCodegenProject,vl as findTsconfig,xu as refreshCodegenProject,Eu as runCodegen};
@@ -1,3 +1,3 @@
1
- import{G as S}from"./emit-Dsr5DNpc.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
1
+ import{G as S}from"./emit-B6ud4F_z.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-BYg8Lpgb.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
2
2
  `,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
@@ -1 +1 @@
1
- import{LunoraError as _}from"@lunora/errors";import{Node as i,SyntaxKind as j}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as $}from"node:module";import{join as z}from"node:path";import{a as D}from"./parse-validator-CMV0eq2a.mjs";const C=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}},R=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}:{}}),p=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:R(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=p(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=C(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,p(a)]));break}case"record":{s.valueType=p(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=p(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(o=>p(o));break}}return s},M=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",F=(e,n)=>{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 "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},B=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return F(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(t).map(([r,o])=>[r,p(o)])),shardMode:M(e.shardMode),vectorIndexes:[]}},V=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([a,l])=>B(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).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:s,bareVectorIndexes:o,key:n}},q=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},J=e=>{const n=q(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===n)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},U=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},K=(e,n)=>{const t=J(e);if(t)try{const s=$(z(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),o=s(r),a=U(o,t);return typeof a!="object"||a===null?void 0:V(a)}catch{return}},G=new Set(["cosine","dot-product","euclidean"]),k=e=>e.replaceAll(/^["']|["']$/gu,""),g=(e,n)=>{const t=e.getProperty(n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=g(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},m=(e,n)=>{const t=g(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},Z=(e,n)=>{const t=g(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},x=(e,n)=>{const t=g(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},w=e=>e&&G.has(e)?e:void 0,b=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",Q=(e,n)=>{const t=x(e,n);return t!==void 0&&t.length>0?t:void 0},T=(e,n,t,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const u=c.getLiteralText();if(!s.has(u))throw f(c,`unknown ${t} ${JSON.stringify(u)} — expected ${r}`);return u}o=l}},W=new Set(["cascade","restrict","set null"]),I=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),X=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),H=/^[A-Za-z_$][\w$]*$/u,L=(e,n)=>{const t=k(e);if(I.has(t))throw f(n,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...I].map(s=>`"${s}"`).join(", ")}). Rename the table.`);if(X.has(t))throw f(n,`table name "${t}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${t} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!H.test(t))throw f(n,`table name ${JSON.stringify(t)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`)},Y=e=>e&&W.has(e)?e:void 0,ee=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},te=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,o]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",u;return o&&i.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,u=s==="one"?Y(d(o,"onDelete")):void 0),{field:l,kind:s,name:e.getName(),onDelete:u,references:c,table:a}},ne=e=>{const n=ee(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=te(s);r&&t.push(r)}return t},re=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — 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.`)},se=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=e.getProperty("unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},ie=e=>{const[n,t,s]=e,r=se(s),o=b(n),a=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw f(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=>i.isStringLiteral(c));for(const c of l)re(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},oe=e=>{const[n,t]=e;let s="_unknown_",r,o,a,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"filterFields"),o=d(t,"language"),a=Z(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:o,name:b(n),staged:a,strategy:l}},ae=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=m(t,"precision")),{field:s,name:b(n),precision:r}},le=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=m(t,"after")),{after:r,field:s}},ce=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},de=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ce(l)).filter(l=>l!==void 0))}r=x(t,"partitionBy")}return{name:b(n),partitionBy:r,sortBy:s}},fe=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:m(s,"dimensions"),field:r,metadata:x(s,"metadata"),metric:w(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},ue=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},pe=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=e.getProperty("field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},ge=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:Q(n,"columns"),hasReconcile:n.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:n.getProperty("softDeleteColumn")!==void 0,hasTenantBy:n.getProperty("tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},me=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ae(t));break}case"global":{e.shardMode="global",e.globalBackend=ue(t);break}case"index":{e.indexes.push(ie(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(de(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ne(r));break}case"searchIndex":{e.searchIndexes.push(oe(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:pe(t[0])};break}case"source":{e.externalSource=ge(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=le(t);break}case"vectorize":{const r=fe(t,s);r&&e.vectorIndexes.push(r);break}}},S=["__vocab","_config","_content","_data","_docsize","_idx"],xe=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const o of S){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.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 f(e,`table "${n}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${S.join(", ")}.`)}},O=(e,n)=>{const t={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))me(t,o.getName(),a,n),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=D(l);else if(l)throw f(l,`table "${n}" 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_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),xe(e,n,t.searchIndexes),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},be=e=>{const n=[],t=new Set;for(const s of e.getProperties()){if(!i.isPropertyAssignment(s))continue;const r=s.getInitializer();if(r){const o=s.getName();L(o,s.getNameNode());const a=k(o);if(t.has(a))throw f(s.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(a),n.push(O(r,o))}}return n},he=e=>{const n=e.getProperty("source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},ye=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:m(s,"dimensions"),metric:w(d(s,"metric")),name:o,table:he(s)}},P=e=>{const n=[];for(const t of e.getProperties()){const s=ye(t);s&&n.push(s)}return n},v=(e,n)=>`${e}_${n}`,y=(e,n,t)=>t.has(e)?v(n,e):e,ve=(e,n,t)=>{const s=v(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:y(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:y(r.table,n,t)}))}},Ee=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ie=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},Se=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},ke=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},we=(e,n)=>{const t=Ee(e);if(t){if(i.isPropertyAccessExpression(n)){const s=ke(t);return s?g(s,n.getName()):void 0}return t}},Te=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Ie(n))return n;const s=Se(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=we(a,n)}},Le=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),options:t}},Oe=e=>{const n=e.getProperty("tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=r.getName();L(a,r.getNameNode()),s.push(O(o,a))}return s},Pe=e=>{const n=e.getProperty("vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:P(t)},N=(e,n,t)=>{const s=new Set(n.map(a=>a.name)),r=n.map(a=>ve(a,e,s)),o=t.map(a=>({...a,name:v(e,a.name),table:y(a.table,e,s)}));return{tables:r,vectorIndexes:o}},Ne=(e,n)=>N(e,Oe(n),Pe(n)),Ae=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=Te(t);if(!s){if(n!==void 0){const o=K(t,n);if(o)return N(o.key,o.bareTables,o.bareVectorIndexes)}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===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 r=Le(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ne(r.key,r.options)},_e=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},je=(e,n,t)=>{const s=new Set(n.map(o=>o.name)),r=[];for(const o of _e(e)){const a=Ae(o,t);if(a){for(const l of a.tables){if(s.has(l.name))throw f(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...a.vectorIndexes)}}return r},$e=new Set(["eu","fedramp","us"]),ze=e=>T(e,"jurisdiction","jurisdiction",$e,'"eu", "us", or "fedramp"'),De=new Set(["required"]),Ce=e=>T(e,"rls","rls mode",De,'"required"'),Je=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(j.CallExpression).find(h=>{const E=h.getExpression();return i.isIdentifier(E)&&E.getText()==="defineSchema"});if(!r)throw new _("INTERNAL",`defineSchema() not found in ${n}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw f(r,"defineSchema() expects an object literal");const a=be(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?P(l):[],u=je(r,a,t),A=[...a.flatMap(h=>h.vectorIndexes),...c,...u];return{jurisdiction:ze(r),rlsMode:Ce(r),tables:a,vectorIndexes:A}};export{Je as default};
1
+ import{LunoraError as $}from"@lunora/errors";import{Node as i,SyntaxKind as j}from"ts-morph";import{diagnosticAt as f}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{createRequire as z}from"node:module";import{join as D}from"node:path";import{a as R}from"./parse-validator-CMV0eq2a.mjs";const C=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}},M=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}:{}}),p=e=>{const n=e?._meta??{},t=e?.kind??"unknown",s={column:M(n.column),kind:t};switch(t){case"array":case"optional":{s.inner=p(n.inner);break}case"from":break;case"id":{s.tableName=n.tableName;break}case"literal":{s.literalValue=C(n.value);break}case"object":{const r=n.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,p(a)]));break}case"record":{s.valueType=p(n.valueValidator),n.keyValidator!==void 0&&(s.keyType=p(n.keyValidator));break}case"storage":{typeof n.bucket=="string"&&(s.bucket=n.bucket);break}case"union":{const r=n.members??[];s.members=r.map(o=>p(o));break}}return s},F=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",B=(e,n)=>{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 "${n}" declares ${t.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},V=(e,n)=>{const t=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return B(e,n),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:n,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(t).map(([r,o])=>[r,p(o)])),shardMode:F(e.shardMode),vectorIndexes:[]}},q=e=>{const{key:n,tables:t}=e;if(typeof n!="string"||typeof t!="object"||t===null)return;const s=Object.entries(t).map(([a,l])=>V(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).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:s,bareVectorIndexes:o,key:n}},J=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n.getText():void 0}},U=e=>{const n=J(e);if(n===void 0)return;const t=i.isPropertyAccessExpression(e)?e.getName():void 0,s=t===void 0?[]:[t];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===n)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===n)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===n&&t!==void 0)return{importedName:t,moduleSpecifier:o,propertyPath:[]}}},K=(e,n)=>{let t=e[n.importedName];for(const s of n.propertyPath){if(typeof t!="object"||t===null)return;t=t[s]}return t},Z=(e,n)=>{const t=U(e);if(t)try{const s=z(D(n,"noop.cjs")),r=s.resolve(t.moduleSpecifier),o=s(r),a=K(o,t);return typeof a!="object"||a===null?void 0:q(a)}catch{return}},G=new Set(["cosine","dot-product","euclidean"]),w=e=>e.replaceAll(/^["']|["']$/gu,""),g=(e,n)=>{const t=e.getProperty(n);if(t&&i.isPropertyAssignment(t))return t.getInitializer()},d=(e,n)=>{const t=g(e,n);if(t&&i.isStringLiteral(t))return t.getLiteralText()},m=(e,n)=>{const t=g(e,n);if(t&&i.isNumericLiteral(t))return Number(t.getLiteralText())},Q=(e,n)=>{const t=g(e,n);if(t&&(i.isTrueLiteral(t)||i.isFalseLiteral(t)))return t.getLiteralValue()},x=(e,n)=>{const t=g(e,n);if(t&&i.isArrayLiteralExpression(t))return t.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},T=e=>e&&G.has(e)?e:void 0,b=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",W=(e,n)=>{const t=x(e,n);return t!==void 0&&t.length>0?t:void 0},L=(e,n,t,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===n){const c=l.getArguments()[0];if(!c||!i.isStringLiteral(c))throw f(l,`\`.${n}(...)\` expects a string literal (${r})`);const u=c.getLiteralText();if(!s.has(u))throw f(c,`unknown ${t} ${JSON.stringify(u)} — expected ${r}`);return u}o=l}},X=new Set(["cascade","restrict","set null"]),S=new Set(["delete","get","insert","normalizeId","patch","query","replace","system"]),H=new Set(["arguments","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","eval","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),N=/^[A-Za-z_$][\w$]*$/u,v=(e,n)=>{const t=w(e);if(S.has(t))throw f(n,`table name "${t}" is reserved — it collides with a \`ctx.db\` member (one of ${[...S].map(s=>`"${s}"`).join(", ")}). Rename the table.`);if(H.has(t))throw f(n,`table name "${t}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${t} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!N.test(t))throw f(n,`table name ${JSON.stringify(t)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`)},Y=e=>e&&X.has(e)?e:void 0,ee=e=>{if(!i.isArrowFunction(e))return;let n=e.getBody();if(i.isParenthesizedExpression(n))n=n.getExpression();else if(i.isBlock(n)){const t=n.getStatements().find(s=>i.isReturnStatement(s));n=t&&i.isReturnStatement(t)?t.getExpression()??n:n}return i.isObjectLiteralExpression(n)?n:void 0},te=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName();if(s!=="one"&&s!=="many")return;const[r,o]=n.getArguments();if(!r||!i.isStringLiteral(r))throw f(r??n,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();let l="_unknown_",c="_id",u;return o&&i.isObjectLiteralExpression(o)&&(l=d(o,"field")??l,c=d(o,"references")??c,u=s==="one"?Y(d(o,"onDelete")):void 0),{field:l,kind:s,name:e.getName(),onDelete:u,references:c,table:a}},ne=e=>{const n=ee(e);if(!n)return[];const t=[];for(const s of n.getProperties()){const r=te(s);r&&t.push(r)}return t},re=(e,n,t)=>{if(!n.includes("."))return;const[s="",...r]=n.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw f(e,`index "${t}" indexes the nested path ${JSON.stringify(n)} — 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.`)},se=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const n=e.getProperty("unique");if(!n||!i.isPropertyAssignment(n))return!1;const t=n.getInitializer();if(t===void 0)return!1;if(!i.isTrueLiteral(t)&&!i.isFalseLiteral(t))throw f(t,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(t.getText())}`);return i.isTrueLiteral(t)},ie=e=>{const[n,t,s]=e,r=se(s),o=b(n),a=t&&i.isArrayLiteralExpression(t)?t.getElements():[];for(const c of a)if(!i.isStringLiteral(c))throw f(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=>i.isStringLiteral(c));for(const c of l)re(c,c.getLiteralText(),o);return{fields:l.map(c=>c.getLiteralText()),name:o,unique:r}},oe=e=>{const[n,t]=e;let s="_unknown_",r,o,a,l;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=x(t,"filterFields"),o=d(t,"language"),a=Q(t,"staged"),l=d(t,"strategy")),{field:s,filterFields:r,language:o,name:b(n),staged:a,strategy:l}},ae=e=>{const[n,t]=e;let s="_unknown_",r;return t&&i.isObjectLiteralExpression(t)&&(s=d(t,"field")??s,r=m(t,"precision")),{field:s,name:b(n),precision:r}},le=e=>{const[n,t]=e,s=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";let r;return t&&i.isObjectLiteralExpression(t)&&(r=m(t,"after")),{after:r,field:s}},ce=e=>{if(!i.isObjectLiteralExpression(e))return;const n=d(e,"field");return n===void 0?void 0:{direction:d(e,"direction")==="desc"?"desc":"asc",field:n}},de=e=>{const[n,t]=e;let s=[],r;if(t&&i.isObjectLiteralExpression(t)){const o=t.getProperty("sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>ce(l)).filter(l=>l!==void 0))}r=x(t,"partitionBy")}return{name:b(n),partitionBy:r,sortBy:s}},fe=(e,n)=>{const[t,s]=e,r=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:m(s,"dimensions"),field:r,metadata:x(s,"metadata"),metric:T(d(s,"metric")),name:d(s,"index")??"_unnamed_",table:n}},ue=e=>{const n=e[0];return n&&i.isObjectLiteralExpression(n)&&d(n,"backend")==="hyperdrive"?"hyperdrive":"d1"},pe=e=>{if(e&&i.isObjectLiteralExpression(e)){const n=e.getProperty("field");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isStringLiteral(t))return t.getLiteralText()}}return"deletedAt"},ge=e=>{const n=e[0];return!n||!i.isObjectLiteralExpression(n)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:d(n,"binding")??"",columns:W(n,"columns"),hasReconcile:n.getProperty("reconcileEveryMs")!==void 0,hasSoftDelete:n.getProperty("softDeleteColumn")!==void 0,hasTenantBy:n.getProperty("tenantBy")!==void 0,idColumn:d(n,"idColumn"),mode:d(n,"mode"),query:d(n,"query")}},me=(e,n,t,s)=>{switch(n){case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ae(t));break}case"global":{e.shardMode="global",e.globalBackend=ue(t);break}case"index":{e.indexes.push(ie(t));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(de(t));break}case"relations":{const r=t[0];r&&e.relations.push(...ne(r));break}case"searchIndex":{e.searchIndexes.push(oe(t));break}case"shardBy":{const r=t[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:pe(t[0])};break}case"source":{e.externalSource=ge(t),e.externallyManaged=!0;break}case"ttl":{e.ttl=le(t);break}case"vectorize":{const r=fe(t,s);r&&e.vectorIndexes.push(r);break}}},k=["__vocab","_config","_content","_data","_docsize","_idx"],xe=(e,n,t)=>{const s=new Set(t.map(r=>r.name));for(const r of t)for(const o of k){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.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 f(e,`table "${n}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${n}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${k.join(", ")}.`)}},O=(e,n)=>{const t={commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))me(t,o.getName(),a,n),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=R(l);else if(l)throw f(l,`table "${n}" 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_${n}\` / \`Insert_${n}\` type instead of sharing the runtime value.`);break}else break}return t.softDelete&&!(t.softDelete.field in s)&&(s={...s,[t.softDelete.field]:{inner:{kind:"number"},kind:"optional"}}),xe(e,n,t.searchIndexes),{commitOrdered:t.commitOrdered,externallyManaged:t.externallyManaged,externalSource:t.externalSource,geoIndexes:t.geoIndexes,globalBackend:t.shardMode==="global"?t.globalBackend??"d1":void 0,indexes:t.indexes,isPublic:t.isPublic,memory:t.memory,name:n,rankIndexes:t.rankIndexes,relations:t.relations,searchIndexes:t.searchIndexes,shape:s,shardMode:t.shardMode,softDelete:t.softDelete,ttl:t.ttl,vectorIndexes:t.vectorIndexes}},be=e=>{const n=[],t=new Set;for(const s of e.getProperties()){if(!i.isPropertyAssignment(s))continue;const r=s.getInitializer();if(r){const o=s.getName();v(o,s.getNameNode());const a=w(o);if(t.has(a))throw f(s.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);t.add(a),n.push(O(r,o))}}return n},he=e=>{const n=e.getProperty("source");if(n&&i.isPropertyAssignment(n)){const t=n.getInitializer();if(t&&i.isObjectLiteralExpression(t))return d(t,"table")??"_unknown_"}return"_unknown_"},ye=e=>{if(!i.isPropertyAssignment(e))return;const n=e.getInitializer();if(!n||!i.isCallExpression(n))return;const t=n.getExpression();if(!i.isIdentifier(t)||t.getText()!=="defineVectorIndex")return;const s=n.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:m(s,"dimensions"),metric:T(d(s,"metric")),name:o,table:he(s)}},P=e=>{const n=[];for(const t of e.getProperties()){const s=ye(t);s&&n.push(s)}return n},E=(e,n)=>`${e}_${n}`,ve=(e,n)=>{if(!N.test(e))throw f(n,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},y=(e,n,t)=>t.has(e)?E(n,e):e,Ee=(e,n,t)=>{const s=E(n,e.name);return{...e,extensionKey:n,name:s,relations:e.relations.map(r=>({...r,table:y(r.table,n,t)})),vectorIndexes:e.vectorIndexes.map(r=>({...r,table:y(r.table,n,t)}))}},Ie=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Se=e=>{if(!i.isCallExpression(e))return!1;const n=e.getExpression();return i.isIdentifier(n)&&n.getText()==="defineSchemaExtension"},ke=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const n=e.getExpression();return i.isIdentifier(n)?n:void 0}},we=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const n=e.getExpression();let t;if(i.isIdentifier(n)?t=n.getText():i.isPropertyAccessExpression(n)&&(t=n.getName()),t==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},Te=(e,n)=>{const t=Ie(e);if(t){if(i.isPropertyAccessExpression(n)){const s=we(t);return s?g(s,n.getName()):void 0}return t}},Le=e=>{let n=e,t=0;for(;n&&t<32;){if(t+=1,Se(n))return n;const s=ke(n),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;n=Te(a,n)}},Ne=e=>{const[n,t]=e.getArguments();if(!(!n||!i.isStringLiteral(n))&&!(!t||!i.isObjectLiteralExpression(t)))return{key:n.getLiteralText(),keyNode:n,options:t}},Oe=e=>{const n=e.getProperty("tables");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();if(!t||!i.isObjectLiteralExpression(t))return[];const s=[];for(const r of t.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=r.getName();v(a,r.getNameNode()),s.push(O(o,a))}return s},Pe=e=>{const n=e.getProperty("vectorIndexes");if(!n||!i.isPropertyAssignment(n))return[];const t=n.getInitializer();return!t||!i.isObjectLiteralExpression(t)?[]:P(t)},A=(e,n,t,s)=>{ve(e,s);const r=new Set(n.map(l=>l.name)),o=n.map(l=>Ee(l,e,r)),a=t.map(l=>({...l,name:E(e,l.name),table:y(l.table,e,r)}));return{tables:o,vectorIndexes:a}},Ae=(e,n,t)=>A(e,Oe(t),Pe(t),n),_e=(e,n)=>{const t=e.getArguments()[0];if(!t)return;const s=Le(t);if(!s){if(n!==void 0){const o=Z(t,n);if(o){for(const a of o.bareTables)v(a.name,t);return A(o.key,o.bareTables,o.bareVectorIndexes,t)}}console.warn(`@lunora/codegen: skipping \`.extend(${t.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${n===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 r=Ne(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Ae(r.key,r.keyNode,r.options)},$e=e=>{const n=[];let t=e;for(;;){const s=t.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&n.push(r),t=r}return n},je=(e,n,t)=>{const s=new Set(n.map(o=>o.name)),r=[];for(const o of $e(e)){const a=_e(o,t);if(a){for(const l of a.tables){if(s.has(l.name))throw f(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),n.push(l)}r.push(...a.vectorIndexes)}}return r},ze=new Set(["eu","fedramp","us"]),De=e=>L(e,"jurisdiction","jurisdiction",ze,'"eu", "us", or "fedramp"'),Re=new Set(["required"]),Ce=e=>L(e,"rls","rls mode",Re,'"required"'),Ue=(e,n,t)=>{const r=e.addSourceFileAtPath(n).getDescendantsOfKind(j.CallExpression).find(h=>{const I=h.getExpression();return i.isIdentifier(I)&&I.getText()==="defineSchema"});if(!r)throw new $("INTERNAL",`defineSchema() not found in ${n}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw f(r,"defineSchema() expects an object literal");const a=be(o),l=r.getArguments()[1],c=l&&i.isObjectLiteralExpression(l)?P(l):[],u=je(r,a,t),_=[...a.flatMap(h=>h.vectorIndexes),...c,...u];return{jurisdiction:De(r),rlsMode:Ce(r),tables:a,vectorIndexes:_}};export{Ue as default};