import { a0 as TypedBase, O as OlapTable, L as LifeCycle, a1 as Column, $ as QueryClient, K as sql, a2 as RowPolicyOptions, R as RawValue, M as Sql, a as OlapConfig, a3 as TypiaValidators, V as View, C as ClickHouseEngines } from './view-CJKyTLjp.js';
import { IJsonSchemaCollection } from 'typia';
import { Client } from '@temporalio/client';
import { JWTPayload } from 'jose';
import http from 'http';

/**
 * @fileoverview Stream SDK for data streaming operations in Moose.
 *
 * This module provides the core streaming functionality including:
 * - Stream creation and configuration
 * - Message transformations between streams
 * - Consumer registration for message processing
 * - Dead letter queue handling for error recovery
 *
 * @module Stream
 */

/**
 * Represents zero, one, or many values of type T.
 * Used for flexible return types in transformations where a single input
 * can produce no output, one output, or multiple outputs.
 *
 * @template T The type of the value(s)
 * @example
 * ```typescript
 * // Can return a single value
 * const single: ZeroOrMany<string> = "hello";
 *
 * // Can return an array
 * const multiple: ZeroOrMany<string> = ["hello", "world"];
 *
 * // Can return null/undefined to filter out
 * const filtered: ZeroOrMany<string> = null;
 * ```
 */
type ZeroOrMany<T> = T | T[] | undefined | null;
/**
 * Function type for transforming records from one type to another.
 * Supports both synchronous and asynchronous transformations.
 *
 * @template T The input record type
 * @template U The output record type
 * @param record The input record to transform
 * @returns The transformed record(s), or null/undefined to filter out
 *
 * @example
 * ```typescript
 * const transform: SyncOrAsyncTransform<InputType, OutputType> = (record) => {
 *   return { ...record, processed: true };
 * };
 * ```
 */
type SyncOrAsyncTransform<T, U> = (record: T) => ZeroOrMany<U> | Promise<ZeroOrMany<U>>;
/**
 * Function type for consuming records without producing output.
 * Used for side effects like logging, external API calls, or database writes.
 *
 * @template T The record type to consume
 * @param record The record to process
 * @returns Promise<void> or void
 *
 * @example
 * ```typescript
 * const consumer: Consumer<UserEvent> = async (event) => {
 *   await sendToAnalytics(event);
 * };
 * ```
 */
type Consumer<T> = (record: T) => Promise<void> | void;
/**
 * Configuration options for stream transformations.
 *
 * @template T The type of records being transformed
 */
interface TransformConfig<T> {
    /**
     * Optional version identifier for this transformation.
     * Multiple transformations to the same destination can coexist with different versions.
     */
    version?: string;
    /**
     * Optional metadata for documentation and tracking purposes.
     */
    metadata?: {
        description?: string;
    };
    /**
     * Optional dead letter queue for handling transformation failures.
     * Failed records will be sent to this queue for manual inspection or reprocessing.
     * Uses {@link Stream.defaultDeadLetterQueue} by default
     * unless a DeadLetterQueue is provided, or it is explicitly disabled with a null value
     */
    deadLetterQueue?: DeadLetterQueue<T> | null;
    /**
     * @internal Source file path where this transform was declared.
     * Automatically captured from stack trace.
     */
    sourceFile?: string;
}
/**
 * Configuration options for stream consumers.
 *
 * @template T The type of records being consumed
 */
interface ConsumerConfig<T> {
    /**
     * Optional version identifier for this consumer.
     * Multiple consumers can coexist with different versions.
     */
    version?: string;
    /**
     * Optional dead letter queue for handling consumer failures.
     * Failed records will be sent to this queue for manual inspection or reprocessing.
     * Uses {@link Stream.defaultDeadLetterQueue} by default
     * unless a DeadLetterQueue is provided, or it is explicitly disabled with a null value
     */
    deadLetterQueue?: DeadLetterQueue<T> | null;
    /**
     * @internal Source file path where this consumer was declared.
     * Automatically captured from stack trace.
     */
    sourceFile?: string;
}
type SchemaRegistryEncoding = "JSON" | "AVRO" | "PROTOBUF";
type SchemaRegistryReference = {
    id: number;
} | {
    subjectLatest: string;
} | {
    subject: string;
    version: number;
};
interface KafkaSchemaConfig {
    kind: SchemaRegistryEncoding;
    reference: SchemaRegistryReference;
}
/**
 * Represents a message routed to a specific destination stream.
 * Used internally by the multi-transform functionality to specify
 * where transformed messages should be sent.
 *
 * @internal
 */
declare class RoutedMessage {
    /** The destination stream for the message */
    destination: Stream<any>;
    /** The message value(s) to send */
    values: ZeroOrMany<any>;
    /**
     * Creates a new routed message.
     *
     * @param destination The target stream
     * @param values The message(s) to route
     */
    constructor(destination: Stream<any>, values: ZeroOrMany<any>);
}
/**
 * Configuration options for a data stream (e.g., a Redpanda topic).
 * @template T The data type of the messages in the stream.
 */
interface StreamConfig<T> {
    /**
     * Specifies the number of partitions for the stream. Affects parallelism and throughput.
     */
    parallelism?: number;
    /**
     * Specifies the data retention period for the stream in seconds. Messages older than this may be deleted.
     */
    retentionPeriod?: number;
    /**
     * An optional destination OLAP table where messages from this stream should be automatically ingested.
     */
    destination?: OlapTable<T>;
    /**
     * An optional version string for this configuration. Can be used for tracking changes or managing deployments.
     */
    version?: string;
    metadata?: {
        description?: string;
    };
    lifeCycle?: LifeCycle;
    defaultDeadLetterQueue?: DeadLetterQueue<T>;
    /** Optional Schema Registry configuration for this stream */
    schemaConfig?: KafkaSchemaConfig;
}
/**
 * Represents a data stream, typically corresponding to a Redpanda topic.
 * Provides a typed interface for producing to and consuming from the stream, and defining transformations.
 *
 * @template T The data type of the messages flowing through the stream. The structure of T defines the message schema.
 */
