@lunora/codegen 1.0.0-alpha.77 → 1.0.0-alpha.78

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
@@ -1,4 +1,4 @@
1
- import { AdvisorExportSink, AdvisorGeoIndexUsage, AdvisorNotifyCall, AdvisorNotifyConfig, Finding } from '@lunora/advisor';
1
+ import { AdvisorExportSink, AdvisorGeoIndexUsage, AdvisorNotifyCall, AdvisorNotifyConfig, Finding, LintContext, AdvisorProcedureProtection } from '@lunora/advisor';
2
2
  export type { Finding } from '@lunora/advisor';
3
3
  import { LunoraError } from '@lunora/errors';
4
4
  export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, type Solution as LunoraSolution, type SolutionRule as LunoraSolutionRule, findSolutionByMessage as findLunoraSolution } from '@lunora/errors';
@@ -803,6 +803,8 @@ interface WorkflowCallIR {
803
803
  * `query(...)` argument is not a string literal (a dynamic table — not lintable).
804
804
  */
805
805
  interface QueryReadIR {
806
+ /** Exported procedure the read sits in, or `""` at module scope. */
807
+ exportName: string;
806
808
  /** Source file relative to `<projectRoot>/lunora/`, without extension. */
807
809
  file: string;
808
810
  /** The chain calls `.filter(...)`. */
@@ -1115,12 +1117,20 @@ interface HttpRouteIR {
1115
1117
  interface ProcedureMiddlewareIR {
1116
1118
  /** `true` when the handler (or a helper inside it) references `ctx.mail` / `ctx.email`. */
1117
1119
  callsMail: boolean;
1120
+ /** `true` when the handler emits a structured observability event (`ctx.log` / `ctx.span` / `ctx.trace`). */
1121
+ emitsEvent: boolean;
1122
+ /** `true` when a `// lunora-advisor-exempt` directive sits above the export. */
1123
+ exempt: boolean;
1124
+ /** The `-- reason` from that directive, or `""`. */
1125
+ exemptReason: string;
1118
1126
  /** Export binding name of the procedure (e.g. `signUp`). */
1119
1127
  exportName: string;
1120
1128
  /** `true` when the handler fans work out to a privileged, cost-bearing dispatch surface (scheduler `runAfter`/`runAt`, a queue producer send, or a workflow create). Feeds the privileged-fanout lint. */
1121
1129
  fanOut: boolean;
1122
1130
  /** Source file relative to `<projectRoot>/lunora/`, without extension. */
1123
1131
  file: string;
1132
+ /** `true` when the handler wraps work in `try`/`catch`. */
1133
+ handlesErrors: boolean;
1124
1134
  /**
1125
1135
  * `true` when the procedure declares an email-shaped argument (`email`,
1126
1136
  * `emailAddress`, `userEmail`, …), `false` when it provably declares none,
@@ -1132,8 +1142,13 @@ interface ProcedureMiddlewareIR {
1132
1142
  * registration that may well expose one.
1133
1143
  */
1134
1144
  hasEmailArg?: boolean;
1135
- /** Registration kind — only `mutation`/`action` are write-shaped; `query` is read-only. */
1136
1145
  kind: "action" | "mutation" | "query";
1146
+ /** `true` when the handler reaches an outbound surface (`ctx.fetch`, mail, queues, storage, sql, ai, …) that can fail. */
1147
+ reachesOutbound: boolean;
1148
+ /** `true` when the handler runs any AI generation, bounded or not. */
1149
+ runsAiGeneration: boolean;
1150
+ /** `true` when the handler throws a bare `new Error(...)` rather than a coded `LunoraError`. */
1151
+ throwsBareError: boolean;
1137
1152
  /** `true` when the handler runs an AI generation (`generateText`/`streamText`/`generateObject`/`streamObject`) with no `maxOutputTokens` bound in its config literal. Feeds the `ai_unbounded_generation_public` lint. */
1138
1153
  unboundedAiGeneration: boolean;
1139
1154
  /** `true` when the chain carries `.use(verifyTurnstile(...))` or a `protectPublic({ captcha })` bundle. */
@@ -1888,22 +1903,6 @@ interface ProjectIR {
1888
1903
  migrations: ReadonlyArray<MigrationIR>;
1889
1904
  schema: SchemaIR;
1890
1905
  }
1891
- /**
1892
- * Run the static lints against a discovered {@link SchemaIR} and the reads/writes/calls
1893
- * found in function bodies: query reads feed `filter_without_index`, insert writes
1894
- * feed `table_without_insert`, authApi calls feed `auth_api_call_without_headers`,
1895
- * rls procedure snapshots feed `rls_uncovered_table`, mask procedure
1896
- * snapshots feed `mask_uncovered_pii_column`, and per-column mask strategies
1897
- * feed `mask_weak_hash_strategy_on_pii`; declared containers
1898
- * feed the `container_*` lints; declared workflows (with their durable step labels)
1899
- * + `ctx.workflows.get(...)` call sites feed the `workflow_unused` /
1900
- * `workflow_unknown_target` / duplicate-step-name lints; non-deterministic
1901
- * calls inside query/mutation handlers feed the `nondeterministic_query_mutation` lint
1902
- * (all default empty for callers that don't analyze functions/containers/workflows).
1903
- * The IR types are structurally identical to the advisor's evidence types so they
1904
- * pass straight through without conversion. Returns the findings; surfacing them
1905
- * (console, error overlay, studio Advisors table) is the caller's choice.
1906
- */
1907
1906
  /**
1908
1907
  * Named inputs for {@link lintSchema}. Every feeder is a discrete key rather than
1909
1908
  * a positional argument: the feeder list grows every few releases and many IR
@@ -1968,6 +1967,38 @@ interface LintSchemaOptions {
1968
1967
  workflows?: ReadonlyArray<WorkflowIR>;
1969
1968
  wranglerVariables?: ReadonlyArray<WranglerVariableIR>;
1970
1969
  }
1970
+ /**
1971
+ * Normalize feeder options into the advisor's {@link LintContext} — the input
1972
+ * both `runAdvisor` and `scoreAdvisor` take. Shared by {@link lintSchema} so the
1973
+ * lint run and the scored map always see byte-identical evidence.
1974
+ *
1975
+ * Exported instead of a `mapSchema(options)` convenience that lints *and* scores:
1976
+ * such a wrapper would either re-run every rule or need a `findings` escape hatch
1977
+ * nothing could validate against its `options`, so mismatched findings would
1978
+ * silently produce a wrong map. Two lines at the call site buys that away:
1979
+ *
1980
+ * ```ts
1981
+ * const context = toAdvisorContext(options);
1982
+ * const map = scoreAdvisor(context.procedureProtections ?? [], runAdvisor(context, { source: "static" }));
1983
+ * ```
1984
+ */
1985
+ declare const toAdvisorContext: (options: LintSchemaOptions) => LintContext;
1986
+ /**
1987
+ * Run the static lints against a discovered {@link SchemaIR} and the reads/writes/calls
1988
+ * found in function bodies: query reads feed `filter_without_index`, insert writes
1989
+ * feed `table_without_insert`, authApi calls feed `auth_api_call_without_headers`,
1990
+ * rls procedure snapshots feed `rls_uncovered_table`, mask procedure
1991
+ * snapshots feed `mask_uncovered_pii_column`, and per-column mask strategies
1992
+ * feed `mask_weak_hash_strategy_on_pii`; declared containers
1993
+ * feed the `container_*` lints; declared workflows (with their durable step labels)
1994
+ * + `ctx.workflows.get(...)` call sites feed the `workflow_unused` /
1995
+ * `workflow_unknown_target` / duplicate-step-name lints; non-deterministic
1996
+ * calls inside query/mutation handlers feed the `nondeterministic_query_mutation` lint
1997
+ * (all default empty for callers that don't analyze functions/containers/workflows).
1998
+ * The IR types are structurally identical to the advisor's evidence types so they
1999
+ * pass straight through without conversion. Returns the findings; surfacing them
2000
+ * (console, error overlay, studio Advisors table) is the caller's choice.
2001
+ */
1971
2002
  declare const lintSchema: (options: LintSchemaOptions) => Finding[];
1972
2003
  /**
1973
2004
  * Render advisor findings as a single multi-line string for console surfacing:
@@ -2379,6 +2410,8 @@ declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>) => string;
2379
2410
  declare const emitAgents: (agents: ReadonlyArray<AgentIR>) => string;
2380
2411
  interface EmitShardOptions {
2381
2412
  advisories?: ReadonlyArray<Finding>;
2413
+ /** Every declared procedure — the health map's denominator, served via `getAdvisorProcedures`. */
2414
+ advisorProcedures?: ReadonlyArray<AdvisorProcedureProtection>;
2382
2415
  /** Agents declared via `defineAgent` exports in `lunora/agents.ts` — wires the typed `ctx.agents` producers. */
2383
2416
  agents?: ReadonlyArray<AgentIR>;
2384
2417
  containers?: ReadonlyArray<ContainerIR>;
@@ -2436,7 +2469,7 @@ interface EmitShardOptions {
2436
2469
  useUmbrella?: boolean;
2437
2470
  workflows?: ReadonlyArray<WorkflowIR>;
2438
2471
  }
2439
- declare const emitShard: ({ advisories, 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;
2472
+ 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;
2440
2473
  /**
2441
2474
  * Emit drizzle `sqliteTable` definitions for the project schema, split into
2442
2475
  * `global` (D1-backed) and `shard` (DO-SQLite-backed) buckets. Tables marked
@@ -2769,6 +2802,15 @@ interface CodegenOptions {
2769
2802
  wranglerVariables?: ReadonlyArray<WranglerVariableIR>;
2770
2803
  }
2771
2804
  interface CodegenResult {
2805
+ /**
2806
+ * The normalized advisor evidence the findings were produced from, so a
2807
+ * caller can score it into a health map (`scoreAdvisor`) without re-running
2808
+ * discovery. `undefined` under `lint: false`.
2809
+ *
2810
+ * Deliberately not scored here: the map carries a `generatedAt` stamp, and
2811
+ * codegen's result stays a pure function of the sources.
2812
+ */
2813
+ advisorContext?: LintContext;
2772
2814
  /**
2773
2815
  * Static schema advisor findings (e.g. unindexed foreign keys) produced
2774
2816
  * this run. Empty when `lint` is `false` or the schema is clean. Codegen
@@ -2956,4 +2998,4 @@ declare const secretKindOf: (value: string) => string | undefined;
2956
2998
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
2957
2999
  declare const redact: (value: string) => string;
2958
3000
  declare const VERSION = "0.0.0";
2959
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, redact, refreshCodegenProject, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, validatorIrToJsonSchema };
3001
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, redact, refreshCodegenProject, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AdvisorExportSink, AdvisorGeoIndexUsage, AdvisorNotifyCall, AdvisorNotifyConfig, Finding } from '@lunora/advisor';
1
+ import { AdvisorExportSink, AdvisorGeoIndexUsage, AdvisorNotifyCall, AdvisorNotifyConfig, Finding, LintContext, AdvisorProcedureProtection } from '@lunora/advisor';
2
2
  export type { Finding } from '@lunora/advisor';
3
3
  import { LunoraError } from '@lunora/errors';
4
4
  export { MESSAGE_SOLUTIONS as LUNORA_SOLUTION_RULES, type Solution as LunoraSolution, type SolutionRule as LunoraSolutionRule, findSolutionByMessage as findLunoraSolution } from '@lunora/errors';
@@ -803,6 +803,8 @@ interface WorkflowCallIR {
803
803
  * `query(...)` argument is not a string literal (a dynamic table — not lintable).
804
804
  */
805
805
  interface QueryReadIR {
806
+ /** Exported procedure the read sits in, or `""` at module scope. */
807
+ exportName: string;
806
808
  /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
807
809
  file: string;
808
810
  /** The chain calls `.filter(...)`. */
@@ -1115,12 +1117,20 @@ interface HttpRouteIR {
1115
1117
  interface ProcedureMiddlewareIR {
1116
1118
  /** `true` when the handler (or a helper inside it) references `ctx.mail` / `ctx.email`. */
1117
1119
  callsMail: boolean;
1120
+ /** `true` when the handler emits a structured observability event (`ctx.log` / `ctx.span` / `ctx.trace`). */
1121
+ emitsEvent: boolean;
1122
+ /** `true` when a `// lunora-advisor-exempt` directive sits above the export. */
1123
+ exempt: boolean;
1124
+ /** The `-- reason` from that directive, or `""`. */
1125
+ exemptReason: string;
1118
1126
  /** Export binding name of the procedure (e.g. `signUp`). */
1119
1127
  exportName: string;
1120
1128
  /** `true` when the handler fans work out to a privileged, cost-bearing dispatch surface (scheduler `runAfter`/`runAt`, a queue producer send, or a workflow create). Feeds the privileged-fanout lint. */
1121
1129
  fanOut: boolean;
1122
1130
  /** Source file relative to `&lt;projectRoot>/lunora/`, without extension. */
1123
1131
  file: string;
1132
+ /** `true` when the handler wraps work in `try`/`catch`. */
1133
+ handlesErrors: boolean;
1124
1134
  /**
1125
1135
  * `true` when the procedure declares an email-shaped argument (`email`,
1126
1136
  * `emailAddress`, `userEmail`, …), `false` when it provably declares none,
@@ -1132,8 +1142,13 @@ interface ProcedureMiddlewareIR {
1132
1142
  * registration that may well expose one.
1133
1143
  */
1134
1144
  hasEmailArg?: boolean;
1135
- /** Registration kind — only `mutation`/`action` are write-shaped; `query` is read-only. */
1136
1145
  kind: "action" | "mutation" | "query";
1146
+ /** `true` when the handler reaches an outbound surface (`ctx.fetch`, mail, queues, storage, sql, ai, …) that can fail. */
1147
+ reachesOutbound: boolean;
1148
+ /** `true` when the handler runs any AI generation, bounded or not. */
1149
+ runsAiGeneration: boolean;
1150
+ /** `true` when the handler throws a bare `new Error(...)` rather than a coded `LunoraError`. */
1151
+ throwsBareError: boolean;
1137
1152
  /** `true` when the handler runs an AI generation (`generateText`/`streamText`/`generateObject`/`streamObject`) with no `maxOutputTokens` bound in its config literal. Feeds the `ai_unbounded_generation_public` lint. */
1138
1153
  unboundedAiGeneration: boolean;
1139
1154
  /** `true` when the chain carries `.use(verifyTurnstile(...))` or a `protectPublic({ captcha })` bundle. */
@@ -1888,22 +1903,6 @@ interface ProjectIR {
1888
1903
  migrations: ReadonlyArray<MigrationIR>;
1889
1904
  schema: SchemaIR;
1890
1905
  }
1891
- /**
1892
- * Run the static lints against a discovered {@link SchemaIR} and the reads/writes/calls
1893
- * found in function bodies: query reads feed `filter_without_index`, insert writes
1894
- * feed `table_without_insert`, authApi calls feed `auth_api_call_without_headers`,
1895
- * rls procedure snapshots feed `rls_uncovered_table`, mask procedure
1896
- * snapshots feed `mask_uncovered_pii_column`, and per-column mask strategies
1897
- * feed `mask_weak_hash_strategy_on_pii`; declared containers
1898
- * feed the `container_*` lints; declared workflows (with their durable step labels)
1899
- * + `ctx.workflows.get(...)` call sites feed the `workflow_unused` /
1900
- * `workflow_unknown_target` / duplicate-step-name lints; non-deterministic
1901
- * calls inside query/mutation handlers feed the `nondeterministic_query_mutation` lint
1902
- * (all default empty for callers that don't analyze functions/containers/workflows).
1903
- * The IR types are structurally identical to the advisor's evidence types so they
1904
- * pass straight through without conversion. Returns the findings; surfacing them
1905
- * (console, error overlay, studio Advisors table) is the caller's choice.
1906
- */
1907
1906
  /**
1908
1907
  * Named inputs for {@link lintSchema}. Every feeder is a discrete key rather than
1909
1908
  * a positional argument: the feeder list grows every few releases and many IR
@@ -1968,6 +1967,38 @@ interface LintSchemaOptions {
1968
1967
  workflows?: ReadonlyArray<WorkflowIR>;
1969
1968
  wranglerVariables?: ReadonlyArray<WranglerVariableIR>;
1970
1969
  }
1970
+ /**
1971
+ * Normalize feeder options into the advisor's {@link LintContext} — the input
1972
+ * both `runAdvisor` and `scoreAdvisor` take. Shared by {@link lintSchema} so the
1973
+ * lint run and the scored map always see byte-identical evidence.
1974
+ *
1975
+ * Exported instead of a `mapSchema(options)` convenience that lints *and* scores:
1976
+ * such a wrapper would either re-run every rule or need a `findings` escape hatch
1977
+ * nothing could validate against its `options`, so mismatched findings would
1978
+ * silently produce a wrong map. Two lines at the call site buys that away:
1979
+ *
1980
+ * ```ts
1981
+ * const context = toAdvisorContext(options);
1982
+ * const map = scoreAdvisor(context.procedureProtections ?? [], runAdvisor(context, { source: "static" }));
1983
+ * ```
1984
+ */
1985
+ declare const toAdvisorContext: (options: LintSchemaOptions) => LintContext;
1986
+ /**
1987
+ * Run the static lints against a discovered {@link SchemaIR} and the reads/writes/calls
1988
+ * found in function bodies: query reads feed `filter_without_index`, insert writes
1989
+ * feed `table_without_insert`, authApi calls feed `auth_api_call_without_headers`,
1990
+ * rls procedure snapshots feed `rls_uncovered_table`, mask procedure
1991
+ * snapshots feed `mask_uncovered_pii_column`, and per-column mask strategies
1992
+ * feed `mask_weak_hash_strategy_on_pii`; declared containers
1993
+ * feed the `container_*` lints; declared workflows (with their durable step labels)
1994
+ * + `ctx.workflows.get(...)` call sites feed the `workflow_unused` /
1995
+ * `workflow_unknown_target` / duplicate-step-name lints; non-deterministic
1996
+ * calls inside query/mutation handlers feed the `nondeterministic_query_mutation` lint
1997
+ * (all default empty for callers that don't analyze functions/containers/workflows).
1998
+ * The IR types are structurally identical to the advisor's evidence types so they
1999
+ * pass straight through without conversion. Returns the findings; surfacing them
2000
+ * (console, error overlay, studio Advisors table) is the caller's choice.
2001
+ */
1971
2002
  declare const lintSchema: (options: LintSchemaOptions) => Finding[];
1972
2003
  /**
1973
2004
  * Render advisor findings as a single multi-line string for console surfacing:
@@ -2379,6 +2410,8 @@ declare const emitWorkflows: (workflows: ReadonlyArray<WorkflowIR>) => string;
2379
2410
  declare const emitAgents: (agents: ReadonlyArray<AgentIR>) => string;
2380
2411
  interface EmitShardOptions {
2381
2412
  advisories?: ReadonlyArray<Finding>;
2413
+ /** Every declared procedure — the health map's denominator, served via `getAdvisorProcedures`. */
2414
+ advisorProcedures?: ReadonlyArray<AdvisorProcedureProtection>;
2382
2415
  /** Agents declared via `defineAgent` exports in `lunora/agents.ts` — wires the typed `ctx.agents` producers. */
2383
2416
  agents?: ReadonlyArray<AgentIR>;
2384
2417
  containers?: ReadonlyArray<ContainerIR>;
@@ -2436,7 +2469,7 @@ interface EmitShardOptions {
2436
2469
  useUmbrella?: boolean;
2437
2470
  workflows?: ReadonlyArray<WorkflowIR>;
2438
2471
  }
2439
- declare const emitShard: ({ advisories, 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;
2472
+ 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;
2440
2473
  /**
2441
2474
  * Emit drizzle `sqliteTable` definitions for the project schema, split into
2442
2475
  * `global` (D1-backed) and `shard` (DO-SQLite-backed) buckets. Tables marked
@@ -2769,6 +2802,15 @@ interface CodegenOptions {
2769
2802
  wranglerVariables?: ReadonlyArray<WranglerVariableIR>;
2770
2803
  }
2771
2804
  interface CodegenResult {
2805
+ /**
2806
+ * The normalized advisor evidence the findings were produced from, so a
2807
+ * caller can score it into a health map (`scoreAdvisor`) without re-running
2808
+ * discovery. `undefined` under `lint: false`.
2809
+ *
2810
+ * Deliberately not scored here: the map carries a `generatedAt` stamp, and
2811
+ * codegen's result stays a pure function of the sources.
2812
+ */
2813
+ advisorContext?: LintContext;
2772
2814
  /**
2773
2815
  * Static schema advisor findings (e.g. unindexed foreign keys) produced
2774
2816
  * this run. Empty when `lint` is `false` or the schema is clean. Codegen
@@ -2956,4 +2998,4 @@ declare const secretKindOf: (value: string) => string | undefined;
2956
2998
  /** A redacted preview of a secret value — first 4 chars plus its length, never the full value. */
2957
2999
  declare const redact: (value: string) => string;
2958
3000
  declare const VERSION = "0.0.0";
2959
- export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, redact, refreshCodegenProject, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, validatorIrToJsonSchema };
3001
+ export { AGENTS_FILENAME, type AgentIR, type AuthApiCallIR, CONTAINERS_FILENAME, CodegenDiagnosticError, type CodegenOptions, type CodegenResult, type ContainerIR, type CronJobIR, type DriftChange, type DriftScope, type EmitAppOptions, FLAGS_FILENAME, type FieldSnapshot, type FlagsIR, type FunctionIR, GENERATED_HEADER, type HttpRouteIR, type IndexIR, type IndexSnapshot, type InsertWriteIR, LUNORA_ERROR_CODES, type LintSchemaOptions, MUTATORS_FILENAME, type MaskProcedureIR, type MigrationIR, type MutatorIR, NOTIFY_FILENAME, OPENRPC_VERSION, type OpenApiEmitInput, type OpenRpcEmitInput, type ProjectIR, QUEUES_FILENAME, type QueryReadIR, type QueueIR, type R2sqlCallIR, type RelationSnapshot, type RlsMetadataIR, type RlsPolicyIR, type RlsProcedureIR, type RlsRoleIR, SCHEMA_SNAPSHOT_FILENAME, SCHEMA_SNAPSHOT_VERSION, SHAPES_FILENAME, type SandboxUsage, type SchemaDrift, type SchemaDriftDecision, type SchemaIR, type SchemaSnapshot, SchemaSnapshotParseError, type ShapeIR, type StorageRuleIR, type StorageRulesMetadataIR, type TableIR, type TableSnapshot, VERSION, type ValidatorIR, type VectorIndexIR, WORKFLOWS_FILENAME, type WorkflowIR, type WranglerVariableIR, buildOpenApiDocument, buildOpenRpcDocument, buildSchemaSnapshot, createCodegenProject, diagnosticAt, diffSchemaSnapshots, discoverAgents, discoverAuthApiCalls, discoverContainers, discoverCrons, discoverFlags, discoverFunctions, discoverHttpRoutes, discoverInserts, discoverMaskProcedures, discoverMigrations, discoverMutators, discoverNondeterministicCalls, discoverNotifyCalls, discoverNotifyConfig, discoverQueries, discoverQueues, discoverR2sqlCalls, discoverRlsMetadata, discoverRlsProcedures, discoverSandboxUsage, discoverSchema, discoverShapes, discoverStorageRulesMetadata, discoverWorkflows, emitAgents, emitApi, emitApp, emitCollections, emitContainers, emitCrons, emitDataModel, emitDrizzleSchema, emitFunctions, emitOpenApi, emitOpenApiModule, emitOpenRpc, emitOpenRpcModule, emitServer, emitShard, emitVectors, emitWorkflows, emitWranglerCronTriggers, evaluateSchemaDrift, formatAdvisories, lintSchema, parseSchemaSnapshot, redact, refreshCodegenProject, runCodegen, schemaFromIr, secretKindOf, serializeSchemaSnapshot, toAdvisorContext, validatorIrToJsonSchema };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d}from"./packem_shared/formatAdvisories-DZvv-0MG.mjs";import{CodegenDiagnosticError as p,diagnosticAt as c}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as S,discoverAgents as l}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as x}from"./packem_shared/discoverAuthApiCalls-CEk3J0kc.mjs";import{CONTAINERS_FILENAME as A,discoverContainers as v}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as O}from"./packem_shared/discoverCrons-kIgM9ZJC.mjs";import{FLAGS_FILENAME as M,discoverFlags as h}from"./packem_shared/FLAGS_FILENAME-CQDN7BKc.mjs";import{discoverFunctions as I}from"./packem_shared/discoverFunctions-DnqHgv0t.mjs";import{default as g}from"./packem_shared/discoverHttpRoutes-CLn3VDRI.mjs";import{default as F}from"./packem_shared/discoverInserts-Cn-CLKET.mjs";import{default as P}from"./packem_shared/discoverMaskProcedures-fZtvsy8v.mjs";import{default as U}from"./packem_shared/discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as W,discoverMutators as b}from"./packem_shared/MUTATORS_FILENAME-3Akvs4aT.mjs";import{default as G}from"./packem_shared/discoverNondeterministicCalls-Cl7qNL0J.mjs";import{NOTIFY_FILENAME as V,discoverNotifyCalls as w,discoverNotifyConfig as y}from"./packem_shared/NOTIFY_FILENAME-B2lXWa7r.mjs";import{default as K}from"./packem_shared/discoverQueries-DENx_T6c.mjs";import{QUEUES_FILENAME as q,discoverQueues as B}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as Y}from"./packem_shared/discoverR2sqlCalls-CMNfDWlq.mjs";import{discoverRlsMetadata as X,default as $}from"./packem_shared/discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as oe}from"./packem_shared/discoverSandboxUsage-Bn1X9COt.mjs";import{default as te}from"./packem_shared/discoverSchema-Cy4OQ0Cu.mjs";import{SHAPES_FILENAME as ae,discoverShapes as ie}from"./packem_shared/SHAPES_FILENAME-maut3z1K.mjs";import{default as de}from"./packem_shared/discoverStorageRulesMetadata-CL8J41rX.mjs";import{WORKFLOWS_FILENAME as pe,discoverWorkflows as ce}from"./packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{w as Se,K as le,g as Ee,h as xe,W as ue,i as Ae,Z as ve,s as Ne,v as Oe,k as Re,t as Me,l as he,Q as Ce,c as Ie}from"./packem_shared/emit-sQzv_a8t.mjs";import{emitApp as ge}from"./packem_shared/emitApp-D5X1S54W.mjs";import{buildOpenApiDocument as Fe,emitOpenApi as Te,emitOpenApiModule as Pe}from"./packem_shared/buildOpenApiDocument-DeMEuKaw.mjs";import{OPENRPC_VERSION as Ue,buildOpenRpcDocument as He,emitOpenRpc as We,emitOpenRpcModule as be}from"./packem_shared/OPENRPC_VERSION-67sJ7JrS.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Ge,createCodegenProject as Qe,refreshCodegenProject as Ve,runCodegen as we}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-x_pw6Agi.mjs";import{SchemaSnapshotParseError as ze,buildSchemaSnapshot as Ke,evaluateSchemaDrift as je,parseSchemaSnapshot as qe}from"./packem_shared/SchemaSnapshotParseError-0KRzSjo4.mjs";import{schemaFromIr as Je}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as Ze,validatorIrToJsonSchema as Xe}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as eo,secretKindOf as oo}from"./packem_shared/redact-CQ8-to6l.mjs";import{MESSAGE_SOLUTIONS as to,findSolutionByMessage as so}from"@lunora/errors";const e="0.0.0";export{S as AGENTS_FILENAME,A as CONTAINERS_FILENAME,p as CodegenDiagnosticError,M as FLAGS_FILENAME,Se as GENERATED_HEADER,Ze as LUNORA_ERROR_CODES,to as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,V as NOTIFY_FILENAME,Ue as OPENRPC_VERSION,q as QUEUES_FILENAME,Ge as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ae as SHAPES_FILENAME,ze as SchemaSnapshotParseError,e as VERSION,pe as WORKFLOWS_FILENAME,Fe as buildOpenApiDocument,He as buildOpenRpcDocument,Ke as buildSchemaSnapshot,Qe as createCodegenProject,c as diagnosticAt,s as diffSchemaSnapshots,l as discoverAgents,x as discoverAuthApiCalls,v as discoverContainers,O as discoverCrons,h as discoverFlags,I as discoverFunctions,g as discoverHttpRoutes,F as discoverInserts,P as discoverMaskProcedures,U as discoverMigrations,b as discoverMutators,G as discoverNondeterministicCalls,w as discoverNotifyCalls,y as discoverNotifyConfig,K as discoverQueries,B as discoverQueues,Y as discoverR2sqlCalls,X as discoverRlsMetadata,$ as discoverRlsProcedures,oe as discoverSandboxUsage,te as discoverSchema,ie as discoverShapes,de as discoverStorageRulesMetadata,ce as discoverWorkflows,le as emitAgents,Ee as emitApi,ge as emitApp,xe as emitCollections,ue as emitContainers,Ae as emitCrons,ve as emitDataModel,Ne as emitDrizzleSchema,Oe as emitFunctions,Te as emitOpenApi,Pe as emitOpenApiModule,We as emitOpenRpc,be as emitOpenRpcModule,Re as emitServer,Me as emitShard,he as emitVectors,Ce as emitWorkflows,Ie as emitWranglerCronTriggers,je as evaluateSchemaDrift,so as findLunoraSolution,m as formatAdvisories,d as lintSchema,qe as parseSchemaSnapshot,eo as redact,Ve as refreshCodegenProject,we as runCodegen,Je as schemaFromIr,oo as secretKindOf,a as serializeSchemaSnapshot,Xe as validatorIrToJsonSchema};
1
+ import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as p}from"./packem_shared/formatAdvisories-BCEfzLT0.mjs";import{CodegenDiagnosticError as c,diagnosticAt as n}from"./packem_shared/CodegenDiagnosticError-DPezpZTz.mjs";import{AGENTS_FILENAME as l,discoverAgents as E}from"./packem_shared/AGENTS_FILENAME-BesaDYkL.mjs";import{default as u}from"./packem_shared/discoverAuthApiCalls-CEk3J0kc.mjs";import{CONTAINERS_FILENAME as v,discoverContainers as N}from"./packem_shared/CONTAINERS_FILENAME-CFwdyaCI.mjs";import{default as R}from"./packem_shared/discoverCrons-kIgM9ZJC.mjs";import{FLAGS_FILENAME as h,discoverFlags as C}from"./packem_shared/FLAGS_FILENAME-CQDN7BKc.mjs";import{discoverFunctions as _}from"./packem_shared/discoverFunctions-DnqHgv0t.mjs";import{default as L}from"./packem_shared/discoverHttpRoutes-CLn3VDRI.mjs";import{default as T}from"./packem_shared/discoverInserts-Cn-CLKET.mjs";import{default as D}from"./packem_shared/discoverMaskProcedures-fZtvsy8v.mjs";import{default as H}from"./packem_shared/discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as W,discoverMutators as G}from"./packem_shared/MUTATORS_FILENAME-3Akvs4aT.mjs";import{default as V}from"./packem_shared/discoverNondeterministicCalls-Cl7qNL0J.mjs";import{NOTIFY_FILENAME as w,discoverNotifyCalls as y,discoverNotifyConfig as z}from"./packem_shared/NOTIFY_FILENAME-B2lXWa7r.mjs";import{E as j}from"./packem_shared/discover-queries-LfER8HbK.mjs";import{QUEUES_FILENAME as B,discoverQueues as J}from"./packem_shared/QUEUES_FILENAME-CSE6i-ld.mjs";import{default as $}from"./packem_shared/discoverR2sqlCalls-CMNfDWlq.mjs";import{discoverRlsMetadata as Z,default as ee}from"./packem_shared/discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as re}from"./packem_shared/discoverSandboxUsage-Bn1X9COt.mjs";import{default as se}from"./packem_shared/discoverSchema-Cy4OQ0Cu.mjs";import{SHAPES_FILENAME as ie,discoverShapes as me}from"./packem_shared/SHAPES_FILENAME-maut3z1K.mjs";import{default as pe}from"./packem_shared/discoverStorageRulesMetadata-CL8J41rX.mjs";import{WORKFLOWS_FILENAME as ce,discoverWorkflows as ne}from"./packem_shared/WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{w as le,H as Ee,h as xe,b as ue,Q as Ae,c as ve,t as Ne,l as Oe,$ as Re,v as Me,r as he,d as Ce,K as Ie,u as _e}from"./packem_shared/emit-BtiV37rG.mjs";import{emitApp as Le}from"./packem_shared/emitApp-Bc3G4eki.mjs";import{buildOpenApiDocument as Te,emitOpenApi as Pe,emitOpenApiModule as De}from"./packem_shared/buildOpenApiDocument-D6xm3JqM.mjs";import{OPENRPC_VERSION as He,buildOpenRpcDocument as be,emitOpenRpc as We,emitOpenRpcModule as Ge}from"./packem_shared/OPENRPC_VERSION-BPT6vyLU.mjs";import{SCHEMA_SNAPSHOT_FILENAME as Ve,createCodegenProject as ke,refreshCodegenProject as we,runCodegen as ye}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-3_Zzh73G.mjs";import{SchemaSnapshotParseError as Ke,buildSchemaSnapshot as je,evaluateSchemaDrift as qe,parseSchemaSnapshot as Be}from"./packem_shared/SchemaSnapshotParseError-0KRzSjo4.mjs";import{schemaFromIr as Ye}from"./packem_shared/schemaFromIr-R1ZFzVyy.mjs";import{LUNORA_ERROR_CODES as Xe,validatorIrToJsonSchema as Ze}from"./packem_shared/LUNORA_ERROR_CODES-Um9hC1gr.mjs";import{redact as oo,secretKindOf as ro}from"./packem_shared/redact-CQ8-to6l.mjs";import{MESSAGE_SOLUTIONS as so,findSolutionByMessage as ao}from"@lunora/errors";const e="0.0.0";export{l as AGENTS_FILENAME,v as CONTAINERS_FILENAME,c as CodegenDiagnosticError,h as FLAGS_FILENAME,le as GENERATED_HEADER,Xe as LUNORA_ERROR_CODES,so as LUNORA_SOLUTION_RULES,W as MUTATORS_FILENAME,w as NOTIFY_FILENAME,He as OPENRPC_VERSION,B as QUEUES_FILENAME,Ve as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,ie as SHAPES_FILENAME,Ke as SchemaSnapshotParseError,e as VERSION,ce as WORKFLOWS_FILENAME,Te as buildOpenApiDocument,be as buildOpenRpcDocument,je as buildSchemaSnapshot,ke as createCodegenProject,n as diagnosticAt,s as diffSchemaSnapshots,E as discoverAgents,u as discoverAuthApiCalls,N as discoverContainers,R as discoverCrons,C as discoverFlags,_ as discoverFunctions,L as discoverHttpRoutes,T as discoverInserts,D as discoverMaskProcedures,H as discoverMigrations,G as discoverMutators,V as discoverNondeterministicCalls,y as discoverNotifyCalls,z as discoverNotifyConfig,j as discoverQueries,J as discoverQueues,$ as discoverR2sqlCalls,Z as discoverRlsMetadata,ee as discoverRlsProcedures,re as discoverSandboxUsage,se as discoverSchema,me as discoverShapes,pe as discoverStorageRulesMetadata,ne as discoverWorkflows,Ee as emitAgents,xe as emitApi,Le as emitApp,ue as emitCollections,Ae as emitContainers,ve as emitCrons,Ne as emitDataModel,Oe as emitDrizzleSchema,Re as emitFunctions,Pe as emitOpenApi,De as emitOpenApiModule,We as emitOpenRpc,Ge as emitOpenRpcModule,Me as emitServer,he as emitShard,Ce as emitVectors,Ie as emitWorkflows,_e as emitWranglerCronTriggers,qe as evaluateSchemaDrift,ao as findLunoraSolution,m as formatAdvisories,d as lintSchema,Be as parseSchemaSnapshot,oo as redact,we as refreshCodegenProject,ye as runCodegen,Ye as schemaFromIr,ro as secretKindOf,a as serializeSchemaSnapshot,p as toAdvisorContext,Ze as validatorIrToJsonSchema};
@@ -0,0 +1 @@
1
+ import"@lunora/agent/component";import"@lunora/errors";import"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{w as r,n as o,H as n,h as l,b as p,Q as u,c,t as d,l as g,$ as C,G as E,f as S,v as A,r as D,d as f,K as h,u as b}from"./emit-BtiV37rG.mjs";import"./paths-BmX5O1sG.mjs";export{r as GENERATED_HEADER,o as buildStorageColumns,n as emitAgents,l as emitApi,p as emitCollections,u as emitContainers,c as emitCrons,d as emitDataModel,g as emitDrizzleSchema,C as emitFunctions,E as emitQueues,S as emitSeed,A as emitServer,D as emitShard,f as emitVectors,h as emitWorkflows,b as emitWranglerCronTriggers};
@@ -1,3 +1,3 @@
1
- import{w as a}from"./emit-sQzv_a8t.mjs";import{n as s}from"./paths-BmX5O1sG.mjs";import{argsObjectSchema as i,LUNORA_ERROR_CODES as c}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const m="1.3.2",p=()=>({description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."}),u=e=>{const n=s(e.filePath),t=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:c.map((r,o)=>({code:-32e3-o,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:i(e.args)}],result:{name:"result",schema:p()},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},d=e=>{const n=e.version??"0.0.0",t=e.functions.filter(r=>r.visibility!=="internal"&&r.kind!=="stream").map(r=>u(r)).toSorted((r,o)=>r.name.localeCompare(o.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:t,openrpc:m}},R=e=>`${JSON.stringify(d(e),void 0,2)}
1
+ import{w as a}from"./emit-BtiV37rG.mjs";import{n as s}from"./paths-BmX5O1sG.mjs";import{argsObjectSchema as i,LUNORA_ERROR_CODES as c}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const m="1.3.2",p=()=>({description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."}),u=e=>{const n=s(e.filePath),t=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${t}", "args": { … } }\`).`,errors:c.map((r,o)=>({code:-32e3-o,data:{code:r},message:r})),name:t,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:i(e.args)}],result:{name:"result",schema:p()},summary:`${e.kind}: ${t}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},d=e=>{const n=e.version??"0.0.0",t=e.functions.filter(r=>r.visibility!=="internal"&&r.kind!=="stream").map(r=>u(r)).toSorted((r,o)=>r.name.localeCompare(o.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:t,openrpc:m}},R=e=>`${JSON.stringify(d(e),void 0,2)}
2
2
  `,O=e=>`${a}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{m as OPENRPC_VERSION,d as buildOpenRpcDocument,R as emitOpenRpc,O as emitOpenRpcModule};
@@ -0,0 +1,5 @@
1
+ import{existsSync as E,readFileSync as $e,mkdirSync as zt,writeFileSync as qt,rmSync as Bt}from"node:fs";import{join as g,dirname as pe}from"node:path";import{performance as me}from"node:perf_hooks";import{runAdvisor as Vt}from"@lunora/advisor";import{LunoraError as B}from"@lunora/errors";import{Node as i,SyntaxKind as u,Project as Xe}from"ts-morph";import{serializeSchemaSnapshot as Ut}from"./SCHEMA_SNAPSHOT_VERSION-CFhF_hmg.mjs";import{toAdvisorContext as Wt}from"./formatAdvisories-BCEfzLT0.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as f,classifyProcedureCall as K,inlineHandler as Gt,procedureHandler as ft,chainUsesWrappedCall as pt,isDatabaseAccessor as C,chainHasStep as Ht,discoverFunctions as _t}from"./discoverFunctions-DnqHgv0t.mjs";import{discoverAgents as Qt}from"./AGENTS_FILENAME-BesaDYkL.mjs";import{i as w,a as F,e as h,c as S,r as Jt,s as H,b as Xt,d as Zt,E as Yt}from"./discover-queries-LfER8HbK.mjs";import es from"./discoverAuthApiCalls-CEk3J0kc.mjs";import{discoverContainers as ts}from"./CONTAINERS_FILENAME-CFwdyaCI.mjs";import ss from"./discoverCrons-kIgM9ZJC.mjs";import{diagnosticAt as _}from"./CodegenDiagnosticError-DPezpZTz.mjs";import{o as Q}from"./module-specifiers-8FEEiUcv.mjs";import{a as xe,n as rs,t as ns,h as is,v as os,$ as as,r as cs,b as us,Q as ls,K as ds,H as gs,G as fs,c as ps,d as ms,l as xs,f as hs,u as Es}from"./emit-BtiV37rG.mjs";import{discoverFlagKeys as ys}from"./FLAGS_FILENAME-CQDN7BKc.mjs";import $s from"./discoverHttpRoutes-CLn3VDRI.mjs";import As from"./discoverInserts-Cn-CLKET.mjs";import Ss,{discoverMaskStrategies as Ns,discoverMaskMetadata as vs}from"./discoverMaskProcedures-fZtvsy8v.mjs";import bs from"./discoverMigrations-BH_IKdFk.mjs";import{MUTATORS_FILENAME as Ps,isDefineMutatorCallee as ws,discoverMutators as Is}from"./MUTATORS_FILENAME-3Akvs4aT.mjs";import Ls from"./discoverNondeterministicCalls-Cl7qNL0J.mjs";import{discoverNotifyConfig as Os,discoverNotifyCalls as Fs}from"./NOTIFY_FILENAME-B2lXWa7r.mjs";import{discoverQueues as Ts}from"./QUEUES_FILENAME-CSE6i-ld.mjs";import Ds from"./discoverR2sqlCalls-CMNfDWlq.mjs";import Cs,{discoverRlsMetadata as Ks}from"./discoverRlsMetadata-Bf4_2S0t.mjs";import{discoverSandboxUsage as ks}from"./discoverSandboxUsage-Bn1X9COt.mjs";import Rs from"./discoverSchema-Cy4OQ0Cu.mjs";import{secretKindOf as js,redact as Ms}from"./redact-CQ8-to6l.mjs";import{discoverShapes as zs}from"./SHAPES_FILENAME-maut3z1K.mjs";import qs from"./discoverStorageRulesMetadata-CL8J41rX.mjs";import{e as Bs}from"./discover-ast-CezKqEhE.mjs";import{discoverWorkflows as Vs}from"./WORKFLOWS_FILENAME-Bk5upkGM.mjs";import{emitApp as Us}from"./emitApp-Bc3G4eki.mjs";import{buildOpenApiDocument as Ws,emitOpenApiModule as Gs}from"./buildOpenApiDocument-D6xm3JqM.mjs";import{buildOpenRpcDocument as Hs,emitOpenRpcModule as _s}from"./OPENRPC_VERSION-BPT6vyLU.mjs";import{buildSchemaSnapshot as Qs}from"./SchemaSnapshotParseError-0KRzSjo4.mjs";const mt=new Set(["delete","get","head","options","patch","post","put"]),Js=new Set(["handler","stream"]),Xs=/\/(?:_|admin|internal|superuser|sudo|root|debug)/iu,Ze=new Set(["ADMIN_TOKEN","adminToken","assertAdmin","assertAuth","auth","Authorization","getSession","identity","isAdmin","requireAdmin","requireAuth","requireRole","verifyAdmin"]),Zs=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!mt.has(t.getName()))return;const s=t.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpRoute")return;const r=e.getArguments()[0];if(!(!r||!i.isStringLiteral(r)))return{method:t.getName().toUpperCase(),path:r.getLiteralValue()}},Ys=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||mt.has(r.getName()))break;s=r.getExpression()}return Zs(s)},er=e=>{for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression))if(Ze.has(t.getName()))return!0;for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&Ze.has(s.getText()))return!0}return!1},tr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=s.getExpression();if(!i.isPropertyAccessExpression(r)||!Js.has(r.getName()))return;const n=Ys(s);if(!n||!Xs.test(n.path))return;const o=s.getArguments()[0],a=o!==void 0&&(i.isArrowFunction(o)||i.isFunctionExpression(o))&&er(o);return{exportName:e.getName(),file:t,method:n.method,path:n.path,usesGuard:a}},sr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=tr(n,t);o&&s.push(o)}return s},rr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...sr(n,f(t,r)))}return s},nr=e=>!i.isPropertyAccessExpression(e)||e.getName()!=="run"?!1:e.getExpression().getText()==="ctx.ai",ir=(e,t)=>{if(!nr(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)||F(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},or=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=ir(r,t);n&&s.push(n)}return s},ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...or(n,f(t,r)))}return s},cr=new Set(["generateText","streamText"]),ur=new Set(["messages","prompt","system"]),lr=[{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"]}],dr=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t))return;const s=t.getName(),r=t.getExpression().getText();for(const n of lr)if(n.methods.has(s)&&n.prefixes.some(o=>r===o||r.startsWith(`${o}.`)))return`${r}.${s}`},gr=e=>{for(const t of e.getDescendantsOfKind(u.CallExpression)){const s=dr(t);if(s!==void 0)return s}},fr=e=>{const t=new Set,s=e.getFirstAncestor(o=>i.isArrowFunction(o)||i.isFunctionExpression(o)||i.isFunctionDeclaration(o)),[r]=s?.getParameters()??[],n=r?.getNameNode();if(n===void 0||!i.isObjectBindingPattern(n))return t;for(const o of n.getElements()){const a=o.getPropertyNameNode()?.getText()??o.getName(),c=o.getNameNode();if(a==="args"&&i.isObjectBindingPattern(c))for(const l of c.getElements())t.add(l.getName())}return t},pr=e=>{if(Jt(e))return!0;const t=fr(e);return t.size===0?!1:e.getDescendantsOfKind(u.Identifier).some(s=>t.has(s.getText()))},mr=e=>{for(const t of e.getProperties()){if(!i.isPropertyAssignment(t)||!ur.has(t.getName()))continue;const s=t.getInitializer();if(s!==void 0&&pr(s))return!0}return!1},xr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!cr.has(n))continue;const[o]=r.getArguments();if(o===void 0||!i.isObjectLiteralExpression(o))continue;let a;for(const c of o.getDescendantsOfKind(u.CallExpression))if(S(c.getExpression())==="tool"&&(a=gr(c),a!==void 0))break;a!==void 0&&s.push({exportName:h(r),file:t,line:r.getStartLineNumber(),method:n,sideEffect:a,userInputDerived:mr(o)})}return s},hr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...xr(n,f(t,r)))}return s},Er=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="fetch")return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="ctx"},yr=(e,t)=>{if(!Er(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!w(s)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},$r=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=yr(r,t);n&&s.push(n)}return s},Ar=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...$r(n,f(t,r)))}return s},xt=e=>e.getProperties().some(t=>i.isSpreadAssignment(t)),Sr=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return{objects:[],opaque:!0};const s=t.getProperty("args");if(!s)return{objects:[],opaque:!1};if(!i.isPropertyAssignment(s))return{objects:[],opaque:!0};const r=s.getInitializer();return!r||!i.isObjectLiteralExpression(r)?{objects:[],opaque:!0}:{objects:[r],opaque:xt(r)}},Nr=e=>{const t=[];let s=!1,r=e;for(;i.isCallExpression(r);){const n=r.getExpression();if(!i.isPropertyAccessExpression(n))break;if(n.getName()==="input"){const o=r.getArguments()[0];o&&i.isObjectLiteralExpression(o)?(t.push(o),s||=xt(o)):s=!0}r=n.getExpression()}return{objects:t,opaque:s}},ht=(e,t)=>t?Nr(t):Sr(e),vr=e=>e.flatMap(t=>t.getProperties().filter(s=>i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)).map(s=>s.getName())),br=/\.check\(|\.meta\(|length|max/iu,Pr=/\bv\.any\s*\(/u,wr=/\bv\.string\s*\(/u,Ir=e=>Pr.test(e),Lr=e=>wr.test(e)&&!br.test(e),Or=e=>{const t=[],s=[];for(const r of e)for(const n of r.getProperties()){if(!i.isPropertyAssignment(n))continue;const o=n.getInitializer();if(!o)continue;const a=o.getText(),c=n.getName();Ir(a)?t.push(c):Lr(a)&&s.push(c)}return{anyArgs:t,unboundedStringArgs:s}},Fr=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(r?.visibility!=="public")return;const{objects:n}=ht(s,r.receiver),{anyArgs:o,unboundedStringArgs:a}=Or(n);if(!(o.length===0&&a.length===0))return{anyArgs:o,exportName:e.getName(),file:t,line:s.getStartLineNumber(),unboundedStringArgs:a}},Tr=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Fr(n,t);o&&s.push(o)}return s},Dr=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Tr(n,f(t,r)))}return s},N=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},he=e=>e?.getKind()===u.TrueKeyword,Cr=e=>e?.getKind()===u.FalseKeyword,Kr=e=>e!==void 0&&i.isNumericLiteral(e)&&e.getLiteralValue()===0,kr=new Set(["lunoraAuthAdapter","lunoraD1Adapter"]),Rr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isCallExpression(t)&&S(t.getExpression())==="scim"),jr=e=>e!==void 0&&i.isCallExpression(e)&&kr.has(S(e.getExpression())??""),Mr=e=>!e||!i.isArrayLiteralExpression(e)?!1:e.getElements().some(t=>i.isStringLiteral(t)&&t.getLiteralText()==="*"),zr=e=>{const t=N(e,"advanced"),s=N(e,"emailAndPassword"),r=N(e,"session");return{analyzable:!0,disableCsrfCheck:he(N(t,"disableCSRFCheck")),emailPasswordEnabled:he(N(s,"enabled")),requireEmailVerification:he(N(s,"requireEmailVerification")),scimOnNonTransactionalAdapter:Rr(N(e,"plugins"))&&jr(N(e,"database")),secureCookiesDisabled:Cr(N(t,"useSecureCookies")),sessionFreshAgeZero:Kr(N(r,"freshAge")),trustedOriginsWildcard:Mr(N(e,"trustedOrigins"))}},qr=()=>({analyzable:!1,disableCsrfCheck:!1,emailPasswordEnabled:!1,requireEmailVerification:!1,scimOnNonTransactionalAdapter:!1,secureCookiesDisabled:!1,sessionFreshAgeZero:!1,trustedOriginsWildcard:!1}),Br=(e,t)=>{if(S(e.getExpression())!=="createAuth")return;const s=e.getArguments()[0],r=s!==void 0&&i.isObjectLiteralExpression(s)&&s.getProperties().some(o=>i.isSpreadAssignment(o)),n=s!==void 0&&i.isObjectLiteralExpression(s)&&!r?zr(s):qr();return{exportName:h(e),file:t,line:e.getStartLineNumber(),...n}},Vr=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Br(r,t);n&&s.push(n)}return s},Ur=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Vr(n,f(t,r)))}return s},Wr=(e,t)=>{if(!i.isPropertyAccessExpression(e))return;const s=e.getName();if(t.methods.has(s))return t.matchReceiver(e.getExpression().getText())?s:void 0},Gr=(e,t,s)=>{const r=Wr(e.getExpression(),s);if(r===void 0)return;const n=e.getArguments()[s.argIndex];if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:r}},Hr=(e,t,s)=>{const r=[];for(const n of e.getDescendantsOfKind(u.CallExpression)){const o=Gr(n,t,s);o&&r.push(o)}return r},J=(e,t,s)=>{const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...Hr(o,f(t,n),s))}return r},_r=new Set(["content","pdf","scrape","screenshot"]),Qr=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.browser",methods:_r}),Jr=new Set(["createBrowser","createInboundEmailHandler","createPayment"]),Xr=new Set(["RateLimiter"]),Zr=new Set(["extend"]),Et=e=>{const t=[],s=[];let r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),n.getInitializer()?.getKind()===u.TrueKeyword&&s.push(o);continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,presentKeys:t,trueKeys:s}},Ye=e=>e&&i.isObjectLiteralExpression(e)?Et(e):{analyzable:!1,presentKeys:[],trueKeys:[]},Yr=e=>{const t=e.getStatements(),[s]=t;if(t.length!==1||s===void 0||!i.isReturnStatement(s))return;const r=s.getExpression();return r!==void 0&&i.isObjectLiteralExpression(r)?r:void 0},en=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isParenthesizedExpression(e)){const t=e.getExpression();return i.isObjectLiteralExpression(t)?t:void 0}return i.isBlock(e)?Yr(e):void 0},tn=e=>{const t=e&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,s=t&&en(t.getBody());return s?Et(s):{analyzable:!1,presentKeys:[],trueKeys:[]}},sn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());n!==void 0&&(Jr.has(n)?s.push({callee:n,file:t,line:r.getStartLineNumber(),...Ye(r.getArguments()[0])}):Zr.has(n)&&s.push({callee:n,file:t,line:r.getStartLineNumber(),...tn(r.getArguments()[0])}))}for(const r of e.getDescendantsOfKind(u.NewExpression)){const n=S(r.getExpression());n===void 0||!Xr.has(n)||s.push({callee:n,file:t,line:r.getStartLineNumber(),...Ye(r.getArguments()[0])})}return s},rn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...sn(n,f(t,r)))}return s},et="ctx.containers.",nn=e=>{if(!e.startsWith(et))return!1;const t=e.slice(et.length);return t.length>0&&!t.includes(".")},on=(e,t)=>J(e,t,{argIndex:0,matchReceiver:nn,methods:new Set(["get"])}),an=new Set(["allow","deny","setAllowed"]),cn=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return!1;const s=t.getProperty("enableInternet");return s!==void 0&&i.isPropertyAssignment(s)&&i.isTrueLiteral(s.getInitializerOrThrow())},un=(e,t)=>{const s=e.getExpression();if(!(!i.isPropertyAccessExpression(s)||s.getName()!=="start"||!cn(e)))return{detail:"enableInternet: true",exportName:h(e),file:t,kind:"enable_internet",line:e.getStartLineNumber()}},ln=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||!an.has(s.getName()))return;const r=s.getExpression();if(!(!i.isPropertyAccessExpression(r)||r.getName()!=="egress"))return{detail:s.getName(),exportName:h(e),file:t,kind:"egress_relaxation",line:e.getStartLineNumber()}},dn=(e,t)=>un(e,t)??ln(e,t),gn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=dn(r,t);n&&s.push(n)}return s},fn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...gn(n,f(t,r)))}return s},pn="env.ts",mn=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineEnv";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineEnv":!1;return!1},xn=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},hn=e=>{if(i.isIdentifier(e))return mn(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineEnv"&&i.isIdentifier(t)&&xn(t)}return!1},En=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!hn(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineEnv exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},yn=(e,t)=>{const s=g(t,pn);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=En(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/env.ts declares ${n.length.toString()} defineEnv() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},$n=new Set(["defineExportSink","r2Sink","webhookExportSink"]),An=e=>{const t=e.getExpression();if(!i.isIdentifier(t))return;const s=t.getText();return $n.has(s)?s:void 0},Sn=e=>{const t=[],s=[];for(const r of e.getProperties()){if(i.isSpreadAssignment(r))return{analyzable:!1,emptyKeys:[],presentKeys:[]};if(i.isPropertyAssignment(r)){const n=r.getName();t.push(n);const o=r.getInitializer();o&&i.isStringLiteral(o)&&o.getLiteralText()===""&&s.push(n);continue}(i.isShorthandPropertyAssignment(r)||i.isMethodDeclaration(r)||i.isGetAccessorDeclaration(r))&&t.push(r.getName())}return{analyzable:!0,emptyKeys:s,presentKeys:t}},Nn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){const c=An(a);if(c===void 0)continue;const l=a.getArguments()[0],p=l&&i.isObjectLiteralExpression(l)?Sn(l):{analyzable:!1,emptyKeys:[],presentKeys:[]};s.push({analyzable:p.analyzable,emptyKeys:p.emptyKeys,factory:c,file:o,line:a.getStartLineNumber(),presentKeys:p.presentKeys})}}return s},vn=new Map([["dbRateLimit",2],["rateLimit",2],["verifyTurnstileMiddleware",0]]),bn=new Set(["dbRateLimit","rateLimit"]),Pn=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=e.getProperty("failOpen");return t!==void 0&&i.isPropertyAssignment(t)&&t.getInitializer()?.getKind()===u.TrueKeyword},wn=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},In=(e,t)=>{const s=S(e.getExpression());if(s===void 0)return;const r=vn.get(s);if(r!==void 0)return{callee:s,exportName:h(e),failOpen:Pn(e.getArguments()[r]),file:t,limitName:bn.has(s)?wn(e):"",line:e.getStartLineNumber()}},Ln=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=In(r,t);n&&s.push(n)}return s},On=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ln(n,f(t,r)))}return s},Fn=e=>{const t=r=>i.isIdentifier(r)&&r.getText()==="ctx",s=new Set;for(const r of e.getDescendantsOfKind(u.PropertyAccessExpression))t(r.getExpression())&&s.add(r.getName());for(const r of e.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getInitializer(),o=r.getNameNode();if(!(n===void 0||!t(n)||!i.isObjectBindingPattern(o)))for(const a of o.getElements()){const c=a.getPropertyNameNode()?.getText()??a.getName();c&&s.add(c)}}return s},Tn=(e,t)=>{const s=Object.fromEntries(xe.map(r=>[r.key,!1]));for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=new Set(n.getImportDeclarations().map(c=>c.getModuleSpecifierValue())),a=Fn(n);for(const c of xe)if(!s[c.key]){if(o.has(c.moduleSpecifier)){s[c.key]=!0;continue}c.contextProperty!==void 0&&a.has(c.contextProperty)&&(s[c.key]=!0)}if(xe.every(c=>s[c.key]))break}return s},Dn=["providerSubscriptionId","state"],Cn=["providerEventId","processedAt"],tt=(e,t)=>t.every(s=>s in e.shape),Kn=e=>{const t=e.find(r=>r.name==="subscriptions"),s=e.find(r=>r.name==="events");return t!==void 0&&s!==void 0&&tt(t,Dn)&&tt(s,Cn)},kn=(e,t)=>({analytics:e.analytics||t.dependencies.has("@lunora/bindings/analytics"),auth:t.dependencies.has("@lunora/auth"),containers:e.container||t.containerCount>0||t.dependencies.has("@lunora/container"),flags:e.flags||t.dependencies.has("@lunora/flags"),kv:e.kv||t.dependencies.has("@lunora/bindings/kv"),mail:e.mail||t.dependencies.has("@lunora/mail"),notifications:e.notify||t.dependencies.has("@lunora/notify"),payments:e.payments||t.hasPaymentTables,queues:t.queueCount>0||t.dependencies.has("@lunora/queue"),scheduler:e.scheduler||t.cronCount>0||t.dependencies.has("@lunora/scheduler"),storage:e.storage||t.storageRuleCount>0||t.storageColumnCount>0||t.dependencies.has("@lunora/storage"),vectors:e.vectors||t.vectorIndexCount>0||t.dependencies.has("@lunora/bindings/vectors"),workflows:e.workflows||t.workflowCount>0||t.dependencies.has("@lunora/workflow")}),Rn=e=>i.isIdentifier(e)&&e.getText()==="ctx",jn=e=>{if(!i.isPropertyAccessExpression(e)||e.getName()!=="boolean")return!1;const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="flags"&&Rn(t.getExpression())},Mn=e=>{if(e?.getKind()===u.TrueKeyword)return!0;if(e?.getKind()===u.FalseKeyword)return!1},zn=(e,t)=>{if(!jn(e.getExpression()))return;const[s,r]=e.getArguments();if(!s||!(i.isStringLiteral(s)||i.isNoSubstitutionTemplateLiteral(s)))return;const n=s.getLiteralValue(),o=Mn(r);if(!(n.length===0||o===void 0))return{defaultValue:o,exportName:h(e),file:t,key:n,line:e.getStartLineNumber()}},qn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=zn(r,t);n&&s.push(n)}return s},Bn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...qn(n,f(t,r)))}return s},Vn=e=>{const t=e.getExpression();return i.isPropertyAccessExpression(t)&&t.getName()==="withGeoIndex"},Un=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},Wn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression))Vn(a)&&s.push({file:o,indexName:Un(a),line:a.getStartLineNumber()})}return s},Gn=new Set(["delete","get","head","options","patch","post","put"]),Hn=new Set(["handler","stream"]),_n=new Set(["runAction","runMutation"]),Qn=new Set(["delete","insert","insertManyUnsafe","patch","replace"]),U=(e,t)=>e!==void 0&&i.isIdentifier(e)&&e.getText()===t,st=e=>e!==void 0&&(i.isArrowFunction(e)||i.isFunctionExpression(e))?e:void 0,rt=(e,t)=>{const s=e.getParameters()[0];if(s===void 0)return;const r=s.getNameNode();if(t)return i.isIdentifier(r)?r.getText():void 0;if(i.isObjectBindingPattern(r)){for(const n of r.getElements())if((n.getPropertyNameNode()?.getText()??n.getNameNode().getText())==="ctx"){const o=n.getNameNode();return i.isIdentifier(o)?o.getText():void 0}}},nt=(e,t)=>{const s=e.getBody(),r=s.getDescendantsOfKind(u.CallExpression);i.isCallExpression(s)&&r.unshift(s);for(const n of r){const o=n.getExpression();if(!i.isPropertyAccessExpression(o))continue;const a=o.getName(),c=o.getExpression();if(_n.has(a)&&U(c,t))return a;if(Qn.has(a)&&i.isPropertyAccessExpression(c)&&c.getName()==="db"&&U(c.getExpression(),t))return`db.${a}`}},it=(e,t)=>{const s=e.getBody();for(const r of s.getDescendantsOfKind(u.PropertyAccessExpression))if(r.getName()==="auth"&&U(r.getExpression(),t))return!0;for(const r of s.getDescendantsOfKind(u.VariableDeclaration)){const n=r.getNameNode();if(!(!i.isObjectBindingPattern(n)||!U(r.getInitializer(),t))){for(const o of n.getElements())if((o.getPropertyNameNode()?.getText()??o.getNameNode().getText())==="auth")return!0}}return!1},Jn=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!Hn.has(t.getName()))return;let s=t.getExpression();for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))return;const n=r.getName();if(Gn.has(n)){const o=r.getExpression();return i.isIdentifier(o)&&o.getText()==="httpRoute"?n.toUpperCase():void 0}s=r.getExpression()}},Xn=(e,t)=>{const s=e.getExpression();if(i.isIdentifier(s)&&s.getText()==="httpAction"){const c=st(e.getArguments()[0]),l=c&&rt(c,!0);if(!c||l===void 0)return;const p=nt(c,l);return p===void 0?void 0:{exportName:h(e),file:t,kind:"httpAction",line:e.getStartLineNumber(),readsAuth:it(c,l),sideEffect:p}}const r=Jn(e);if(r===void 0)return;const n=st(e.getArguments()[0]),o=n&&rt(n,!1);if(!n||o===void 0)return;const a=nt(n,o);return a===void 0?void 0:{exportName:h(e),file:t,kind:"httpRoute",line:e.getStartLineNumber(),method:r,readsAuth:it(n,o),sideEffect:a}},Zn=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Xn(r,t);n&&s.push(n)}return s},Yn=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Zn(n,f(t,r)))}return s},ei=new Set(["btoa","encodeURI","encodeURIComponent","isSafeHeaderValue","Number","parseFloat","parseInt"]),ti=new Set(["append","set"]),Ae=e=>i.isIdentifier(e)?e.getText():i.isPropertyAccessExpression(e)?e.getName():"",yt=e=>e!==void 0&&(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))?e.getLiteralText():"",ot=(e,t)=>(i.isCallExpression(e)?[e,...e.getDescendantsOfKind(u.CallExpression)]:e.getDescendantsOfKind(u.CallExpression)).some(s=>ei.has(Ae(s.getExpression()))&&Zt(s,t)),si=(e,t)=>{if(ot(e,t))return!0;const s=H(e);return s!==void 0&&ot(s,t)},ye=(e,t)=>Xt(e,t)&&!si(e,t),ri=e=>{if(i.isPropertyAccessExpression(e)&&e.getName()==="headers")return!0;const t=H(e);return t!==void 0&&i.isNewExpression(t)&&Ae(t.getExpression())==="Headers"},W=e=>{if(e===void 0)return;if(i.isObjectLiteralExpression(e))return e;const t=H(e);return t!==void 0&&i.isObjectLiteralExpression(t)?t:void 0},Se=(e,t,s)=>{for(const r of e.getProperties())if(i.isPropertyAssignment(r)){const n=r.getInitializer();n!==void 0&&ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:yt(r.getNameNode()),line:n.getStartLineNumber(),via:t})}else if(i.isShorthandPropertyAssignment(r)){const n=r.getNameNode();ye(n,s.requestName)&&s.rows.push({exportName:s.exportName,file:s.relativePath,headerName:r.getName(),line:n.getStartLineNumber(),via:t})}else if(i.isSpreadAssignment(r)){const n=W(r.getExpression());n!==void 0&&Se(n,t,s)}},$t=(e,t)=>{const s=W(e);if(s===void 0)return;const r=s.getProperty("headers");if(r===void 0||!i.isPropertyAssignment(r))return;const n=W(r.getInitializer());n!==void 0&&Se(n,"response-init",t)},ni=(e,t)=>{const s=Ae(e.getExpression());if(s==="Response")$t(e.getArguments()[1],t);else if(s==="Headers"){const r=W(e.getArguments()[0]);r!==void 0&&Se(r,"headers-ctor",t)}},ii=(e,t)=>{const s=e.getExpression();if(!i.isPropertyAccessExpression(s))return;const r=s.getName(),n=s.getExpression();if(r==="json"&&i.isIdentifier(n)&&n.getText()==="Response"){$t(e.getArguments()[1],t);return}if(ti.has(r)&&ri(n)){const o=e.getArguments()[1];o!==void 0&&ye(o,t.requestName)&&t.rows.push({exportName:t.exportName,file:t.relativePath,headerName:yt(e.getArguments()[0]),line:o.getStartLineNumber(),via:r==="set"?"headers-set":"headers-append"})}},oi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.NewExpression))ni(s,t);for(const s of e.getDescendantsOfKind(u.CallExpression))ii(s,t)},ai=(e,t)=>{const s=e.getExpression();if(!i.isIdentifier(s)||s.getText()!=="httpAction")return[];const r=Gt(e.getArguments()[0]);if(r===void 0)return[];const n=r.getParameters()[1];if(n===void 0)return[];const o=n.getNameNode();if(!i.isIdentifier(o))return[];const a=[];return oi(r,{exportName:h(e),relativePath:t,requestName:o.getText(),rows:a}),a},ci=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...ai(r,t));return s},ui=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ci(n,f(t,r)))}return s},At="identity.ts",li=e=>{const t=e.getSymbol();if(!t)return e.getText()==="defineIdentity";for(const s of t.getDeclarations())if(i.isImportSpecifier(s))return Q(s.getImportDeclaration().getModuleSpecifierValue())?s.getNameNode().getText()==="defineIdentity":!1;return!1},di=e=>{const t=e.getSymbol();if(!t)return!1;for(const s of t.getDeclarations()){if(!i.isNamespaceImport(s))continue;const r=s.getFirstAncestorByKind(u.ImportDeclaration);return r!==void 0&&Q(r.getModuleSpecifierValue())}return!1},gi=e=>{if(i.isIdentifier(e))return li(e);if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return e.getName()==="defineIdentity"&&i.isIdentifier(t)&&di(t)}return!1},fi=e=>{const t=[];for(const s of e.getVariableDeclarations()){if(!s.isExported())continue;const r=s.getInitializer();if(r?.getKind()!==u.CallExpression||!gi(r.getExpression()))continue;const n=s.getNameNode();if(!i.isIdentifier(n))throw _(n,"defineIdentity exports must be plain named exports (no destructuring)");t.push({exportName:n.getText()})}return t},pi=(e,t)=>{const s=g(t,At);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=fi(r);if(n.length!==0){if(n.length>1)throw _(r,`lunora/identity.ts declares ${n.length.toString()} defineIdentity() contracts (${n.map(o=>o.exportName).join(", ")}); exactly one is allowed`);return n[0]}},mi=new Set(["auth","context.auth","ctx.auth"]),xi="userId",hi=e=>{const t=new Set;for(const s of e.getProperties()){if(i.isSpreadAssignment(s))return;(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s))&&t.add(s.getName())}return t},Ei=(e,t)=>{const s=g(t,At);if(!E(s))return;const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);for(const n of r.getDescendantsOfKind(u.CallExpression)){if(S(n.getExpression())!=="defineIdentity")continue;const[o]=n.getArguments();return o&&i.isObjectLiteralExpression(o)?hi(o):void 0}},at=e=>{if(!(e===void 0||!i.isPropertyAccessExpression(e)||e.getName()!=="identity"))return mi.has(e.getExpression().getText())?e:void 0},yi=e=>{if(i.isPropertyAccessExpression(e)&&at(e.getExpression())!==void 0)return e.getName();if(i.isElementAccessExpression(e)&&at(e.getExpression())!==void 0){const t=e.getArgumentExpression();return t&&i.isStringLiteral(t)?t.getLiteralValue():void 0}},$i=(e,t,s)=>{const r=[];for(const n of e.getDescendants()){const o=yi(n);o!==void 0&&r.push({declared:o===xi||s.has(o),exportName:h(n),file:t,key:o,line:n.getStartLineNumber()})}return r},Ai=(e,t)=>{const s=Ei(e,t);if(s===void 0)return[];const r=[];for(const n of d(t)){const o=e.getSourceFile(n)??e.addSourceFileAtPath(n);r.push(...$i(o,f(t,n),s))}return r},Si=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},Ni=(e,t)=>{if(S(e.getExpression())!=="buildImageDeliveryUrl")return;const s=e.getArguments()[0];if(!s)return;const r=Si(s);if(!(!r||!w(r)||F(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber()}},vi=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ni(r,t);n&&s.push(n)}return s},bi=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...vi(n,f(t,r)))}return s},Pi=new Set(["delete","get","getRaw","getWithMetadata","put"]),wi=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.kv"||s.startsWith("ctx.kv."),methods:Pi}),Ii=new Set(["queue","send"]),ct=new Set(["bcc","cc","to"]),Li=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!Ii.has(t))return;const s=e.getExpression().getText();return s==="ctx.mail"||s==="ctx.email"?t:void 0},Oi=e=>i.isObjectLiteralExpression(e)?e.getProperties().some(t=>{if(i.isShorthandPropertyAssignment(t)){const r=t.getNameNode();return ct.has(t.getName())&&w(r)&&!F(r)}if(!i.isPropertyAssignment(t)||!ct.has(t.getName()))return!1;const s=t.getInitializer();return s!==void 0&&w(s)&&!F(s)}):!1,Fi=(e,t)=>{const s=Li(e.getExpression());if(s===void 0)return;const r=e.getArguments()[0];if(!(!r||!Oi(r)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},Ti=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Fi(r,t);n&&s.push(n)}return s},Di=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ti(n,f(t,r)))}return s},Ci=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="replace")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Ki=e=>{const t=e.getArguments()[0];if(t===void 0||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("server");if(s!==void 0)return i.isPropertyAssignment(s)?s.getInitializer():s},ki=e=>{if(!e.isExported())return;const t=e.getInitializer();if(t?.getKind()!==u.CallExpression)return;const s=t;return ws(s.getExpression())?s:void 0},Ri=e=>{const t=ki(e),s=t===void 0?void 0:Ki(t);if(s===void 0)return[];const r=e.getNameNode(),n=i.isIdentifier(r)?r.getText():"";return s.getDescendantsOfKind(u.CallExpression).filter(o=>Ci(o)).map(o=>({exportName:n,file:"lunora/mutators.ts",line:o.getStartLineNumber()}))},ji=e=>e.getVariableDeclarations().flatMap(t=>Ri(t)),Mi=(e,t)=>{const s=g(t,Ps);if(!E(s))return[];const r=e.getSourceFile(s)??e.addSourceFileAtPath(s);return ji(r)},zi=new Set(["delete","get","patch"]),qi=new Set(["accountId","authorId","companyId","createdBy","createdById","customerId","groupId","memberId","organizationId","orgId","ownerId","projectId","teamId","tenantId","userId","workspaceId"]),Bi=new Set(["auth","identity","session","user"]),Vi=new Set([u.EqualsEqualsEqualsToken,u.EqualsEqualsToken,u.ExclamationEqualsEqualsToken,u.ExclamationEqualsToken]),Ui=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="normalizeId"||!C(t.getExpression()))return;const s=e.getArguments()[0];return s&&i.isStringLiteral(s)?s.getLiteralText():""},Wi=e=>{let t=e,s=t.getParent();for(;s!==void 0&&(i.isAsExpression(s)||i.isParenthesizedExpression(s)||i.isNonNullExpression(s));)t=s,s=t.getParent();if(s===void 0||!i.isVariableDeclaration(s))return;const r=s.getNameNode();return i.isIdentifier(r)?r.getText():void 0},Gi=(e,t)=>e.getDescendantsOfKind(u.Identifier).some(s=>s.getText()===t),Hi=e=>i.isThrowStatement(e)||i.isReturnStatement(e)||e.getDescendantsOfKind(u.ThrowStatement).length>0||e.getDescendantsOfKind(u.ReturnStatement).length>0,_i=(e,t)=>e.getDescendantsOfKind(u.IfStatement).some(s=>Gi(s.getExpression(),t)&&Hi(s.getThenStatement())),Qi=(e,t)=>{for(const s of e.getDescendantsOfKind(u.CallExpression)){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))continue;const n=r.getName();if(!zi.has(n))continue;const o=r.getExpression();if(!(C(o)||i.isPropertyAccessExpression(o)&&C(o.getExpression())))continue;const a=s.getArguments()[0];if(a!==void 0&&i.isIdentifier(a)&&a.getText()===t)return n}},Ji=e=>{let t=e;for(;i.isPropertyAccessExpression(t)||i.isElementAccessExpression(t)||i.isNonNullExpression(t)||i.isParenthesizedExpression(t)||i.isAsExpression(t)||i.isAwaitExpression(t);)t=t.getExpression();return i.isIdentifier(t)?t.getText():void 0},Xi=e=>e.getDescendantsOfKind(u.CallExpression).some(t=>t.getArguments().some(s=>Ji(s)==="ctx")),Zi=e=>e.getDescendantsOfKind(u.BinaryExpression).some(t=>Vi.has(t.getOperatorToken().getKind())?i.isPropertyAccessExpression(t.getLeft())||i.isPropertyAccessExpression(t.getRight()):!1),Yi=e=>{for(const t of e.getDescendantsOfKind(u.Identifier))if(qi.has(t.getText()))return!0;for(const t of e.getDescendantsOfKind(u.PropertyAccessExpression)){const s=t.getExpression();if(i.isIdentifier(s)&&s.getText()==="ctx"&&Bi.has(t.getName()))return!0}return Xi(e)||Zi(e)},eo=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query"&&r?.kind!=="mutation")return[];const n=ft(s);if(n===void 0)return[];const o=r.receiver!==void 0&&pt(r.receiver,"use","rls"),a=Yi(n),c=new Set,l=[];for(const p of n.getDescendantsOfKind(u.CallExpression)){const y=Ui(p);if(y===void 0)continue;const I=Wi(p);if(I===void 0||c.has(I)||!_i(n,I))continue;const k=Qi(n,I);k!==void 0&&(c.add(I),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),mentionsOwnership:a,sinkMethod:k,table:y,usesRls:o,visibility:r.visibility}))}return l},to=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...eo(c,o))}return s},so=new Set(["accountId","authorId","createdBy","createdById","organizationId","orgId","ownerId","tenantId","updatedBy","userId","workspaceId"]),ro=new Set(["insert","insertManyUnsafe","patch","replace"]),no=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(!ro.has(t))return;const s=e.getExpression();if(!i.isPropertyAccessExpression(s)||s.getName()!=="db")return;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"?t:void 0},io=(e,t)=>{if(t!=="insertManyUnsafe")return i.isObjectLiteralExpression(e)?[e]:[];if(!i.isArrayLiteralExpression(e))return[];const s=[];for(const r of e.getElements())i.isObjectLiteralExpression(r)&&s.push(r);return s},oo=(e,t,s,r)=>{const n=[];for(const o of e.getProperties()){let a,c;i.isPropertyAssignment(o)?(a=o.getName(),c=o.getInitializer()):i.isShorthandPropertyAssignment(o)&&(a=o.getName(),c=o.getNameNode()),!(a===void 0||c===void 0||!so.has(a))&&w(c)&&!F(c)&&n.push({exportName:h(s),field:a,file:r,line:s.getStartLineNumber(),method:t})}return n},ao=(e,t)=>{const s=no(e.getExpression());if(s===void 0)return[];const r=e.getArguments()[1];return r?io(r,s).flatMap(n=>oo(n,s,e,t)):[]},co=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression))s.push(...ao(r,t));return s},uo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...co(n,f(t,r)))}return s},lo=e=>{const t=g(e,"package.json");if(!E(t))return new Set;try{const s=JSON.parse($e(t,"utf8")),r=new Set;for(const n of["dependencies","devDependencies","peerDependencies","optionalDependencies"]){const o=s[n];if(o!==null&&typeof o=="object")for(const a of Object.keys(o))r.add(a)}return r}catch{return new Set}},go=new Set(["createAutumnAdapter","createDodoPaymentsAdapter","createPolarAdapter","createStripeAdapter"]),fo=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,po=e=>{const t=e.getProperty("webhookToleranceSeconds");return t&&i.isPropertyAssignment(t)?fo(t.getInitializer()):void 0},mo=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=S(r.getExpression());if(n===void 0||!go.has(n))continue;const[o]=r.getArguments(),a=o&&i.isObjectLiteralExpression(o)?po(o):void 0;s.push({callee:n,exportName:h(r),file:t,line:r.getStartLineNumber(),...a===void 0?{}:{toleranceSeconds:a}})}return s},xo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...mo(n,f(t,r)))}return s},ho=new Set(["defineQueue","defineWorkflow"]),Eo=new Set(["run","runAction","runMutation","runQuery"]),yo=new Set(["api","internal"]),$o=e=>{const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0},Ao=e=>{const t=e.getArguments()[0];if(!t||!i.isObjectLiteralExpression(t))return;const s=t.getProperty("handler");if(s===void 0||!i.isPropertyAssignment(s))return;const r=s.getInitializer();if(r&&(i.isArrowFunction(r)||i.isFunctionExpression(r)))return r},St=(e,t)=>{const s=e.getParameters()[t]?.getNameNode();return s&&i.isIdentifier(s)?s.getText():void 0},Nt=(e,t)=>e===t||e.startsWith(`${t}.`),vt=e=>{const t=e.getDescendantsOfKind(u.PropertyAccessExpression);return i.isPropertyAccessExpression(e)&&t.push(e),t},ut=e=>{const t=e.getParent();return i.isPropertyAccessExpression(t)&&t.getNameNode()===e||i.isPropertyAssignment(t)&&t.getNameNode()===e?!1:!(i.isBindingElement(t)&&t.getNameNode()===e)},bt=e=>{const t=e.getDescendantsOfKind(u.Identifier).filter(s=>ut(s));return i.isIdentifier(e)&&ut(e)&&t.push(e),t},So=e=>{if(!i.isVariableDeclaration(e))return[];const t=e.getNameNode();return i.isIdentifier(t)?[t.getText()]:t.getDescendantsOfKind(u.BindingElement).map(s=>s.getName())},No=e=>{const t=St(e,1);if(t===void 0)return[];const s=[`${t}.messages`];for(const r of e.getDescendantsOfKind(u.ForOfStatement)){if(r.getExpression().getText()!==`${t}.messages`)continue;const n=r.getInitializer(),o=i.isVariableDeclarationList(n)?n.getDeclarations()[0]?.getNameNode():void 0;o&&i.isIdentifier(o)&&s.push(`${o.getText()}.body`)}return s},vo=(e,t,s)=>{const r=t==="workflow"?[`${s}.params`]:No(e),n=new Set,o=a=>vt(a).some(c=>r.some(l=>Nt(c.getText(),l)))?!0:bt(a).some(c=>n.has(c.getText()));for(const a of e.getDescendantsOfKind(u.VariableDeclaration)){const c=a.getInitializer();if(c&&o(c))for(const l of So(a))n.add(l)}return{names:n,prefixes:r}},bo=(e,t)=>vt(e).some(s=>t.prefixes.some(r=>Nt(s.getText(),r)))?!0:bt(e).some(s=>t.names.has(s.getText())),Po=e=>{if(e===void 0||!i.isPropertyAccessExpression(e))return;const t=[];let s=e;for(;i.isPropertyAccessExpression(s);)t.unshift(s.getName()),s=s.getExpression();const r=t.at(-1);if(!(r===void 0||!i.isIdentifier(s)||!yo.has(s.getText())||t.length<2))return{exportName:r,file:t.slice(0,-1).join("/")}},wo=(e,t,s)=>{const r=St(e,0);if(r===void 0)return[];const n=vo(e,t,r),o=[];for(const a of e.getDescendantsOfKind(u.CallExpression)){const c=a.getExpression();if(!i.isPropertyAccessExpression(c)||!Eo.has(c.getName())||c.getExpression().getText()!==r)continue;const l=a.getArguments()[1];if(!l||!bo(l,n))continue;const p=Po(a.getArguments()[0]);p!==void 0&&o.push({dispatchKind:t,file:s,handlerExport:h(a),line:a.getStartLineNumber(),targetExport:p.exportName,targetFile:p.file})}return o},Io=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=$o(r);if(n===void 0||!ho.has(n))continue;const o=Ao(r);o!==void 0&&s.push(...wo(o,n==="defineQueue"?"queue":"workflow",t))}return s},Lo=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Io(n,f(t,r)))}return s},lt={dbRateLimit:"usesRateLimit",emailGateMiddleware:"usesEmailGate",mask:"usesMask",rateLimit:"usesRateLimit",rls:"usesRls",verifyTurnstile:"usesCaptcha",verifyTurnstileMiddleware:"usesCaptcha"},Oo=/account|credential|member|passkey|session|user/iu,Fo=e=>{const t=e.replaceAll(/[^a-z0-9]/giu,"").toLowerCase();return t.endsWith("email")||t.endsWith("emailaddress")},To=(e,t)=>{const{objects:s,opaque:r}=ht(e,t);return vr(s).some(n=>Fo(n))?!0:r?void 0:!1},Ne=e=>{const t=e.getExpression();if(i.isIdentifier(t))return t.getText();if(i.isPropertyAccessExpression(t))return t.getName()},Do=e=>{const t=e.getArguments()[0];return!t||!i.isObjectLiteralExpression(t)?{usesCaptcha:!1,usesRateLimit:!1}:{usesCaptcha:!!t.getProperty("captcha"),usesRateLimit:!!t.getProperty("rateLimit")}},Co=e=>{if(i.isCallExpression(e))return e;if(!i.isIdentifier(e))return;const t=e.getSourceFile().getVariableDeclaration(e.getText())?.getInitializer();return t&&i.isCallExpression(t)?t:void 0},V={usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1},Ko=e=>{const t=Co(e),s=t?Ne(t):void 0;if(t&&s==="protectPublic"){const r=Do(t);return{...V,usesCaptcha:r.usesCaptcha,usesRateLimit:r.usesRateLimit}}return s!==void 0&&s in lt?{...V,[lt[s]]:!0}:V},ko=e=>{const t={...V};let s=e;for(;i.isCallExpression(s);){const r=s.getExpression();if(!i.isPropertyAccessExpression(r))break;const n=r.getName()==="use"?s.getArguments()[0]:void 0;if(n){const o=Ko(n);t.usesCaptcha||=o.usesCaptcha,t.usesEmailGate||=o.usesEmailGate,t.usesMask||=o.usesMask,t.usesRateLimit||=o.usesRateLimit,t.usesRls||=o.usesRls}s=r.getExpression()}return t},Ro=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insert")return!1;const s=t.getExpression();if(!(i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"))return!1;const r=e.getArguments()[0];return!!(r&&i.isStringLiteral(r)&&Oo.test(r.getLiteralText()))},jo=new Set(["create","runAfter","runAt","send","sendBatch"]),Mo=new Set(["queues","scheduler","workflows"]),zo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!jo.has(t.getName()))return!1;let s=t.getExpression();for(;i.isCallExpression(s)||i.isElementAccessExpression(s)||i.isPropertyAccessExpression(s);){if(i.isPropertyAccessExpression(s)&&Mo.has(s.getName())){const r=s.getExpression();if(i.isIdentifier(r)&&r.getText()==="ctx")return!0}s=s.getExpression()}return!1},qo=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="insertManyUnsafe")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="db":i.isIdentifier(s)&&s.getText()==="db"},Pt=new Set(["generateObject","generateText","streamObject","streamText"]),Bo=e=>{const t=Ne(e);return t!==void 0&&Pt.has(t)},Vo=e=>{const t=Ne(e);if(t===void 0||!Pt.has(t))return!1;const s=e.getArguments()[0];return!s||!i.isObjectLiteralExpression(s)||s.getProperties().some(r=>i.isSpreadAssignment(r))?!1:!s.getProperty("maxOutputTokens")},Uo=new Set(["log","span","trace"]),Wo=new Set(["ai"]),Go=new Set(["email","mail"]),Ho=new Set(["ai","browser","fetch","mail","notify","queues","sql","storage","workflows"]),q=(e,t)=>e.getDescendantsOfKind(u.PropertyAccessExpression).some(s=>{if(!t.has(s.getName()))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="ctx"}),_o=e=>e.getDescendantsOfKind(u.ThrowStatement).some(t=>{const s=t.getExpression();if(!i.isNewExpression(s))return!1;const r=s.getExpression();return i.isIdentifier(r)&&r.getText()==="Error"}),dt="lunora-advisor-exempt",Qo=/^[\s*/]+/u,Jo=/[\w-]/u,Xo=e=>{const t=(e.getFirstAncestorByKind(u.VariableStatement)??e).getLeadingCommentRanges().map(s=>s.getText()).join(`
2
+ `);for(const s of t.split(`
3
+ `)){const r=s.replace(Qo,"");if(!r.startsWith(dt))continue;const n=r.slice(dt.length);if(Jo.test(n.charAt(0)))continue;const o=n.indexOf("--");return{exempt:!0,exemptReason:(o===-1?"":n.slice(o+2).split("*")[0]??"").trim()}}return{exempt:!1,exemptReason:""}},Zo=e=>{let t=!1,s=!1,r=!1,n=!1,o=!1;for(const a of e.getDescendantsOfKind(u.CallExpression))if(Ro(a)&&(o=!0),zo(a)&&(t=!0),qo(a)&&(n=!0),Bo(a)&&(s=!0),Vo(a)&&(r=!0),o&&t&&n&&r)break;return{callsMail:q(e,Go),emitsEvent:q(e,Uo),fanOut:t,handlesErrors:e.getDescendantsOfKind(u.TryStatement).length>0,reachesOutbound:q(e,Ho),runsAiGeneration:s||q(e,Wo),throwsBareError:_o(e),unboundedAiGeneration:r,usesInsertManyUnsafe:n,writesUserTable:o}},Yo=(e,t)=>{const s=e.getInitializer();if(!s||!i.isCallExpression(s))return;const r=K(s);if(!r||r.kind!=="query"&&r.kind!=="mutation"&&r.kind!=="action")return;const n=r.receiver?ko(r.receiver):{usesCaptcha:!1,usesEmailGate:!1,usesMask:!1,usesRateLimit:!1,usesRls:!1};return{...Zo(e),...Xo(e),...n,exportName:e.getName(),file:t,hasEmailArg:To(s,r.receiver),kind:r.kind,visibility:r.visibility}},ea=(e,t)=>{const s=[];for(const r of e.getVariableStatements())if(r.isExported())for(const n of r.getDeclarations()){const o=Yo(n,t);o&&s.push(o)}return s},ta=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ea(n,f(t,r)))}return s},sa=new Set(["dbRateLimit","rateLimit"]),ra=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("key");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},na=e=>{const t=e.getArguments()[1];return t&&i.isStringLiteral(t)?t.getLiteralValue():""},ia=e=>i.isArrowFunction(e)?e.getBody():e,oa=(e,t)=>{const s=S(e.getExpression());if(s===void 0||!sa.has(s))return;const r=e.getArguments()[2];if(!r)return;const n=ra(r);if(!n)return;const o=ia(n);if(!(!w(o)||F(o)))return{callee:s,exportName:h(e),file:t,limitName:na(e),line:e.getStartLineNumber()}},aa=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=oa(r,t);n&&s.push(n)}return s},ca=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...aa(n,f(t,r)))}return s},ua=new Set(["findFirst","findFirstOrThrow","findMany","get"]),la=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ua.has(t.getName()))return;const s=t.getExpression();if(C(s)){const r=e.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}if(i.isPropertyAccessExpression(s)&&C(s.getExpression()))return s.getName()},da=e=>{let t=e;for(;i.isCallExpression(t);){const s=t.getExpression();if(!i.isPropertyAccessExpression(s))return;if(s.getName()==="query"&&C(s.getExpression())){const r=t.getArguments()[0];return r&&i.isStringLiteral(r)?r.getLiteralText():""}t=s.getExpression()}},ga=e=>{let t=e;for(;i.isAwaitExpression(t)||i.isParenthesizedExpression(t)||i.isNonNullExpression(t)||i.isAsExpression(t);)t=t.getExpression();return t},wt=(e,t=!1)=>{const s=ga(e);if(i.isIdentifier(s)){if(t)return;const r=H(s);return r===void 0?void 0:wt(r,!0)}if(i.isCallExpression(s))return la(s)??da(s)},fa=e=>{const t=e.getBody();if(!i.isBlock(t))return[t];const s=[];for(const r of e.getDescendantsOfKind(u.ReturnStatement)){const n=r.getFirstAncestor(a=>i.isArrowFunction(a)||i.isFunctionExpression(a)||i.isFunctionDeclaration(a)),o=r.getExpression();n===e&&o!==void 0&&s.push(o)}return s},pa=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer();if(s===void 0||!i.isCallExpression(s))return[];const r=K(s);if(r?.kind!=="query")return[];const n=ft(s);if(n===void 0)return[];const o=r.receiver!==void 0&&Ht(r.receiver,"output"),a=r.receiver!==void 0&&pt(r.receiver,"use","mask"),c=new Set,l=[];for(const p of fa(n)){const y=wt(p);y===void 0||c.has(y)||(c.add(y),l.push({exportName:e.getName(),file:t,line:p.getStartLineNumber(),table:y,usesMask:a,usesOutput:o,visibility:r.visibility}))}return l},ma=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...pa(c,o))}return s},xa=new Set(["findFirst","findFirstOrThrow","findMany"]),ha=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!xa.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},Ea=e=>{if(!e||!i.isObjectLiteralExpression(e))return[];const t=[];for(const s of e.getProperties())(i.isPropertyAssignment(s)||i.isShorthandPropertyAssignment(s)||i.isMethodDeclaration(s)||i.isGetAccessorDeclaration(s))&&t.push(s.getName());return t},ya=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},$a=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=ha(o);if(a===void 0)continue;const c=Ea(ya(a.options,"with"));c.length!==0&&n.push({exportName:e.getName(),file:t,line:o.getStartLineNumber(),parentTable:a.table,relations:c,visibility:r.visibility})}return n},Aa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...$a(c,o))}return s},G=e=>{if(i.isStringLiteral(e)||i.isNoSubstitutionTemplateLiteral(e))return e.getLiteralText();if(i.isBinaryExpression(e)&&e.getOperatorToken().getKind()===u.PlusToken){const t=G(e.getLeft()),s=G(e.getRight());return t!==void 0&&s!==void 0?t+s:void 0}},Sa=e=>{let t=e,s=t.getParent();for(;s!==void 0&&i.isBinaryExpression(s)&&s.getOperatorToken().getKind()===u.PlusToken;)t=s,s=t.getParent();return t!==e&&G(t)!==void 0},Na=(e,t)=>{const s=[],r=[...e.getDescendantsOfKind(u.BinaryExpression),...e.getDescendantsOfKind(u.StringLiteral),...e.getDescendantsOfKind(u.NoSubstitutionTemplateLiteral)],n=new Set;for(const o of r){if(Sa(o))continue;const a=G(o);if(a===void 0)continue;const c=js(a);if(c===void 0)continue;const l=o.getStartLineNumber(),p=`${String(l)}:${c}`;n.has(p)||(n.add(p),s.push({file:t,kind:c,line:l,preview:Ms(a)}))}return s},va=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Na(n,f(t,r)))}return s},ba=new Set(["findFirst","findFirstOrThrow","findMany"]),Pa=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||!ba.has(t.getName()))return;const s=t.getExpression();if(i.isPropertyAccessExpression(s)&&s.getName()==="db"||i.isIdentifier(s)&&s.getText()==="db"){const r=e.getArguments()[0];return{options:e.getArguments()[1],table:r&&i.isStringLiteral(r)?r.getLiteralText():""}}if(i.isPropertyAccessExpression(s)){const r=s.getExpression();if(i.isPropertyAccessExpression(r)&&r.getName()==="db"||i.isIdentifier(r)&&r.getText()==="db")return{options:e.getArguments()[0],table:s.getName()}}},wa=(e,t)=>{if(!e||!i.isObjectLiteralExpression(e))return;const s=e.getProperty(t);return s&&i.isPropertyAssignment(s)?s.getInitializer():void 0},Ia=(e,t)=>{if(!i.isVariableDeclaration(e))return[];const s=e.getInitializer(),r=s&&i.isCallExpression(s)?K(s):void 0;if(!r)return[];const n=[];for(const o of e.getDescendantsOfKind(u.CallExpression)){const a=Pa(o);if(a===void 0)continue;const c=wa(a.options,"includeDeleted");if(c===void 0)continue;const l=i.isTrueLiteral(c),p=!l&&w(c);!l&&!p||n.push({exportName:e.getName(),file:t,fromArgs:p,hardcodedTrue:l,line:o.getStartLineNumber(),table:a.table,visibility:r.visibility})}return n},La=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getVariableStatements())if(a.isExported())for(const c of a.getDeclarations())s.push(...Ia(c,o))}return s},Oa=new Set(["query","unsafe"]),Fa=e=>{if(!i.isPropertyAccessExpression(e)||!Oa.has(e.getName()))return!1;const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="sql")return!1;const s=t.getExpression();return i.isIdentifier(s)&&s.getText()==="ctx"},Ta=e=>i.isBinaryExpression(e)||i.isTemplateExpression(e),Da=e=>e.getFirstAncestorByKind(u.VariableDeclaration)?.getName()??"<module>",Ca=(e,t)=>{if(!Fa(e.getExpression()))return;const s=e.getArguments()[0];if(!(!s||!Ta(s)))return{exportName:Da(e),file:t,line:s.getStartLineNumber()}},Ka=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ca(r,t);n&&s.push(n)}return s},ka=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ka(n,f(t,r)))}return s},Ra=new Set(["createMultipartUpload","delete","download","generateUploadUrl","get","getMetadata","getPresignedUrl","getSignedUrl","getUrl","head","put","resumeMultipartUpload","store","upload"]),ja=(e,t)=>J(e,t,{argIndex:0,matchReceiver:s=>s==="ctx.storage"||s.startsWith("ctx.storage."),methods:Ra}),Ma=new Map([["generateUploadUrl",1],["getPresignedUrl",1],["getSignedUrl",1],["store",2],["upload",2]]),za=e=>e&&i.isNumericLiteral(e)?Number(e.getText()):void 0,qa=e=>{if(e===void 0)return{analyzable:!0,presentKeys:[]};if(!i.isObjectLiteralExpression(e))return{analyzable:!1,presentKeys:[]};const t=[];let s,r=!1;for(const n of e.getProperties()){if(i.isSpreadAssignment(n)){r=!0;continue}if(i.isPropertyAssignment(n)){const o=n.getName();t.push(o),o==="expiresInSeconds"&&(s=za(n.getInitializer()));continue}(i.isShorthandPropertyAssignment(n)||i.isMethodDeclaration(n))&&t.push(n.getName())}return{analyzable:!r,expiresInSeconds:s,presentKeys:t}},Ba=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName(),s=Ma.get(t);if(s===void 0)return;const r=e.getExpression().getText();return r==="ctx.storage"||r.startsWith("ctx.storage.")?{method:t,optionsIndex:s}:void 0},Va=(e,t)=>{const s=Ba(e.getExpression());if(s!==void 0)return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s.method,...qa(e.getArguments()[s.optionsIndex])}},Ua=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Va(r,t);n&&s.push(n)}return s},Wa=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ua(n,f(t,r)))}return s},Ga=new Set(["when","where"]),Ee=new Set(["definePolicy","defineShape"]),Ha=e=>{if(!i.isCallExpression(e))return;const t=e.getExpression();if(i.isPropertyAccessExpression(t)){const r=t.getName();return Ee.has(r)?r:void 0}if(!i.isIdentifier(t))return;for(const r of t.getSymbol()?.getDeclarations()??[])if(i.isImportSpecifier(r)){const n=r.getNameNode().getText();return Ee.has(n)?n:void 0}const s=t.getText();return Ee.has(s)?s:void 0},_a=e=>i.isObjectLiteralExpression(e)&&e.getProperties().length===0,It=e=>{if(e!==void 0){if(i.isReturnStatement(e)&&e.getExpression()===void 0||e.getKind()===u.UndefinedKeyword||e.getText()==="undefined")return"undefined";if(_a(e))return"empty-object";if(i.isParenthesizedExpression(e))return It(e.getExpression())}},Lt=e=>e.getAncestors().find(t=>i.isArrowFunction(t)||i.isFunctionExpression(t)||i.isFunctionDeclaration(t)),Ot=e=>e.getDescendantsOfKind(u.ReturnStatement).filter(t=>Lt(t)===e),Ft=e=>e.getDescendantsOfKind(u.ConditionalExpression).filter(t=>Lt(t)===e),Qa=e=>{const t=Ot(e);return t.length>1?!0:t.some(s=>s.getFirstAncestorByKind(u.IfStatement)!==void 0)||Ft(e).length>0},Ja=e=>{const t=[],s=e.getBody();i.isBlock(s)||t.push(s);for(const r of Ot(e)){const n=i.isReturnStatement(r)?r.getExpression():void 0;t.push(n??r)}for(const r of Ft(e))t.push(r.getWhenTrue(),r.getWhenFalse());return t},Xa=e=>{for(const t of e.getAncestors())if(i.isVariableDeclaration(t)){const s=t.getNameNode();if(i.isIdentifier(s))return s.getText()}return"<anonymous>"},Za=(e,t,s)=>{if(!i.isCallExpression(e))return[];const[r]=e.getArguments();if(!r||!i.isObjectLiteralExpression(r))return[];const n=[];for(const o of r.getProperties()){if(!i.isPropertyAssignment(o)||!Ga.has(o.getName()))continue;const a=o.getInitializer();if(!(!a||!(i.isArrowFunction(a)||i.isFunctionExpression(a)))&&Qa(a))for(const c of Ja(a)){const l=It(c);l!==void 0&&n.push({exportName:Xa(e),file:s,form:l,key:o.getName(),line:c.getStartLineNumber(),owner:t})}}return n},Ya=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=Ha(r);n!==void 0&&s.push(...Za(r,n,t))}return s},ec=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...Ya(n,f(t,r)))}return s},tc=new Set(["query","upsert","upsertMany"]),sc=e=>{if(!i.isPropertyAccessExpression(e))return;const t=e.getName();if(tc.has(t))return e.getExpression().getText()==="ctx.vectors"?t:void 0},rc=e=>{if(!i.isObjectLiteralExpression(e))return;const t=e.getProperty("namespace");return t&&i.isPropertyAssignment(t)?t.getInitializer():void 0},nc=(e,t)=>{const s=sc(e.getExpression());if(s===void 0)return;const r=e.getArguments()[1];if(!r)return;const n=rc(r);if(!(!n||!w(n)||F(n)))return{exportName:h(e),file:t,line:e.getStartLineNumber(),method:s}},ic=(e,t)=>{const s=[];for(const r of e.getDescendantsOfKind(u.CallExpression)){const n=nc(r,t);n&&s.push(n)}return s},oc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r);s.push(...ic(n,f(t,r)))}return s},ac=e=>{const t=e.getExpression();if(!i.isPropertyAccessExpression(t)||t.getName()!=="get")return!1;const s=t.getExpression();return i.isPropertyAccessExpression(s)?s.getName()==="workflows":i.isIdentifier(s)&&s.getText()==="workflows"},cc=e=>{const t=e.getArguments()[0];return t&&i.isStringLiteral(t)?t.getLiteralText():""},uc=(e,t)=>{const s=[];for(const r of d(t)){const n=e.getSourceFile(r)??e.addSourceFileAtPath(r),o=f(t,r);for(const a of n.getDescendantsOfKind(u.CallExpression)){if(!ac(a))continue;const c=Bs(a);c!==""&&s.push({exportName:c,file:o,line:a.getStartLineNumber(),workflow:cc(a)})}}return s},lc=".lunora-schema.json",A=(e,t)=>{E(e)&&$e(e,"utf8")===t||qt(e,t,"utf8")},P=(e,t)=>{if(t===""){Bt(e,{force:!0});return}A(e,t)},dc=e=>{const t=g(e,"package.json");if(E(t))try{const s=JSON.parse($e(t,"utf8"));return typeof s.version=="string"&&s.version!==""?s.version:void 0}catch{return}},gc=()=>{const e=process.env.LUNORA_CODEGEN_TIMING;return e!==void 0&&e!==""},fc=e=>{let t=E(e)?e:pe(e);for(;t&&t!==pe(t);){const s=g(t,"tsconfig.json");if(E(s))return s;t=pe(t)}},gt=e=>e.replaceAll("\\","/"),pc=(e,t)=>{const s=new Map,r=new Map,n=new Map;for(const o of e)s.set(o.name,`workflow "${o.exportName}"`),r.set(o.bindingName,`workflow "${o.exportName}"`),n.set(o.className,`workflow "${o.exportName}"`);for(const o of t){const a=s.get(o.name);if(a!==void 0)throw new B("DUPLICATE_WORKFLOW_NAME",`Duplicate deployed name "${o.name}": produced by both ${a} and agent "${o.exportName}". Workflow and agent names share the same wrangler workflows[] array and must be unique together.`,{status:500});const c=r.get(o.bindingName);if(c!==void 0)throw new B("DUPLICATE_WORKFLOW_BINDING",`Duplicate binding "${o.bindingName}": produced by both ${c} and agent "${o.exportName}". Workflow and agent bindings share the same wrangler workflows[] array and must be unique together.`,{status:500});const l=n.get(o.className);if(l!==void 0)throw new B("DUPLICATE_WORKFLOW_CLASS",`Duplicate generated class "${o.className}": produced by both ${l} and agent "${o.exportName}". Workflow and agent export names must yield unique generated class names.`,{status:500})}},mc=e=>{const t=fc(e);return t?new Xe({skipAddingFilesFromTsConfig:!1,tsConfigFilePath:t,useInMemoryFileSystem:!1}):new Xe({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1})},tu=(e,t)=>{const s=d(t),r=g(t,"schema.ts");E(r)&&s.push(r);for(const c of s){const l=e.getSourceFile(c);l===void 0?e.addSourceFileAtPath(c):l.refreshFromFileSystemSync()}const n=new Set(s.map(c=>gt(c))),o=gt(t),a=`${o}/`;for(const c of e.getSourceFiles()){const l=c.getFilePath();(l===o||l.startsWith(a))&&!n.has(l)&&e.removeSourceFile(c)}},su=e=>{const t=gc(),s=t?me.now():0,r=g(e.projectRoot,e.lunoraDirectory??"lunora"),n=g(r,"schema.ts");if(!E(n))throw new B("INTERNAL",`schema.ts not found at ${n}`);const o=e.project??mc(r),a=Rs(o,n,e.projectRoot),c=_t(o,r),l=$s(o,r),p=bs(o,r),y=zs(o,r),I=Is(o,r),k=pi(o,r),ve=yn(o,r),v=Vs(o,r),T=Ts(o,r),b=Qt(o,r);pc(v,b);const X=ss(o,r,v,b),D=ts(o,r),R=e.lint===!1?void 0:Wt({adminRoutes:rr(o,r),aiRawRuns:ar(o,r),aiToolSideEffects:hr(o,r),argumentDerivedFetches:Ar(o,r),argumentValidators:Dr(o,r),authApiCalls:es(o,r),authConfigs:Ur(o,r),browserUrlAccesses:Qr(o,r),configCalls:rn(o,r),containerKeyAccesses:on(o,r),containerOverrides:fn(o,r),containers:D,exportSinks:Nn(o,r),failOpenGuards:On(o,r),flagSecurityDefaults:Bn(o,r),geoIndexUsages:Wn(o,r),httpActionGuards:Yn(o,r),httpHeaderWrites:ui(o,r),identityClaimReads:Ai(o,r),imageDeliveryUrlAccesses:bi(o,r),inserts:As(o,r),kvKeyAccesses:wi(o,r),mailRecipientAccesses:Di(o,r),maskProcedures:Ss(o,r),maskStrategies:Ns(o,r),mutatorWrites:Mi(o,r),nondeterministicCalls:Ls(o,r),normalizeIdAuthorizations:to(o,r),notifyCalls:Fs(o,r),notifyConfig:Os(o,r),ownerFieldWrites:uo(o,r),unrestrictedWhereBranches:ec(o,r),paymentWebhooks:xo(o,r),privilegedDispatches:Lo(o,r),procedureProtections:ta(o,r),queries:Yt(o,r),queues:T,r2sqlCalls:Ds(o,r),ratelimitKeySelectors:ca(o,r),rawRowReturns:ma(o,r),relationLoads:Aa(o,r),rlsProcedures:Cs(o,r),schema:a,secretLiterals:va(o,r),shapes:y,softDeleteReads:La(o,r),sqlInterpolations:ka(o,r),storageKeyAccesses:ja(o,r),storageUploads:Wa(o,r),vectorNamespaceAccesses:oc(o,r),workflowCalls:uc(o,r),workflows:v,wranglerVariables:e.wranglerVariables}),be=R===void 0?[]:Vt(R,{source:"static"}),Tt=Ks(o,r),Dt=vs(o,r),Z=qs(o,r),$=Tn(o,r),Y=$.ai,ee=$.payments,Pe=$.kv,we=$.access,te=E(g(r,"flags.ts")),Ct=te?ys(o,r):[],se=E(g(r,"notify.ts")),re=$.hyperdrive,ne=ks(o,r),Kt=ne.usesSandboxBrowser||ne.usesSandboxContainer,ie=$.browser||ne.usesSandboxBrowser,oe=$.images,ae=$.analytics,Ie=$.pipelines,ce=$.r2sql,ue=$.x402,L=lo(e.projectRoot),j=kn($,{containerCount:D.length,cronCount:X.length,dependencies:L,hasPaymentTables:Kn(a.tables),queueCount:T.length,storageColumnCount:Object.keys(rs(a)).length,storageRuleCount:Z.rules.length,vectorIndexCount:a.vectorIndexes.length,workflowCount:v.length}),O=L.has("lunorash"),Le=t?me.now():0,Oe=ns(a,O),Fe=is({agents:b,functions:c,httpRoutes:l,mutators:I,useUmbrella:O,workflows:v}),Te=os({agents:b,containers:D,env:ve,hasAccessFacade:we,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:Pe,hasNotify:se,hasPayments:ee,hasPipelines:Ie,hasR2sql:ce,hasX402:ue,identity:k,queues:T,schema:a,storageRuleBuckets:Z.rules.map(m=>m.bucket),useUmbrella:O,workflows:v}),De=as({agents:b,functions:c,migrations:p,mutators:I,shapes:y,useUmbrella:O,usesSandbox:Kt}),le=Qs(a,p.map(m=>m.id)),Ce=cs({advisories:be,advisorProcedures:R?.procedureProtections??[],agents:b,containers:D,env:ve,flagKeys:Ct,hasAccessFacade:we,hasAi:Y,hasAnalytics:ae,hasBrowser:ie,hasFlags:te,hasHyperdrive:re,hasImages:oe,hasKv:Pe,hasNotify:se,hasPayments:ee,hasPipelines:Ie,hasR2sql:ce,hasX402:ue,maskMetadata:Dt,mutators:I,queues:T,rlsMetadata:Tt,schema:a,schemaSnapshot:le,shapes:y,storageRules:Z,studioFeatures:j,useUmbrella:O,workflows:v}),Ke=us(y,L.has("@lunora/db"),O),ke=ls(D,a.jurisdiction),Re=ds(v),je=gs(b),Me=fs(T),ze=ps(X),qe=ms(a.vectorIndexes),M=xs(a,O),Be=hs(L.has("@lunora/seed")),z=e.apiSpec??"openapi",de=z==="openapi"||z==="both",ge=z==="openrpc"||z==="both",Ve=Us({emailAgents:b.filter(m=>m.onEmail===!0).map(m=>({bindingName:m.bindingName,exportName:m.exportName})),hasAccess:L.has("@lunora/cloudflare-access"),hasAi:Y,hasAnalytics:ae,hasAuth:L.has("@lunora/auth"),hasBrowser:ie,hasFramework:L.has("@lunora/astro")||L.has("@lunora/svelte")||L.has("@lunora/vue"),hasGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend!=="hyperdrive"),hasHyperdrive:re,hasHyperdriveGlobal:a.tables.some(m=>m.shardMode==="global"&&m.globalBackend==="hyperdrive"),hasImages:oe,hasKv:j.kv,hasNotify:se,hasPayments:ee,hasR2sql:ce,hasQueue:T.some(m=>m.mode==="push"),hasScheduler:j.scheduler,hasStorage:j.storage,hasVectors:a.vectorIndexes.length>0,hasWorkflow:v.length>0,hasX402:ue,identity:k,jurisdiction:a.jurisdiction,useUmbrella:O,voiceAgents:b.filter(m=>m.voice===!0&&m.voiceBindingName!==void 0).map(m=>({bindingName:m.voiceBindingName,exportName:m.exportName})),wantsOpenApi:de,wantsOpenRpc:ge}),Ue=dc(e.projectRoot),We=Ws({functions:c,httpRoutes:l,version:Ue}),Ge=Hs({functions:c,version:Ue}),He=`${JSON.stringify(We,void 0,2)}
4
+ `,_e=`${JSON.stringify(Ge,void 0,2)}
5
+ `,Qe=Gs(We),Je=_s(Ge),fe=g(r,lc),kt=E(fe),x=g(r,"_generated");if(e.dryRun||(E(x)||zt(x,{recursive:!0}),A(g(x,"app.ts"),Ve),A(g(x,"dataModel.ts"),Oe),A(g(x,"api.ts"),Fe),A(g(x,"server.ts"),Te),A(g(x,"functions.ts"),De),A(g(x,"shard.ts"),Ce),A(g(x,"crons.ts"),ze),A(g(x,"vectors.ts"),qe),A(g(x,"drizzle.global.ts"),M.global),A(g(x,"drizzle.shard.ts"),M.shard),P(g(x,"containers.ts"),ke),P(g(x,"workflows.ts"),Re),P(g(x,"agents.ts"),je),P(g(x,"queues.ts"),Me),P(g(x,"seed.ts"),Be),P(g(x,"collections.ts"),Ke),P(g(x,"openapi.json"),de?He:""),P(g(x,"openapi.ts"),de?Qe:""),P(g(x,"openrpc.json"),ge?_e:""),P(g(x,"openrpc.ts"),ge?Je:""),(!kt||e.updateSchemaBaseline===!0)&&A(fe,Ut(le))),t){const m=me.now(),Rt=Math.round(m-s),jt=Math.round(Le-s),Mt=Math.round(m-Le);console.error(`@lunora/codegen: codegen took ${Rt.toString()}ms (discovery ${jt.toString()}ms, emit ${Mt.toString()}ms)`)}return{advisories:be,advisorContext:R,agents:b,containers:D,cronTriggers:Es(X),generated:{agents:je,api:Fe,app:Ve,collections:Ke,containers:ke,crons:ze,dataModel:Oe,drizzleGlobal:M.global,drizzleShard:M.shard,functions:De,openApi:He,openApiModule:Qe,openRpc:_e,openRpcModule:Je,queues:Me,seed:Be,server:Te,shard:Ce,vectors:qe,workflows:Re},outputDirectory:x,queues:T,schemaSnapshot:le,schemaSnapshotPath:fe,workflows:v}};export{lc as SCHEMA_SNAPSHOT_FILENAME,mc as createCodegenProject,tu as refreshCodegenProject,su as runCodegen};
@@ -1,3 +1,3 @@
1
- import{w as v}from"./emit-sQzv_a8t.mjs";import{n as c}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as S,objectSchema as b,argsObjectSchema as g,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const O="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie"],h=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],m=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,f=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const n=o.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(m(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(m(e.staleWhileRevalidate))}`),r.join(", ")},k=e=>e.scope==="public"?f(e.vary,...P(e),...h):f(e.vary,...h),R=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},j=e=>{const t=R(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},q=e=>e==="query"?"GET":"POST",l="#/components/responses/LunoraError",y=/:([A-Za-z_$][\w$]*)/gu,A=e=>[...e.matchAll(y)].map(t=>t[1]),w=e=>e.replaceAll(y,"{$1}"),N=e=>{const t=new Set(A(e.path)),r=[];for(const[o,n]of Object.entries(e.searchParams)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:n.kind!=="optional",schema:u(p)})}for(const[o,n]of Object.entries(e.params)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:n.kind!=="optional",schema:u(p)})}return r},C=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},E=e=>{const t=c(e.filePath),r=N(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${c(e.path)}`,responses:{200:C(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:l}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:b(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=c(e.filePath),o={additionalProperties:!1,properties:{args:g(e.args),functionPath:{const:t,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:t,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:{content:{"application/json":{schema:{description:"RPC result. The shape is TS-inferred from the function's return type; best-effort — any JSON."}}},description:"Successful RPC result (TypeScript-inferred return shape, documented best-effort)."},default:{$ref:l}},summary:`${e.kind}: ${t}`,tags:[r],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${t}`}},_=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const n=k(r);return n!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:n,type:"string"}}),{headers:o}},I=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=j(t);if(r===void 0)return;const o=c(e.filePath),n=q(e.kind),p=n==="GET",a={description:`Public REST endpoint for the \`${e.kind}\` \`${t}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${c(r)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",..._(e.expose?.cache,p?"get":"post")},default:{$ref:l}},summary:`${n} ${r}`,tags:[o],"x-lunora-function-kind":e.kind};if(p){const s=Object.entries(e.args).map(([i,d])=>{const $=d.kind==="optional"?d.inner??d:d;return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:d.kind!=="optional",schema:u($)}});return s.length>0&&(a.parameters=s),{method:"get",operation:a,path:r}}return a.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:a,path:r}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const a of e.httpRoutes){const s=w(a.path),i=r[s]??{};i[a.method.toLowerCase()]=E(a),r[s]=i,o.add(c(a.filePath))}const n=e.functions.filter(a=>a.visibility!=="internal"&&a.kind!=="stream");for(const a of n){const{operation:s,pathKey:i}=L(a);r[i]={post:s},o.add(c(a.filePath))}for(const a of n){if(a.expose?.rest!==!0)continue;const s=I(a);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i,o.add(c(a.filePath))}const p=[...o].toSorted((a,s)=>a.localeCompare(s)).map(a=>({description:`Operations declared in \`lunora/${a}\`.`,name:a}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:S,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:p}},U=e=>`${JSON.stringify(D(e),void 0,2)}
1
+ import{w as v}from"./emit-BtiV37rG.mjs";import{n as c}from"./paths-BmX5O1sG.mjs";import{LUNORA_ERROR_CODES as S,objectSchema as b,argsObjectSchema as g,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-Um9hC1gr.mjs";const O="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie"],h=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],m=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,f=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const n=o.trim().toLowerCase();n!==""&&!t.includes(n)&&t.push(n)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(m(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(m(e.staleWhileRevalidate))}`),r.join(", ")},k=e=>e.scope==="public"?f(e.vary,...P(e),...h):f(e.vary,...h),R=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},j=e=>{const t=R(e);if(t!==void 0)return`${O}/${t.namespace}/${t.name}`},q=e=>e==="query"?"GET":"POST",l="#/components/responses/LunoraError",y=/:([A-Za-z_$][\w$]*)/gu,A=e=>[...e.matchAll(y)].map(t=>t[1]),w=e=>e.replaceAll(y,"{$1}"),N=e=>{const t=new Set(A(e.path)),r=[];for(const[o,n]of Object.entries(e.searchParams)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:n.kind!=="optional",schema:u(p)})}for(const[o,n]of Object.entries(e.params)){const p=n.kind==="optional"?n.inner??n:n;r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:n.kind!=="optional",schema:u(p)})}return r},C=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},E=e=>{const t=c(e.filePath),r=N(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${c(e.path)}`,responses:{200:C(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:l}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:b(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},L=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=c(e.filePath),o={additionalProperties:!1,properties:{args:g(e.args),functionPath:{const:t,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${t}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:t,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:{content:{"application/json":{schema:{description:"RPC result. The shape is TS-inferred from the function's return type; best-effort — any JSON."}}},description:"Successful RPC result (TypeScript-inferred return shape, documented best-effort)."},default:{$ref:l}},summary:`${e.kind}: ${t}`,tags:[r],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${t}`}},_=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const n=k(r);return n!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:n,type:"string"}}),{headers:o}},I=e=>{const t=`${c(e.filePath)}:${e.exportName}`,r=j(t);if(r===void 0)return;const o=c(e.filePath),n=q(e.kind),p=n==="GET",a={description:`Public REST endpoint for the \`${e.kind}\` \`${t}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${c(r)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",..._(e.expose?.cache,p?"get":"post")},default:{$ref:l}},summary:`${n} ${r}`,tags:[o],"x-lunora-function-kind":e.kind};if(p){const s=Object.entries(e.args).map(([i,d])=>{const $=d.kind==="optional"?d.inner??d:d;return{description:`Argument \`${i}\` (JSON-encoded for non-string values).`,in:"query",name:i,required:d.kind!=="optional",schema:u($)}});return s.length>0&&(a.parameters=s),{method:"get",operation:a,path:r}}return a.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:a,path:r}},D=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const a of e.httpRoutes){const s=w(a.path),i=r[s]??{};i[a.method.toLowerCase()]=E(a),r[s]=i,o.add(c(a.filePath))}const n=e.functions.filter(a=>a.visibility!=="internal"&&a.kind!=="stream");for(const a of n){const{operation:s,pathKey:i}=L(a);r[i]={post:s},o.add(c(a.filePath))}for(const a of n){if(a.expose?.rest!==!0)continue;const s=I(a);if(s===void 0)continue;const i=r[s.path]??{};i[s.method]=s.operation,r[s.path]=i,o.add(c(a.filePath))}const p=[...o].toSorted((a,s)=>a.localeCompare(s)).map(a=>({description:`Operations declared in \`lunora/${a}\`.`,name:a}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:S,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:p}},U=e=>`${JSON.stringify(D(e),void 0,2)}
2
2
  `,W=e=>`${v}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
3
3
  `;export{D as buildOpenApiDocument,U as emitOpenApi,W as emitOpenApiModule};