declare class Stream<T> extends TypedBase<T, StreamConfig<T>> {
    defaultDeadLetterQueue?: DeadLetterQueue<T>;
    /** @internal Memoized KafkaJS producer for reusing connections across sends */
    private _memoizedProducer?;
    /** @internal Hash of the configuration used to create the memoized Kafka producer */
    private _kafkaConfigHash?;
    /**
     * Creates a new Stream instance.
     * @param name The name of the stream. This name is used for the underlying Redpanda topic.
     * @param config Optional configuration for the stream.
     */
    constructor(name: string, config?: StreamConfig<T>);
    /**
     * @internal
     * Note: `validators` parameter is a positional placeholder (always undefined for Stream).
     * It exists because TypedBase has validators as the 5th param, and we need to pass
     * allowExtraFields as the 6th param. Stream doesn't use validators.
     */
    constructor(name: string, config: StreamConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators: undefined, allowExtraFields: boolean);
    /**
     * Internal map storing transformation configurations.
     * Maps destination stream names to arrays of transformation functions and their configs.
     *
     * @internal
     */
    _transformations: Map<string, [Stream<any>, SyncOrAsyncTransform<T, any>, TransformConfig<T>][]>;
    /**
     * Internal function for multi-stream transformations.
     * Allows a single transformation to route messages to multiple destinations.
     *
     * @internal
     */
    _multipleTransformations?: (record: T) => [RoutedMessage];
    /**
     * Internal array storing consumer configurations.
     *
     * @internal
     */
    _consumers: {
        consumer: Consumer<T>;
        config: ConsumerConfig<T>;
    }[];
    /**
     * Builds the full Kafka topic name including optional namespace and version suffix.
     * Version suffix is appended as _x_y_z where dots in version are replaced with underscores.
     */
    private buildFullTopicName;
    /**
     * Creates a fast hash string from relevant Kafka configuration fields.
     */
    private createConfigHash;
    /**
     * Gets or creates a memoized KafkaJS producer using runtime configuration.
     */
    private getMemoizedProducer;
    /**
     * Closes the memoized Kafka producer if it exists.
     */
    closeProducer(): Promise<void>;
    /**
     * Sends one or more records to this stream's Kafka topic.
     * Values are JSON-serialized as message values.
     */
    send(values: ZeroOrMany<T>): Promise<void>;
    /**
     * Adds a transformation step that processes messages from this stream and sends the results to a destination stream.
     * Multiple transformations to the same destination stream can be added if they have distinct `version` identifiers in their config.
     *
     * @template U The data type of the messages in the destination stream.
     * @param destination The destination stream for the transformed messages.
     * @param transformation A function that takes a message of type T and returns zero or more messages of type U (or a Promise thereof).
     *                       Return `null` or `undefined` or an empty array `[]` to filter out a message. Return an array to emit multiple messages.
     * @param config Optional configuration for this specific transformation step, like a version.
     */
    addTransform<U>(destination: Stream<U>, transformation: SyncOrAsyncTransform<T, U>, config?: TransformConfig<T>): void;
    /**
     * Adds a consumer function that processes messages from this stream.
     * Multiple consumers can be added if they have distinct `version` identifiers in their config.
     *
     * @param consumer A function that takes a message of type T and performs an action (e.g., side effect, logging). Should return void or Promise<void>.
     * @param config Optional configuration for this specific consumer, like a version.
     */
    addConsumer(consumer: Consumer<T>, config?: ConsumerConfig<T>): void;
    /**
     * Helper method for `addMultiTransform` to specify the destination and values for a routed message.
     * @param values The value or values to send to this stream.
     * @returns A `RoutedMessage` object associating the values with this stream.
     *
     * @example
     * ```typescript
     * sourceStream.addMultiTransform((record) => [
     *   destinationStream1.routed(transformedRecord1),
     *   destinationStream2.routed([record2a, record2b])
     * ]);
     * ```
     */
    routed: (values: ZeroOrMany<T>) => RoutedMessage;
    /**
     * Adds a single transformation function that can route messages to multiple destination streams.
     * This is an alternative to adding multiple individual `addTransform` calls.
     * Only one multi-transform function can be added per stream.
     *
     * @param transformation A function that takes a message of type T and returns an array of `RoutedMessage` objects,
     *                       each specifying a destination stream and the message(s) to send to it.
     */
    addMultiTransform(transformation: (record: T) => [RoutedMessage]): void;
}
/**
 * Base model for dead letter queue entries.
 * Contains the original failed record along with error information.
 */
interface DeadLetterModel {
    /** The original record that failed processing */
    originalRecord: Record<string, any>;
    /** Human-readable error message describing the failure */
    errorMessage: string;
    /** Classification of the error type (e.g., "ValidationError", "TransformError") */
    errorType: string;
    /** Timestamp when the failure occurred */
    failedAt: Date;
    /** The source component where the failure occurred */
    source: "api" | "transform" | "table";
}
/**
 * Enhanced dead letter model with type recovery functionality.
 * Extends the base model with the ability to recover the original typed record.
 *
 * @template T The original record type before failure
 */
interface DeadLetter<T> extends DeadLetterModel {
    /**
     * Recovers the original record as its typed form.
     * Useful for reprocessing failed records with proper type safety.
     *
     * @returns The original record cast to type T
     */
    asTyped: () => T;
}
/**
 * Specialized stream for handling failed records (dead letters).
 * Provides type-safe access to failed records for reprocessing or analysis.
 *
 * @template T The original record type that failed processing
 *
 * @example
 * ```typescript
 * const dlq = new DeadLetterQueue<UserEvent>("user-events-dlq");
 *
 * dlq.addConsumer(async (deadLetter) => {
 *   const originalEvent = deadLetter.asTyped();
 *   console.log(`Failed event: ${deadLetter.errorMessage}`);
 *   // Potentially reprocess or alert
 * });
 * ```
 */
declare class DeadLetterQueue<T> extends Stream<DeadLetterModel> {
    /**
     * Creates a new DeadLetterQueue instance.
     * @param name The name of the dead letter queue stream
     * @param config Optional configuration for the stream. The metadata property is always present and includes stackTrace.
     */
    constructor(name: string, config?: StreamConfig<DeadLetterModel>);
    /** @internal **/
    constructor(name: string, config: StreamConfig<DeadLetterModel>, validate: (originalRecord: any) => T);
    /**
     * Internal type guard function for validating and casting original records.
     *
     * @internal
     */
    private typeGuard;
    /**
     * Adds a transformation step for dead letter records.
     * The transformation function receives a DeadLetter<T> with type recovery capabilities.
     *
     * @template U The output type for the transformation
     * @param destination The destination stream for transformed messages
     * @param transformation Function to transform dead letter records
     * @param config Optional transformation configuration
     */
    addTransform<U>(destination: Stream<U>, transformation: SyncOrAsyncTransform<DeadLetter<T>, U>, config?: TransformConfig<DeadLetterModel>): void;
    /**
     * Adds a consumer for dead letter records.
     * The consumer function receives a DeadLetter<T> with type recovery capabilities.
     *
     * @param consumer Function to process dead letter records
     * @param config Optional consumer configuration
     */
    addConsumer(consumer: Consumer<DeadLetter<T>>, config?: ConsumerConfig<DeadLetterModel>): void;
    /**
     * Adds a multi-stream transformation for dead letter records.
     * The transformation function receives a DeadLetter<T> with type recovery capabilities.
     *
     * @param transformation Function to route dead letter records to multiple destinations
     */
    addMultiTransform(transformation: (record: DeadLetter<T>) => [RoutedMessage]): void;
}

/**
 * Context passed to task handlers. Single param to future-proof API changes.
 *
 * - state: shared mutable state for the task and its lifecycle hooks
 * - input: optional typed input for the task (undefined when task has no input)
 */
/**
 * Task handler context. If the task declares an input type (T != null),
 * `input` is required and strongly typed. For no-input tasks (T = null),
 * `input` is omitted/optional.
 */
type TaskContext<TInput> = TInput extends null ? {
    state: any;
    input?: null;
} : {
    state: any;
    input: TInput;
};
/**
 * Configuration options for defining a task within a workflow.
 *
 * @template T - The input type for the task
 * @template R - The return type for the task
 */
interface TaskConfig<T, R> {
    /** The main function that executes the task logic */
    run: (context: TaskContext<T>) => Promise<R>;
    /**
     * Optional array of tasks to execute after this task completes successfully.
     * Supports all combinations of input types (real type or null) and output types (real type or void).
     * When this task returns void, onComplete tasks expect null as input.
     * When this task returns a real type, onComplete tasks expect that type as input.
     */
    onComplete?: (Task<R extends void ? null : R, any> | Task<R extends void ? null : R, void>)[];
    /**
     * Optional function that is called when the task is cancelled.
     */
    /** Optional function that is called when the task is cancelled. */
    onCancel?: (context: TaskContext<T>) => Promise<void>;
    /** Optional timeout duration for the task execution (e.g., "30s", "5m") */
    timeout?: string;
    /** Optional number of retry attempts if the task fails */
    retries?: number;
}
/**
 * Represents a single task within a workflow system.
 *
 * A Task encapsulates the execution logic, completion handlers, and configuration
 * for a unit of work that can be chained with other tasks in a workflow.
 *
 * @template T - The input type that this task expects
 * @template R - The return type that this task produces
 */
declare class Task<T, R> {
    readonly name: string;
    readonly config: TaskConfig<T, R>;
    /**
     * Creates a new Task instance.
     *
     * @param name - Unique identifier for the task
     * @param config - Configuration object defining the task behavior
     *
     * @example
     * ```typescript
     * // No input, no output
     * const task1 = new Task<null, void>("task1", {
     *   run: async () => {
     *     console.log("No input/output");
     *   }
     * });
     *
     * // No input, but has output
     * const task2 = new Task<null, OutputType>("task2", {
     *   run: async () => {
     *     return someOutput;
     *   }
     * });
     *
     * // Has input, no output
     * const task3 = new Task<InputType, void>("task3", {
     *   run: async (input: InputType) => {
     *     // process input but return nothing
     *   }
     * });
     *
     * // Has both input and output
     * const task4 = new Task<InputType, OutputType>("task4", {
     *   run: async (input: InputType) => {
     *     return process(input);
     *   }
     * });
     * ```
     */
    constructor(name: string, config: TaskConfig<T, R>);
}
/**
 * Configuration options for defining a workflow.
 *
 * A workflow orchestrates the execution of multiple tasks in a defined sequence
 * or pattern, with support for scheduling, retries, and timeouts.
 */
interface WorkflowConfig {
    /**
     * The initial task that begins the workflow execution.
     * Supports all combinations of input types (real type or null) and output types (real type or void):
     * - Task<null, OutputType>: No input, returns a type
     * - Task<null, void>: No input, returns nothing
     * - Task<InputType, OutputType>: Has input, returns a type
     * - Task<InputType, void>: Has input, returns nothing
     */
    startingTask: Task<null, any> | Task<null, void> | Task<any, any> | Task<any, void>;
    /** Optional number of retry attempts if the entire workflow fails */
    retries?: number;
    /** Optional timeout duration for the entire workflow execution (e.g., "10m", "1h") */
    timeout?: string;
    /** Optional cron-style schedule string for automated workflow execution */
    schedule?: string;
}
/**
 * Represents a complete workflow composed of interconnected tasks.
 *
 * A Workflow manages the execution flow of multiple tasks, handling scheduling,
 * error recovery, and task orchestration. Once created, workflows are automatically
 * registered with the internal Moose system.
 *
 * @example
 * ```typescript
 * const dataProcessingWorkflow = new Workflow("dataProcessing", {
 *   startingTask: extractDataTask,
 *   schedule: "0 2 * * *", // Run daily at 2 AM
 *   timeout: "1h",
 *   retries: 2
 * });
 * ```
 */
declare class Workflow {
    readonly name: string;
    readonly config: WorkflowConfig;
    /** @internal Source file path where this workflow was declared */
    sourceFile?: string;
    /** @internal Source line number where this workflow was declared */
    sourceLine?: number;
    /** @internal Source column number where this workflow was declared */
    sourceColumn?: number;
    /**
     * Creates a new Workflow instance and registers it with the Moose system.
     *
     * @param name - Unique identifier for the workflow
     * @param config - Configuration object defining the workflow behavior and task orchestration
     * @throws {Error} When the workflow contains null/undefined tasks or infinite loops
     */
    constructor(name: string, config: WorkflowConfig);
    /**
     * Validates the task graph to ensure there are no null tasks or infinite loops.
     *
     * @private
     * @param startingTask - The starting task to begin validation from
     * @param workflowName - The name of the workflow being validated (for error messages)
     * @throws {Error} When null/undefined tasks are found or infinite loops are detected
     */
    private validateTaskGraph;
}