@@ -0,0 +1 @@
1
+ import{Node as s,SyntaxKind as a}from"ts-morph";import{listLunoraSourceFiles as E,lunoraRelativePath as A}from"./discoverFunctions-DnqHgv0t.mjs";const p=e=>{if(e.getText()!=="args")return!1;const t=e.getParent();return s.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(s.isPropertyAssignment(t)&&t.getNameNode()===e)},m=e=>{if(e.getText()!=="ctx")return!1;const t=e.getParent();return s.isPropertyAccessExpression(t)&&t.getNameNode()===e?!1:!(s.isPropertyAssignment(t)&&t.getNameNode()===e)},g=e=>s.isIdentifier(e)?m(e):e.getDescendantsOfKind(a.Identifier).some(t=>m(t)),x=(e,t)=>{if(e.getText()!==t)return!1;const r=e.getParent();return s.isPropertyAccessExpression(r)&&r.getNameNode()===e?!1:!(s.isPropertyAssignment(r)&&r.getNameNode()===e)},I=e=>{let t=e;for(;s.isPropertyAccessExpression(t)||s.isElementAccessExpression(t)||s.isNonNullExpression(t);)t=t.getExpression();return s.isIdentifier(t)?t:void 0},F=e=>{if(s.isIdentifier(e))return e.getText();if(s.isPropertyAccessExpression(e))return e.getName()},N=e=>s.isIdentifier(e)?p(e):e.getDescendantsOfKind(a.Identifier).some(t=>p(t)),u=e=>{if(!s.isIdentifier(e))return;const t=e.getText(),r=e.getFirstAncestor(o=>s.isArrowFunction(o)||s.isFunctionExpression(o)||s.isFunctionDeclaration(o));if(r===void 0)return;const n=e.getStart();let i,d=-1;for(const o of r.getDescendantsOfKind(a.VariableDeclaration)){if(o.getName()!==t)continue;const c=o.getInitializer(),f=o.getStart();c!==void 0&&f<n&&f>d&&(i=c,d=f)}return i},K=e=>{if(N(e))return!0;const t=u(e);return t!==void 0&&N(t)},T=e=>{if(g(e))return!0;const t=u(e);if(t!==void 0&&g(t))return!0;const r=t??e;return(s.isIdentifier(r)?[r]:r.getDescendantsOfKind(a.Identifier)).some(n=>{const i=u(n);return i!==void 0&&g(i)})},l=(e,t)=>s.isIdentifier(e)?x(e,t):e.getDescendantsOfKind(a.Identifier).some(r=>x(r,t)),O=(e,t)=>{if(l(e,t))return!0;const r=u(e);if(r!==void 0&&l(r,t))return!0;const n=I(e);if(n!==void 0){const i=u(n);return i!==void 0&&l(i,t)}return!1},P=e=>{for(const t of e.getAncestors())if(s.isVariableDeclaration(t)&&t.getVariableStatement()?.hasExportKeyword()===!0)return t.getName();return"<module>"},y=new Set(["withIndex","withSearchIndex"]),h=e=>{const t=e.getExpression();if(!s.isPropertyAccessExpression(t)||t.getName()!=="query")return!1;const r=t.getExpression();return s.isPropertyAccessExpression(r)?r.getName()==="db":s.isIdentifier(r)&&r.getText()==="db"},v=e=>{const t=[];let r=e;for(;;){const n=r.getParent();if(!n||!s.isPropertyAccessExpression(n))break;const i=n.getParent();if(!i||!s.isCallExpression(i))break;t.push(n.getName()),r=i}return t},S=e=>{const t=e.getArguments()[0];return t&&s.isStringLiteral(t)?t.getLiteralText():""},w=(e,t)=>{const r=[];for(const n of E(t)){const i=e.getSourceFile(n)??e.addSourceFileAtPath(n),d=A(t,n);for(const o of i.getDescendantsOfKind(a.CallExpression)){if(!h(o))continue;const c=v(o);c.includes("filter")&&r.push({exportName:P(o),file:d,hasFilter:!0,hasIndex:c.some(f=>y.has(f)),line:o.getStartLineNumber(),table:S(o)})}}return r};export{w as E,T as a,O as b,F as c,l as d,P as e,K as i,N as r,u as s};
@@ -0,0 +1 @@
1
+ import"ts-morph";import{E as p}from"./discover-queries-LfER8HbK.mjs";import"./discoverFunctions-DnqHgv0t.mjs";export{p as default};