/**
 * @template T The data type of the messages expected by the destination stream.
 */
interface IngestConfig<T> {
    /**
     * The destination stream where the ingested data should be sent.
     */
    destination: Stream<T>;
    deadLetterQueue?: DeadLetterQueue<T>;
    /**
     * An optional version string for this configuration.
     */
    version?: string;
    /**
     * An optional custom path for the ingestion endpoint.
     */
    path?: string;
    metadata?: {
        description?: string;
    };
}
/**
 * Represents an Ingest API endpoint, used for sending data into a Moose system, typically writing to a Stream.
 * Provides a typed interface for the expected data format.
 *
 * @template T The data type of the records that this API endpoint accepts. The structure of T defines the expected request body schema.
 */
declare class IngestApi<T> extends TypedBase<T, IngestConfig<T>> {
    /**
     * Creates a new IngestApi instance.
     * @param name The name of the ingest API endpoint.
     * @param config Optional configuration for the ingest API.
     */
    constructor(name: string, config?: IngestConfig<T>);
    /**
     * @internal
     * Note: `validators` parameter is a positional placeholder (always undefined for IngestApi).
     * It exists because TypedBase has validators as the 5th param, and we need to pass
     * allowExtraFields as the 6th param. IngestApi doesn't use validators.
     */
    constructor(name: string, config: IngestConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators: undefined, allowExtraFields: boolean);
}

/**
 * Utilities provided by getMooseUtils() for database access and SQL queries.
 * Works in both Moose runtime and standalone contexts.
 */
interface MooseUtils {
    client: MooseClient;
    sql: typeof sql;
    jwt?: JWTPayload;
}
/**
 * @deprecated Use MooseUtils instead. ApiUtil is now a type alias to MooseUtils
 * and will be removed in a future version.
 *
 * Migration: Replace `ApiUtil` with `MooseUtils` in your type annotations.
 */
type ApiUtil = MooseUtils;
/** @deprecated Use MooseUtils instead. */
type ConsumptionUtil = MooseUtils;
declare class MooseClient {
    query: QueryClient;
    workflow: WorkflowClient;
    constructor(queryClient: QueryClient, temporalClient?: Client);
}
/**
 * Shared ClickHouse role name used by all row policies.
 * IMPORTANT: Must match MOOSE_RLS_ROLE in apps/framework-cli/src/framework/core/infrastructure/select_row_policy.rs
 */
declare const MOOSE_RLS_ROLE = "moose_rls_role";
/**
 * Dedicated ClickHouse user for RLS queries.
 * Created at DDL time with SELECT-only permissions and the RLS role granted.
 * IMPORTANT: Must match MOOSE_RLS_USER in apps/framework-cli/src/framework/core/infrastructure/select_row_policy.rs
 */
declare const MOOSE_RLS_USER = "moose_rls_user";
/**
 * Prefix for ClickHouse custom settings used by row policies.
 * Setting names are `{MOOSE_RLS_SETTING_PREFIX}{column}`.
 * IMPORTANT: Must match the format in setting_name() in apps/framework-cli/src/framework/core/infrastructure/select_row_policy.rs
 */
declare const MOOSE_RLS_SETTING_PREFIX = "SQL_moose_rls_";
/** Config mapping ClickHouse setting names to JWT claim names */
type RowPoliciesConfig = Record<string, string>;
/**
 * Build RowPolicyOptions from a row policies config and a claim-value source.
 * Only sets ClickHouse settings for claims that are present in the source.
 *
 * Missing claims are skipped — if a table's row policy calls getSetting()
 * for a setting that wasn't set, ClickHouse will error. This is correct:
 * it means the JWT is missing a claim that the queried table requires.
 * Tables whose policies don't reference the missing setting are unaffected.
 *
 * @param config  Maps ClickHouse setting name → claim name
 * @param claims  Maps claim name → claim value (e.g., JWT payload or rlsContext)
 * @returns RowPolicyOptions with the shared RLS role and populated settings
 */
declare function buildRowPolicyOptionsFromClaims(config: RowPoliciesConfig, claims: Record<string, unknown>): RowPolicyOptions;
declare class WorkflowClient {
    client: Client | undefined;
    constructor(temporalClient?: Client);
    execute(name: string, input_data: any): Promise<{
        status: number;
        body: string;
    }>;
    terminate(workflowId: string): Promise<{
        status: number;
        body: string;
    }>;
    private getWorkflowConfig;
    private processInputData;
}
/**
 * This looks similar to the client in runner.ts which is a worker.
 * Temporal SDK uses similar looking connection options & client,
 * but there are different libraries for a worker & client like this one
 * that triggers workflows.
 */
declare function getTemporalClient(temporalUrl: string, namespace: string, clientCert: string, clientKey: string, apiKey: string): Promise<Client | undefined>;
declare const ApiHelpers: {
    column: (value: string) => [string, string];
    table: (value: string) => [string, string];
};
/** @deprecated Use ApiHelpers instead. */
declare const ConsumptionHelpers: {
    column: (value: string) => [string, string];
    table: (value: string) => [string, string];
};
declare function joinQueries({ values, separator, prefix, suffix, }: {
    values: readonly RawValue[];
    separator?: string;
    prefix?: string;
    suffix?: string;
}): Sql;

/**
 * Defines the signature for a handler function used by a Consumption API.
 * @template T The expected type of the request parameters or query parameters.
 * @template R The expected type of the response data.
 * @param params An object containing the validated request parameters, matching the structure of T.
 * @param utils Utility functions provided to the handler, e.g., for database access (`runSql`).
 * @returns A Promise resolving to the response data of type R.
 */
type ApiHandler<T, R> = (params: T, utils: ApiUtil) => Promise<R>;
/**
 * @template T The data type of the request parameters.
 */
interface ApiConfig<T> {
    /**
     * An optional version string for this configuration.
     */
    version?: string;
    /**
     * An optional custom path for the API endpoint.
     * If not specified, defaults to the API name.
     */
    path?: string;
    metadata?: {
        description?: string;
    };
}
/**
 * Represents a Consumption API endpoint (API), used for querying data from a Moose system.
 * Exposes data, often from an OlapTable or derived through a custom handler function.
 *
 * @template T The data type defining the expected structure of the API's query parameters.
 * @template R The data type defining the expected structure of the API's response body. Defaults to `any`.
 */
declare class Api<T, R = any> extends TypedBase<T, ApiConfig<T>> {
    /** @internal The handler function that processes requests and generates responses. */
    _handler: ApiHandler<T, R>;
    /** @internal The JSON schema definition for the response type R. */
    responseSchema: IJsonSchemaCollection.IV3_1;
    /**
     * Creates a new Api instance.
     * @param name The name of the consumption API endpoint.
     * @param handler The function to execute when the endpoint is called. It receives validated query parameters and utility functions.
     * @param config Optional configuration for the consumption API.
     */
    constructor(name: string, handler: ApiHandler<T, R>, config?: {});
    /** @internal **/
    constructor(name: string, handler: ApiHandler<T, R>, config: ApiConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], responseSchema: IJsonSchemaCollection.IV3_1);
    /**
     * Retrieves the handler function associated with this Consumption API.
     * @returns The handler function.
     */
    getHandler: () => ApiHandler<T, R>;
    call(baseUrl: string, queryParams: T): Promise<R>;
}
/** @deprecated Use ApiConfig<T> directly instead. */
type EgressConfig<T> = ApiConfig<T>;
/** @deprecated Use Api directly instead. */
declare const ConsumptionApi: typeof Api;

/**
 * Configuration options for a complete ingestion pipeline, potentially including an Ingest API, a Stream, and an OLAP Table.
 *
 * @template T The data type of the records being ingested.
 *
 * @example
 * ```typescript
 * // Simple pipeline with all components enabled
 * const pipelineConfig: IngestPipelineConfig<UserData> = {
 *   table: true,
 *   stream: true,
 *   ingestApi: true
 * };
 *
 * // Advanced pipeline with custom configurations
 * const advancedConfig: IngestPipelineConfig<UserData> = {
 *   table: { orderByFields: ['timestamp', 'userId'], engine: ClickHouseEngines.ReplacingMergeTree },
 *   stream: { parallelism: 4, retentionPeriod: 86400 },
 *   ingestApi: true,
 *   version: '1.2.0',
 *   metadata: { description: 'User data ingestion pipeline' }
 * };
 * ```
 */
type IngestPipelineConfig<T> = {
    /**
     * Configuration for the OLAP table component of the pipeline.
     *
     * - If `true`, a table with default settings is created.
     * - If an `OlapConfig` object is provided, it specifies the table's configuration.
     * - If `false`, no OLAP table is created.
     *
     * @default false
     */
    table: boolean | OlapConfig<T>;
    /**
     * Configuration for the stream component of the pipeline.
     *
     * - If `true`, a stream with default settings is created.
     * - Pass a config object to specify the stream's configuration.
     * - The stream's destination will automatically be set to the pipeline's table if one exists.
     * - If `false`, no stream is created.
     *
     * @default false
     */
    stream: boolean | Omit<StreamConfig<T>, "destination">;
    /**
     * Configuration for the ingest API component of the pipeline.
     *
     * - If `true`, an ingest API with default settings is created.
     * - If a partial `IngestConfig` object (excluding `destination`) is provided, it specifies the API's configuration.
     * - The API's destination will automatically be set to the pipeline's stream if one exists.
     * - If `false`, no ingest API is created.
     *
     * **Note:** Requires a stream to be configured when enabled.
     *
     * @default false
     */
    ingestApi: boolean | Omit<IngestConfig<T>, "destination">;
    /**
     * @deprecated Use `ingestApi` instead. This parameter will be removed in a future version.
     */
    ingest?: boolean | Omit<IngestConfig<T>, "destination">;
    /**
     * Configuration for the dead letter queue of the pipeline.
     * If `true`, a dead letter queue with default settings is created.
     * If a partial `StreamConfig` object (excluding `destination`) is provided, it specifies the dead letter queue's configuration.
     * The API's destination will automatically be set to the pipeline's stream if one exists.
     * If `false` or `undefined`, no dead letter queue is created.
     */
    deadLetterQueue?: boolean | StreamConfig<DeadLetterModel>;
    /**
     * An optional version string applying to all components (table, stream, ingest) created by this pipeline configuration.
     * This version will be used for schema versioning and component identification.
     *
     * @example "v1.0.0", "2023-12", "prod"
     */
    version?: string;
    /**
     * An optional custom path for the ingestion API endpoint.
     * This will be used as the HTTP path for the ingest API if one is created.
     *
     * @example "pipelines/analytics", "data/events"
     */
    path?: string;
    /**
     * Optional metadata for the pipeline.
     */
    metadata?: {
        /** Human-readable description of the pipeline's purpose */
        description?: string;
    };
    /** Determines how changes in code will propagate to the resources. */
    lifeCycle?: LifeCycle;
};
/**
 * Represents a complete ingestion pipeline, potentially combining an Ingest API, a Stream, and an OLAP Table
 * under a single name and configuration. Simplifies the setup of common ingestion patterns.
 *
 * This class provides a high-level abstraction for creating data ingestion workflows that can include:
 * - An HTTP API endpoint for receiving data
 * - A streaming component for real-time data processing
 * - An OLAP table for analytical queries
 *
 * @template T The data type of the records flowing through the pipeline. This type defines the schema for the
 *             Ingest API input, the Stream messages, and the OLAP Table rows.
 *
 * @example
 * ```typescript
 * // Create a complete pipeline with all components
 * const userDataPipeline = new IngestPipeline('userData', {
 *   table: true,
 *   stream: true,
 *   ingestApi: true,
 *   version: '1.0.0',
 *   metadata: { description: 'Pipeline for user registration data' }
 * });
 *
 * // Create a pipeline with only table and stream
 * const analyticsStream = new IngestPipeline('analytics', {
 *   table: { orderByFields: ['timestamp'], engine: ClickHouseEngines.ReplacingMergeTree },
 *   stream: { parallelism: 8, retentionPeriod: 604800 },
 *   ingestApi: false
 * });
 * ```
 */
declare class IngestPipeline<T> extends TypedBase<T, IngestPipelineConfig<T>> {
    /**
     * The OLAP table component of the pipeline, if configured.
     * Provides analytical query capabilities for the ingested data.
     * Only present when `config.table` is not `false`.
     */
    table?: OlapTable<T>;
    /**
     * The stream component of the pipeline, if configured.
     * Handles real-time data flow and processing between components.
     * Only present when `config.stream` is not `false`.
     */
    stream?: Stream<T>;
    /**
     * The ingest API component of the pipeline, if configured.
     * Provides HTTP endpoints for data ingestion.
     * Only present when `config.ingestApi` is not `false`.
     */
    ingestApi?: IngestApi<T>;
    /** The dead letter queue of the pipeline, if configured. */
    deadLetterQueue?: DeadLetterQueue<T>;
    /**
     * Creates a new IngestPipeline instance.
     * Based on the configuration, it automatically creates and links the IngestApi, Stream, and OlapTable components.
     *
     * @param name The base name for the pipeline components (e.g., "userData" could create "userData" table, "userData" stream, "userData" ingest API).
     * @param config Optional configuration for the ingestion pipeline.
     *
     * @throws {Error} When ingest API is enabled but no stream is configured, since the API requires a stream destination.
     *
     * @example
     * ```typescript
     * const pipeline = new IngestPipeline('events', {
     *   table: { orderByFields: ['timestamp'], engine: ClickHouseEngines.ReplacingMergeTree },
     *   stream: { parallelism: 2 },
     *   ingestApi: true
     * });
     * ```
     */
    constructor(name: string, config: IngestPipelineConfig<T>);
    /**
     * Internal constructor used by the framework for advanced initialization.
     *
     * @internal
     * @param name The base name for the pipeline components.
     * @param config Configuration specifying which components to create and their settings.
     * @param schema JSON schema collection for type validation.
     * @param columns Column definitions for the data model.
     * @param validators Typia validation functions.
     * @param allowExtraFields Whether extra fields are allowed (injected when type has index signature).
     */
    constructor(name: string, config: IngestPipelineConfig<T>, schema: IJsonSchemaCollection.IV3_1, columns: Column[], validators: TypiaValidators<T>, allowExtraFields: boolean);
}

interface ETLPipelineConfig<T, U> {
    extract: AsyncIterable<T> | (() => AsyncIterable<T>);
    transform: (sourceData: T) => Promise<U>;
    load: ((data: U[]) => Promise<void>) | OlapTable<U>;
}
declare class ETLPipeline<T, U> {
    readonly name: string;
    readonly config: ETLPipelineConfig<T, U>;
    private batcher;
    constructor(name: string, config: ETLPipelineConfig<T, U>);
    private setupPipeline;
    private createBatcher;
    private getDefaultTaskConfig;
    private createAllTasks;
    private createExtractTask;
    private createTransformTask;
    private createLoadTask;
    run(): Promise<void>;
}

/**
 * Configuration options for creating a Materialized View.
 * @template T The data type of the records stored in the target table of the materialized view.
 */
interface MaterializedViewConfig<T> {
    /** The SQL SELECT statement or `Sql` object defining the data to be materialized. Dynamic SQL (with parameters) is not allowed here. */
    selectStatement: string | Sql;
    /** An array of OlapTable or View objects that the `selectStatement` reads from. */
    selectTables: (OlapTable<any> | View)[];
    /** @deprecated See {@link targetTable}
     *  The name for the underlying target OlapTable that stores the materialized data. */
    tableName?: string;
    /** The name for the ClickHouse MATERIALIZED VIEW object itself. */
    materializedViewName: string;
    /** @deprecated See {@link targetTable}
     *  Optional ClickHouse engine for the target table (e.g., ReplacingMergeTree). Defaults to MergeTree. */
    engine?: ClickHouseEngines;
    targetTable?: OlapTable<T> /**  Target table if the OlapTable object is already constructed. */ | {
        /** The name for the underlying target OlapTable that stores the materialized data. */
        name: string;
        /** Optional ClickHouse engine for the target table (e.g., ReplacingMergeTree). Defaults to MergeTree. */
        engine?: ClickHouseEngines;
        /** Optional ordering fields for the target table. Crucial if using ReplacingMergeTree. */
        orderByFields?: (keyof T & string)[];
    };
    /** @deprecated See {@link targetTable}
     *  Optional ordering fields for the target table. Crucial if using ReplacingMergeTree. */
    orderByFields?: (keyof T & string)[];
    /** Optional metadata for the materialized view (e.g., description, source file). */
    metadata?: {
        [key: string]: any;
    };
    /** Optional lifecycle management policy for the materialized view.
     * Controls whether Moose can drop or modify the MV automatically.
     * Defaults to FULLY_MANAGED if not specified. */
    lifeCycle?: LifeCycle;
}
/**
 * Represents a Materialized View in ClickHouse.
 * This encapsulates both the target OlapTable that stores the data and the MATERIALIZED VIEW definition
 * that populates the table based on inserts into the source tables.
 *
 * @template TargetTable The data type of the records stored in the underlying target OlapTable. The structure of T defines the target table schema.
 */
declare class MaterializedView<TargetTable> {
    /** @internal */
    readonly kind = "MaterializedView";
    /** The name of the materialized view */
    name: string;
    /** The target OlapTable instance where the materialized data is stored. */
    targetTable: OlapTable<TargetTable>;
    /** The SELECT SQL statement */
    selectSql: string;
    /** Names of source tables that the SELECT reads from */
    sourceTables: string[];
    /** Optional metadata for the materialized view */
    metadata: {
        [key: string]: any;
    };
    /** Optional lifecycle management policy for the materialized view */
    lifeCycle?: LifeCycle;
    /**
     * Creates a new MaterializedView instance.
     * Requires the `TargetTable` type parameter to be explicitly provided or inferred,
     * as it's needed to define the schema of the underlying target table.
     *
     * @param options Configuration options for the materialized view.
     */
    constructor(options: MaterializedViewConfig<TargetTable>);
    /** @internal **/
    constructor(options: MaterializedViewConfig<TargetTable>, targetSchema: IJsonSchemaCollection.IV3_1, targetColumns: Column[]);
}

type SqlObject = OlapTable<any> | SqlResource | View | MaterializedView<any>;
/**
 * Represents a generic SQL resource that requires setup and teardown commands.
 * Base class for constructs like Views and Materialized Views. Tracks dependencies.
 */
declare class SqlResource {
    /** @internal */
    readonly kind = "SqlResource";
    /** Array of SQL statements to execute for setting up the resource. */
    setup: readonly string[];
    /** Array of SQL statements to execute for tearing down the resource. */
    teardown: readonly string[];
    /** The name of the SQL resource (e.g., view name, materialized view name). */
    name: string;
    /** List of OlapTables or Views that this resource reads data from. */
    pullsDataFrom: SqlObject[];
    /** List of OlapTables or Views that this resource writes data to. */
    pushesDataTo: SqlObject[];
    /** @internal Source file path where this resource was defined */
    sourceFile?: string;
    /** @internal Source line number where this resource was defined */
    sourceLine?: number;
    /** @internal Source column number where this resource was defined */
    sourceColumn?: number;
    /**
     * Creates a new SqlResource instance.
     * @param name The name of the resource.
     * @param setup An array of SQL DDL statements to create the resource.
     * @param teardown An array of SQL DDL statements to drop the resource.
     * @param options Optional configuration for specifying data dependencies.
     * @param options.pullsDataFrom Tables/Views this resource reads from.
     * @param options.pushesDataTo Tables/Views this resource writes to.
     */
    constructor(name: string, setup: readonly (string | Sql)[], teardown: readonly (string | Sql)[], options?: {
        pullsDataFrom?: SqlObject[];
        pushesDataTo?: SqlObject[];
    });
}

/** Extract the row type from an OlapTable instance. */
type RowOf<T> = T extends OlapTable<infer R> ? R : never;
/**
 * Configuration for a SelectRowPolicy.
 *
 * Defines a ClickHouse row policy that filters rows based on a column value
 * matched against a JWT claim via `getSetting()`.
 *
 * The `column` field is type-checked against the columns shared by all
 * tables — a typo will be caught at compile time.
 */
interface SelectRowPolicyConfig<Tables extends readonly OlapTable<any>[] = readonly OlapTable<any>[]> {
    /** Tables the policy applies to. Policies propagate through regular Views automatically. */
    tables: readonly [...Tables];
    /** Column to filter on (e.g., "org_id"). Must exist in every table. */
    column: keyof RowOf<Tables[number]> & string;
    /** JWT claim name that provides the filter value (e.g., "org_id") */
    claim: string;
}
/**
 * Represents a ClickHouse Row Policy as a first-class Moose primitive.
 *
 * When defined, Moose generates `CREATE ROW POLICY` DDL that uses
 * `getSetting('SQL_moose_rls_{column}')` for dynamic per-query tenant scoping.
 *
 * @example
 * ```typescript
 * export const tenantIsolation = new SelectRowPolicy("tenant_isolation", {
 *   tables: [DataEventTable],
 *   column: "org_id",
 *   claim: "org_id",
 * });
 * ```
 */
declare class SelectRowPolicy<Tables extends readonly OlapTable<any>[] = readonly OlapTable<any>[]> {
    /** @internal */
    readonly kind = "SelectRowPolicy";
    /** The name of the row policy */
    readonly name: string;
    /** The policy configuration */
    readonly config: Readonly<SelectRowPolicyConfig<Tables>>;
    constructor(name: string, config: SelectRowPolicyConfig<Tables>);
    /** Resolved table references for serialization */
    get tableRefs(): {
        name: string;
        database?: string;
    }[];
}

type WebAppHandler = (req: http.IncomingMessage, res: http.ServerResponse) => void | Promise<void>;
interface FrameworkApp {
    handle?: (req: http.IncomingMessage, res: http.ServerResponse, next?: (err?: any) => void) => void;
    callback?: () => WebAppHandler;
    routing?: (req: http.IncomingMessage, res: http.ServerResponse) => void;
    ready?: () => PromiseLike<unknown>;
}
interface WebAppConfig {
    mountPath: string;
    metadata?: {
        description?: string;
    };
    injectMooseUtils?: boolean;
}
declare class WebApp {
    name: string;
    handler: WebAppHandler;
    config: WebAppConfig;
    /** @internal Source file path where this web app was declared */
    sourceFile?: string;
    /** @internal Source line number where this web app was declared */
    sourceLine?: number;
    /** @internal Source column number where this web app was declared */
    sourceColumn?: number;
    private _rawApp?;
    constructor(name: string, appOrHandler: FrameworkApp | WebAppHandler, config: WebAppConfig);
    private toHandler;
    getRawApp(): FrameworkApp | undefined;
}

/**
 * @module registry
 * Public registry functions for accessing Moose Data Model v2 (dmv2) resources.
 *
 * This module provides functions to retrieve registered resources like tables, streams,
 * APIs, and more. These functions are part of the public API and can be used by
 * user applications to inspect and interact with registered Moose resources.
 */

/**
 * Get all registered OLAP tables.
 * @returns A Map of table name to OlapTable instance
 */
declare function getTables(): Map<string, OlapTable<any>>;
/**
 * Get a registered OLAP table by name.
 * @param name - The name of the table
 * @returns The OlapTable instance or undefined if not found
 */
declare function getTable(name: string): OlapTable<any> | undefined;
/**
 * Get all registered streams.
 * @returns A Map of stream name to Stream instance
 */
declare function getStreams(): Map<string, Stream<any>>;
/**
 * Get a registered stream by name.
 * @param name - The name of the stream
 * @returns The Stream instance or undefined if not found
 */
declare function getStream(name: string): Stream<any> | undefined;
/**
 * Get all registered ingestion APIs.
 * @returns A Map of API name to IngestApi instance
 */
declare function getIngestApis(): Map<string, IngestApi<any>>;
/**
 * Get a registered ingestion API by name.
 * @param name - The name of the ingestion API
 * @returns The IngestApi instance or undefined if not found
 */
declare function getIngestApi(name: string): IngestApi<any> | undefined;
/**
 * Get all registered APIs (consumption/egress APIs).
 * @returns A Map of API key to Api instance
 */
declare function getApis(): Map<string, Api<any>>;
/**
 * Get a registered API by name, version, or path.
 *
 * Supports multiple lookup strategies:
 * 1. Direct lookup by full key (name:version or name for unversioned)
 * 2. Lookup by name with automatic version aliasing when only one versioned API exists
 * 3. Lookup by custom path (if configured)
 *
 * @param nameOrPath - The name, name:version, or custom path of the API
 * @returns The Api instance or undefined if not found
 */
declare function getApi(nameOrPath: string): Api<any> | undefined;
/**
 * Get all registered SQL resources.
 * @returns A Map of resource name to SqlResource instance
 */
declare function getSqlResources(): Map<string, SqlResource>;
/**
 * Get a registered SQL resource by name.
 * @param name - The name of the SQL resource
 * @returns The SqlResource instance or undefined if not found
 */
declare function getSqlResource(name: string): SqlResource | undefined;
/**
 * Get all registered workflows.
 * @returns A Map of workflow name to Workflow instance
 */
declare function getWorkflows(): Map<string, Workflow>;
/**
 * Get a registered workflow by name.
 * @param name - The name of the workflow
 * @returns The Workflow instance or undefined if not found
 */
declare function getWorkflow(name: string): Workflow | undefined;
/**
 * Get all registered web apps.
 * @returns A Map of web app name to WebApp instance
 */
declare function getWebApps(): Map<string, WebApp>;
/**
 * Get a registered web app by name.
 * @param name - The name of the web app
 * @returns The WebApp instance or undefined if not found
 */
declare function getWebApp(name: string): WebApp | undefined;
/**
 * Get all registered materialized views.
 * @returns A Map of MV name to MaterializedView instance
 */
declare function getMaterializedViews(): Map<string, MaterializedView<any>>;
/**
 * Get a registered materialized view by name.
 * @param name - The name of the materialized view
 * @returns The MaterializedView instance or undefined if not found
 */
declare function getMaterializedView(name: string): MaterializedView<any> | undefined;
/**
 * Get all registered views.
 * @returns A Map of view name to View instance
 */
declare function getViews(): Map<string, View>;
/**
 * Get a registered view by name.
 * @param name - The name of the view
 * @returns The View instance or undefined if not found
 */
declare function getView(name: string): View | undefined;
/**
 * Get all registered row policies.
 * @returns A Map of policy name to SelectRowPolicy instance
 */
declare function getSelectRowPolicies(): Map<string, SelectRowPolicy>;
/**
 * Get a registered row policy by name.
 * @param name - The name of the row policy
 * @returns The SelectRowPolicy instance or undefined if not found
 */
declare function getSelectRowPolicy(name: string): SelectRowPolicy | undefined;

/**
 * @module dmv2
 * This module defines the core Moose v2 data model constructs, including OlapTable, Stream, IngestApi, Api,
 * IngestPipeline, View, and MaterializedView. These classes provide a typed interface for defining and managing
 * data infrastructure components like ClickHouse tables, Redpanda streams, and data processing pipelines.
 */
/**
 * A helper type used potentially for indicating aggregated fields in query results or schemas.
 * Captures the aggregation function name and argument types.
 * (Usage context might be specific to query builders or ORM features).
 *
 * @template AggregationFunction The name of the aggregation function (e.g., 'sum', 'avg', 'count').
 * @template ArgTypes An array type representing the types of the arguments passed to the aggregation function.
 */
type Aggregated<AggregationFunction extends string, ArgTypes extends any[] = []> = {
    _aggregationFunction?: AggregationFunction;
    _argTypes?: ArgTypes;
};
/**
 * A helper type for SimpleAggregateFunction in ClickHouse.
 * SimpleAggregateFunction stores the aggregated value directly instead of intermediate states,
 * offering better performance for functions like sum, max, min, any, anyLast, etc.
 *
 * @template AggregationFunction The name of the simple aggregation function (e.g., 'sum', 'max', 'anyLast').
 * @template ArgType The type of the argument (and result) of the aggregation function.
 *
 * @example
 * ```typescript
 * interface Stats {
 *   rowCount: number & SimpleAggregated<'sum', number>;
 *   maxValue: number & SimpleAggregated<'max', number>;
 *   lastStatus: string & SimpleAggregated<'anyLast', string>;
 * }
 * ```
 */
type SimpleAggregated<AggregationFunction extends string, ArgType = any> = {
    _simpleAggregationFunction?: AggregationFunction;
    _argType?: ArgType;
};

export { type RowPoliciesConfig as $, type Aggregated as A, getWorkflows as B, ConsumptionApi as C, type DeadLetterModel as D, type EgressConfig as E, type FrameworkApp as F, getWorkflow as G, getWebApps as H, IngestApi as I, getWebApp as J, getView as K, getViews as L, MaterializedView as M, getMaterializedView as N, getMaterializedViews as O, getSelectRowPolicies as P, getSelectRowPolicy as Q, type ApiUtil as R, type SimpleAggregated as S, Task as T, type ConsumptionUtil as U, type MooseUtils as V, Workflow as W, MooseClient as X, MOOSE_RLS_ROLE as Y, MOOSE_RLS_USER as Z, MOOSE_RLS_SETTING_PREFIX as _, Stream as a, buildRowPolicyOptionsFromClaims as a0, WorkflowClient as a1, getTemporalClient as a2, ApiHelpers as a3, ConsumptionHelpers as a4, joinQueries as a5, type ConsumerConfig as a6, type TransformConfig as a7, type TaskContext as a8, type TaskConfig as a9, type IngestPipelineConfig as aa, type MaterializedViewConfig as ab, type StreamConfig as b, type DeadLetter as c, DeadLetterQueue as d, type IngestConfig as e, Api as f, type ApiConfig as g, IngestPipeline as h, SqlResource as i, SelectRowPolicy as j, type SelectRowPolicyConfig as k, ETLPipeline as l, type ETLPipelineConfig as m, WebApp as n, type WebAppConfig as o, type WebAppHandler as p, getTables as q, getTable as r, getStreams as s, getStream as t, getIngestApis as u, getIngestApi as v, getApis as w, getApi as x, getSqlResources as y, getSqlResource as z };
