/**
 * Core types for the Fluxbase SDK
 */
/**
 * Client configuration options (Supabase-compatible)
 * These options are passed as the third parameter to createClient()
 */
interface FluxbaseClientOptions {
    /**
     * Authentication options
     */
    auth?: {
        /**
         * Access token for authentication
         */
        token?: string;
        /**
         * Auto-refresh token when it expires
         * @default true
         */
        autoRefresh?: boolean;
        /**
         * Persist auth state in localStorage
         * @default true
         */
        persist?: boolean;
    };
    /**
     * Whether this is a service role client
     * When true, enables service_role features like onBehalfOf for job submission
     * @internal
     */
    serviceRole?: boolean;
    /**
     * Global headers to include in all requests
     */
    headers?: Record<string, string>;
    /**
     * Request timeout in milliseconds
     * @default 30000
     */
    timeout?: number;
    /**
     * Enable debug logging
     * @default false
     */
    debug?: boolean;
}
interface AuthSession {
    user: User;
    access_token: string;
    refresh_token: string;
    expires_in: number;
    expires_at?: number;
}
interface User {
    id: string;
    email: string;
    email_verified: boolean;
    role: string;
    metadata?: Record<string, unknown> | null;
    created_at: string;
    updated_at: string;
}
interface SignInCredentials {
    email: string;
    password: string;
    /** CAPTCHA token for bot protection (optional, required if CAPTCHA is enabled) */
    captchaToken?: string;
    /** Challenge ID from pre-flight CAPTCHA check (for adaptive trust) */
    challengeId?: string;
    /** Device fingerprint for trust tracking (optional) */
    deviceFingerprint?: string;
}
interface SignUpCredentials {
    email: string;
    password: string;
    /** CAPTCHA token for bot protection (optional, required if CAPTCHA is enabled) */
    captchaToken?: string;
    /** Challenge ID from pre-flight CAPTCHA check (for adaptive trust) */
    challengeId?: string;
    /** Device fingerprint for trust tracking (optional) */
    deviceFingerprint?: string;
    options?: {
        /** User metadata to store in raw_user_meta_data (Supabase-compatible) */
        data?: Record<string, unknown>;
    };
}
/**
 * User attributes for updateUser (Supabase-compatible)
 */
interface UpdateUserAttributes {
    /** New email address */
    email?: string;
    /** New password */
    password?: string;
    /** User metadata (Supabase-compatible) */
    data?: Record<string, unknown>;
    /** Nonce for password update reauthentication */
    nonce?: string;
}
interface AuthResponse {
    user: User;
    access_token: string;
    refresh_token: string;
    expires_in: number;
}
/**
 * MFA Factor (Supabase-compatible)
 */
interface Factor {
    id: string;
    type: "totp" | "phone";
    status: "verified" | "unverified";
    created_at: string;
    updated_at: string;
    friendly_name?: string;
}
/**
 * TOTP setup details (Supabase-compatible)
 */
interface TOTPSetup {
    qr_code: string;
    secret: string;
    uri: string;
}
/**
 * MFA enroll response (Supabase-compatible)
 */
interface TwoFactorSetupResponse {
    id: string;
    type: "totp";
    totp: TOTPSetup;
}
/**
 * MFA enable response - returned when activating 2FA after setup
 */
interface TwoFactorEnableResponse {
    success: boolean;
    backup_codes: string[];
    message: string;
}
/**
 * MFA login response - returned when verifying 2FA during login
 */
interface TwoFactorLoginResponse {
    access_token: string;
    refresh_token: string;
    user: User;
    token_type?: string;
    expires_in?: number;
}
/**
 * MFA status response (Supabase-compatible)
 */
interface TwoFactorStatusResponse {
    all: Factor[];
    totp: Factor[];
}
/**
 * MFA unenroll response (Supabase-compatible)
 */
interface TwoFactorDisableResponse {
    id: string;
}
interface TwoFactorVerifyRequest {
    user_id: string;
    code: string;
}
interface SignInWith2FAResponse {
    requires_2fa: boolean;
    user_id: string;
    message: string;
}
interface FluxbaseError extends Error {
    status?: number;
    code?: string;
    details?: unknown;
}
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD";
interface RequestOptions {
    method: HttpMethod;
    headers?: Record<string, string>;
    body?: unknown;
    timeout?: number;
}
interface PostgrestError {
    message: string;
    details?: string;
    hint?: string;
    code?: string;
}
interface PostgrestResponse<T> {
    data: T | null;
    error: PostgrestError | null;
    count: number | null;
    status: number;
    statusText: string;
}
/**
 * Count type for select queries (Supabase-compatible)
 * - 'exact': Returns the exact count of rows (SELECT COUNT(*))
 * - 'planned': Uses PostgreSQL's query planner estimate (faster, less accurate)
 * - 'estimated': Uses statistics-based estimate (fastest, least accurate)
 */
type CountType = "exact" | "planned" | "estimated";
/**
 * Options for select queries (Supabase-compatible)
 */
interface SelectOptions {
    /**
     * Count type to use for the query
     * When specified, the count will be returned in the response
     */
    count?: CountType;
    /**
     * If true, only returns count without fetching data (HEAD request)
     * Useful for getting total count without transferring row data
     */
    head?: boolean;
}
type FilterOperator = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "like" | "ilike" | "is" | "in" | "cs" | "cd" | "ov" | "sl" | "sr" | "nxr" | "nxl" | "adj" | "not" | "fts" | "plfts" | "wfts" | "st_intersects" | "st_contains" | "st_within" | "st_dwithin" | "st_distance" | "st_touches" | "st_crosses" | "st_overlaps" | "between" | "not.between" | "vec_l2" | "vec_cos" | "vec_ip";
interface QueryFilter {
    column: string;
    operator: FilterOperator;
    value: unknown;
}
type OrderDirection = "asc" | "desc";
interface OrderBy {
    column: string;
    direction: OrderDirection;
    nulls?: "first" | "last";
    /** Vector operator for similarity ordering (vec_l2, vec_cos, vec_ip) */
    vectorOp?: "vec_l2" | "vec_cos" | "vec_ip";
    /** Vector value for similarity ordering */
    vectorValue?: number[];
}
/**
 * Options for upsert operations (Supabase-compatible)
 */
interface UpsertOptions {
    /**
     * Comma-separated columns to use for conflict resolution
     * @example 'email'
     * @example 'user_id,tenant_id'
     */
    onConflict?: string;
    /**
     * If true, duplicate rows are ignored (not upserted)
     * @default false
     */
    ignoreDuplicates?: boolean;
    /**
     * If true, missing columns default to null instead of using existing values
     * @default false
     */
    defaultToNull?: boolean;
}
interface RealtimeMessage {
    type: "subscribe" | "unsubscribe" | "heartbeat" | "broadcast" | "presence" | "ack" | "error" | "postgres_changes" | "access_token";
    channel?: string;
    event?: string;
    schema?: string;
    table?: string;
    filter?: string;
    payload?: unknown;
    error?: string;
    config?: PostgresChangesConfig;
    presence?: unknown;
    broadcast?: unknown;
    messageId?: string;
    status?: string;
    subscription_id?: string;
    token?: string;
}
interface PostgresChangesConfig {
    event: "INSERT" | "UPDATE" | "DELETE" | "*";
    schema: string;
    table: string;
    filter?: string;
}
/**
 * Realtime postgres_changes payload structure
 * Compatible with Supabase realtime payloads
 */
interface RealtimePostgresChangesPayload<T = unknown> {
    /** Event type (Supabase-compatible field name) */
    eventType: "INSERT" | "UPDATE" | "DELETE" | "*";
    /** Database schema */
    schema: string;
    /** Table name */
    table: string;
    /** Commit timestamp (Supabase-compatible field name) */
    commit_timestamp: string;
    /** New record data (Supabase-compatible field name) */
    new: T;
    /** Old record data (Supabase-compatible field name) */
    old: T;
    /** Error message if any */
    errors: string | null;
}
/**
 * @deprecated Use RealtimePostgresChangesPayload instead
 */
interface RealtimeChangePayload {
    /** @deprecated Use eventType instead */
    type: "INSERT" | "UPDATE" | "DELETE";
    schema: string;
    table: string;
    /** @deprecated Use 'new' instead */
    new_record?: Record<string, unknown>;
    /** @deprecated Use 'old' instead */
    old_record?: Record<string, unknown>;
    /** @deprecated Use commit_timestamp instead */
    timestamp: string;
}
type RealtimeCallback = (payload: RealtimePostgresChangesPayload) => void;
/**
 * Realtime channel configuration options
 */
interface RealtimeChannelConfig {
    broadcast?: {
        self?: boolean;
        ack?: boolean;
        ackTimeout?: number;
    };
    presence?: {
        key?: string;
    };
}
/**
 * Presence state for a user
 */
interface PresenceState {
    [key: string]: unknown;
}
/**
 * Realtime presence payload structure
 */
interface RealtimePresencePayload {
    event: "sync" | "join" | "leave";
    key?: string;
    newPresences?: PresenceState[];
    leftPresences?: PresenceState[];
    currentPresences?: Record<string, PresenceState[]>;
}
/**
 * Presence callback type
 */
type PresenceCallback = (payload: RealtimePresencePayload) => void;
/**
 * Broadcast message structure
 */
interface BroadcastMessage {
    type: "broadcast";
    event: string;
    payload: unknown;
}
/**
 * Realtime broadcast payload structure
 */
interface RealtimeBroadcastPayload {
    event: string;
    payload: unknown;
}
/**
 * Broadcast callback type
 */
type BroadcastCallback = (payload: RealtimeBroadcastPayload) => void;
/**
 * File object returned by storage operations
 * Compatible with Supabase FileObject structure
 */
interface FileObject {
    name: string;
    id?: string;
    bucket_id?: string;
    owner?: string;
    created_at?: string;
    updated_at?: string;
    last_accessed_at?: string;
    metadata?: Record<string, unknown>;
}
/**
 * @deprecated Use FileObject instead. This alias is provided for backwards compatibility.
 */
type StorageObject = FileObject;
/**
 * Upload progress information
 */
interface UploadProgress {
    /** Number of bytes uploaded so far */
    loaded: number;
    /** Total number of bytes to upload */
    total: number;
    /** Upload percentage (0-100) */
    percentage: number;
}
interface UploadOptions {
    contentType?: string;
    metadata?: Record<string, string>;
    cacheControl?: string;
    upsert?: boolean;
    /** Optional callback to track upload progress */
    onUploadProgress?: (progress: UploadProgress) => void;
}
/**
 * Options for streaming uploads (memory-efficient for large files)
 */
interface StreamUploadOptions {
    /** MIME type of the file */
    contentType?: string;
    /** Custom metadata to attach to the file */
    metadata?: Record<string, string>;
    /** Cache-Control header value */
    cacheControl?: string;
    /** If true, overwrite existing file at this path */
    upsert?: boolean;
    /** AbortSignal to cancel the upload */
    signal?: AbortSignal;
    /** Optional callback to track upload progress */
    onUploadProgress?: (progress: UploadProgress) => void;
}
interface ListOptions {
    prefix?: string;
    limit?: number;
    offset?: number;
}
interface SignedUrlOptions {
    /** Expiration time in seconds (default: 3600 = 1 hour) */
    expiresIn?: number;
    /** Image transformation options (only applies to images) */
    transform?: TransformOptions;
}
interface DownloadOptions {
    /** If true, returns a ReadableStream instead of Blob */
    stream?: boolean;
    /**
     * Timeout in milliseconds for the download request.
     * For streaming downloads, this applies to the initial response.
     * Set to 0 or undefined for no timeout (recommended for large files).
     * @default undefined (no timeout for streaming, 30000 for non-streaming)
     */
    timeout?: number;
    /** AbortSignal to cancel the download */
    signal?: AbortSignal;
}
/** Response type for stream downloads, includes file size from Content-Length header */
interface StreamDownloadData {
    /** The readable stream for the file content */
    stream: ReadableStream<Uint8Array>;
    /** File size in bytes from Content-Length header, or null if unknown */
    size: number | null;
}
/** Options for resumable chunked downloads */
interface ResumableDownloadOptions {
    /**
     * Chunk size in bytes for each download request.
     * @default 5242880 (5MB)
     */
    chunkSize?: number;
    /**
     * Number of retry attempts per chunk on failure.
     * @default 3
     */
    maxRetries?: number;
    /**
     * Base delay in milliseconds for exponential backoff.
     * @default 1000
     */
    retryDelayMs?: number;
    /**
     * Timeout in milliseconds per chunk request.
     * @default 30000
     */
    chunkTimeout?: number;
    /** AbortSignal to cancel the download */
    signal?: AbortSignal;
    /** Callback for download progress */
    onProgress?: (progress: DownloadProgress) => void;
}
/** Download progress information */
interface DownloadProgress {
    /** Number of bytes downloaded so far */
    loaded: number;
    /** Total file size in bytes, or null if unknown */
    total: number | null;
    /** Download percentage (0-100), or null if total is unknown */
    percentage: number | null;
    /** Current chunk being downloaded (1-indexed) */
    currentChunk: number;
    /** Total number of chunks, or null if total size unknown */
    totalChunks: number | null;
    /** Transfer rate in bytes per second */
    bytesPerSecond: number;
}
/** Response type for resumable downloads - stream abstracts chunking */
interface ResumableDownloadData {
    /** The readable stream for the file content (abstracts chunking internally) */
    stream: ReadableStream<Uint8Array>;
    /** File size in bytes from HEAD request, or null if unknown */
    size: number | null;
}
/** Options for resumable chunked uploads */
interface ResumableUploadOptions {
    /**
     * Chunk size in bytes for each upload request.
     * @default 5242880 (5MB)
     */
    chunkSize?: number;
    /**
     * Number of retry attempts per chunk on failure.
     * @default 3
     */
    maxRetries?: number;
    /**
     * Base delay in milliseconds for exponential backoff.
     * @default 1000
     */
    retryDelayMs?: number;
    /**
     * Timeout in milliseconds per chunk request.
     * @default 60000 (1 minute)
     */
    chunkTimeout?: number;
    /** AbortSignal to cancel the upload */
    signal?: AbortSignal;
    /** Callback for upload progress */
    onProgress?: (progress: ResumableUploadProgress) => void;
    /** MIME type of the file */
    contentType?: string;
    /** Custom metadata to attach to the file */
    metadata?: Record<string, string>;
    /** Cache-Control header value */
    cacheControl?: string;
    /** Existing upload session ID to resume (optional) */
    resumeSessionId?: string;
}
/** Upload progress information for resumable uploads */
interface ResumableUploadProgress {
    /** Number of bytes uploaded so far */
    loaded: number;
    /** Total file size in bytes */
    total: number;
    /** Upload percentage (0-100) */
    percentage: number;
    /** Current chunk being uploaded (1-indexed) */
    currentChunk: number;
    /** Total number of chunks */
    totalChunks: number;
    /** Transfer rate in bytes per second */
    bytesPerSecond: number;
    /** Upload session ID (for resume capability) */
    sessionId: string;
}
/** Chunked upload session information */
interface ChunkedUploadSession {
    /** Unique session identifier for resume */
    sessionId: string;
    /** Target bucket */
    bucket: string;
    /** Target file path */
    path: string;
    /** Total file size */
    totalSize: number;
    /** Chunk size used */
    chunkSize: number;
    /** Total number of chunks */
    totalChunks: number;
    /** Array of completed chunk indices (0-indexed) */
    completedChunks: number[];
    /** Session status */
    status: "active" | "completing" | "completed" | "aborted" | "expired";
    /** Session expiration time */
    expiresAt: string;
    /** Session creation time */
    createdAt: string;
}
interface ShareFileOptions {
    userId: string;
    permission: "read" | "write";
}
interface FileShare {
    user_id: string;
    permission: "read" | "write";
    created_at: string;
}
interface BucketSettings {
    public?: boolean;
    allowed_mime_types?: string[];
    max_file_size?: number;
}
interface Bucket {
    id: string;
    name: string;
    public: boolean;
    allowed_mime_types: string[];
    max_file_size?: number;
    created_at: string;
    updated_at: string;
}
/**
 * Password reset email sent response (Supabase-compatible)
 * Returns OTP-style response similar to Supabase's AuthOtpResponse
 */
interface PasswordResetResponse {
    user: null;
    session: null;
    messageId?: string;
}
/**
 * Verify password reset token response (Fluxbase extension)
 */
interface VerifyResetTokenResponse {
    valid: boolean;
    message: string;
}
/**
 * Reset password completion response (Supabase-compatible)
 * Returns user and session after successful password reset
 */
type ResetPasswordResponse = AuthResponseData;
interface MagicLinkOptions {
    redirect_to?: string;
    /** CAPTCHA token for bot protection (optional, required if CAPTCHA is enabled) */
    captchaToken?: string;
}
/**
 * Magic link sent response (Supabase-compatible)
 * Returns OTP-style response similar to Supabase's AuthOtpResponse
 */
interface MagicLinkResponse {
    user: null;
    session: null;
    messageId?: string;
}
interface OAuthProviderInfo {
    id: string;
    name: string;
    enabled: boolean;
    authorize_url?: string;
}
interface OAuthProvidersResponse {
    providers: OAuthProviderInfo[];
}
interface OAuthOptions {
    redirect_to?: string;
    redirect_uri?: string;
    scopes?: string[];
}
interface OAuthUrlResponse {
    url: string;
    provider: string;
}
/**
 * Options for OAuth logout
 */
interface OAuthLogoutOptions {
    /** URL to redirect to after logout completes */
    redirect_url?: string;
}
/**
 * Response from OAuth logout endpoint
 */
interface OAuthLogoutResponse {
    /** OAuth provider name */
    provider: string;
    /** Whether local JWT tokens were revoked */
    local_tokens_revoked: boolean;
    /** Whether the token was revoked at the OAuth provider */
    provider_token_revoked: boolean;
    /** Whether the user should be redirected to the provider's logout page */
    requires_redirect?: boolean;
    /** URL to redirect to for OIDC logout (if requires_redirect is true) */
    redirect_url?: string;
    /** Warning message if something failed but logout still proceeded */
    warning?: string;
}
/**
 * Response from the provider token endpoint
 * Contains OAuth tokens that can be used to call provider APIs (e.g., Google Drive)
 */
interface ProviderTokenResponse {
    /** OAuth provider name (e.g., 'google', 'github') */
    provider: string;
    /** Provider access token - use this to call provider APIs */
    access_token: string;
    /** Provider refresh token (may be empty for some providers) */
    refresh_token?: string;
    /** Token expiry timestamp in RFC3339 format */
    token_expiry: string;
    /** Seconds until token expires (0 if already expired) */
    expires_in: number;
    /** OpenID Connect ID token (if available) */
    id_token?: string;
    /** OAuth scopes granted for this token */
    scopes?: string[];
    /** Token type (always 'Bearer') */
    token_type: string;
}
/**
 * Error response when provider token is not found
 */
interface ProviderTokenNotFoundError {
    /** Error message */
    error: string;
    /** Error code for programmatic handling */
    error_code: "oauth_token_not_found";
    /** Hint for resolving the error */
    error_hint: string;
    /** Provider name */
    provider: string;
    /** URL to initiate OAuth flow for this provider */
    authorize_url: string;
}
/**
 * SAML Identity Provider configuration
 */
interface SAMLProvider {
    /** Unique provider identifier (slug name) */
    id: string;
    /** Display name of the provider */
    name: string;
    /** Whether the provider is enabled */
    enabled: boolean;
    /** Provider's entity ID (used for SP metadata) */
    entity_id: string;
    /** SSO endpoint URL */
    sso_url: string;
    /** Single Logout endpoint URL (optional) */
    slo_url?: string;
}
/**
 * Response containing list of SAML providers
 */
interface SAMLProvidersResponse {
    providers: SAMLProvider[];
}
/**
 * Options for initiating SAML login
 */
interface SAMLLoginOptions {
    /** URL to redirect after successful authentication */
    redirectUrl?: string;
}
/**
 * Response containing SAML login URL
 */
interface SAMLLoginResponse {
    /** URL to redirect user to for SAML authentication */
    url: string;
    /** Provider name */
    provider: string;
}
/**
 * SAML session information
 */
interface SAMLSession {
    /** Session ID */
    id: string;
    /** User ID */
    user_id: string;
    /** Provider name */
    provider_name: string;
    /** SAML NameID */
    name_id: string;
    /** Session index from IdP */
    session_index?: string;
    /** SAML attributes */
    attributes?: Record<string, string[]>;
    /** Session expiration time */
    expires_at?: string;
    /** Session creation time */
    created_at: string;
}
type OTPType = "signup" | "invite" | "magiclink" | "recovery" | "email_change" | "sms" | "phone_change" | "email";
interface SignInWithOtpCredentials {
    email?: string;
    phone?: string;
    options?: {
        emailRedirectTo?: string;
        shouldCreateUser?: boolean;
        data?: Record<string, unknown>;
        captchaToken?: string;
    };
}
interface VerifyOtpParams {
    email?: string;
    phone?: string;
    token: string;
    type: OTPType;
    options?: {
        redirectTo?: string;
        captchaToken?: string;
    };
}
interface ResendOtpParams {
    type: "signup" | "sms" | "email";
    email?: string;
    phone?: string;
    options?: {
        emailRedirectTo?: string;
        captchaToken?: string;
    };
}
interface OTPResponse {
    user: null;
    session: null;
    messageId?: string;
}
interface UserIdentity {
    id: string;
    user_id: string;
    identity_data?: Record<string, unknown>;
    provider: string;
    created_at: string;
    updated_at: string;
}
interface UserIdentitiesResponse {
    identities: UserIdentity[];
}
interface LinkIdentityCredentials {
    provider: string;
}
interface UnlinkIdentityParams {
    identity: UserIdentity;
}
interface ReauthenticateResponse {
    nonce: string;
}
interface SignInWithIdTokenCredentials {
    provider: "google" | "apple";
    token: string;
    nonce?: string;
    options?: {
        captchaToken?: string;
    };
}
interface AdminSetupStatusResponse {
    needs_setup: boolean;
    has_admin: boolean;
}
interface AdminSetupRequest {
    email: string;
    password: string;
    name: string;
    setup_token: string;
}
interface AdminUser {
    id: string;
    email: string;
    name: string;
    role: string;
    email_verified: boolean;
    created_at: string;
    updated_at: string;
    last_login_at?: string;
}
interface AdminAuthResponse {
    user: AdminUser;
    access_token: string;
    refresh_token: string;
    expires_in: number;
}
interface AdminLoginRequest {
    email: string;
    password: string;
}
interface AdminRefreshRequest {
    refresh_token: string;
}
interface AdminRefreshResponse {
    access_token: string;
    refresh_token: string;
    expires_in: number;
    user: AdminUser;
}
interface AdminMeResponse {
    user: {
        id: string;
        email: string;
        role: string;
    };
}
interface EnrichedUser {
    id: string;
    email: string;
    role?: string;
    created_at: string;
    updated_at?: string;
    email_verified?: boolean;
    last_login_at?: string;
    session_count?: number;
    is_anonymous?: boolean;
    metadata?: Record<string, unknown>;
}
interface ListUsersResponse {
    users: EnrichedUser[];
    total: number;
}
interface ListUsersOptions {
    exclude_admins?: boolean;
    search?: string;
    limit?: number;
    type?: "app" | "dashboard";
}
interface InviteUserRequest {
    email: string;
    role?: string;
    send_email?: boolean;
}
interface InviteUserResponse {
    user: EnrichedUser;
    invitation_link?: string;
    message: string;
}
interface UpdateUserRoleRequest {
    role: string;
}
interface ResetUserPasswordResponse {
    message: string;
}
interface DeleteUserResponse {
    message: string;
}
interface ClientKey {
    id: string;
    name: string;
    description?: string;
    key_prefix: string;
    scopes: string[];
    rate_limit_per_minute: number;
    created_at: string;
    updated_at?: string;
    expires_at?: string;
    revoked_at?: string;
    last_used_at?: string;
    user_id: string;
}
interface CreateClientKeyRequest {
    name: string;
    description?: string;
    scopes: string[];
    rate_limit_per_minute: number;
    expires_at?: string;
}
interface CreateClientKeyResponse {
    client_key: ClientKey;
    key: string;
}
interface ListClientKeysResponse {
    client_keys: ClientKey[];
    total: number;
}
interface UpdateClientKeyRequest {
    name?: string;
    description?: string;
    scopes?: string[];
    rate_limit_per_minute?: number;
}
interface RevokeClientKeyResponse {
    message: string;
}
interface DeleteClientKeyResponse {
    message: string;
}
/** @deprecated Use ClientKey instead */
type APIKey = ClientKey;
/** @deprecated Use CreateClientKeyRequest instead */
type CreateAPIKeyRequest = CreateClientKeyRequest;
/** @deprecated Use CreateClientKeyResponse instead */
type CreateAPIKeyResponse = CreateClientKeyResponse;
/** @deprecated Use ListClientKeysResponse instead */
type ListAPIKeysResponse = ListClientKeysResponse;
/** @deprecated Use UpdateClientKeyRequest instead */
type UpdateAPIKeyRequest = UpdateClientKeyRequest;
/** @deprecated Use RevokeClientKeyResponse instead */
type RevokeAPIKeyResponse = RevokeClientKeyResponse;
/** @deprecated Use DeleteClientKeyResponse instead */
type DeleteAPIKeyResponse = DeleteClientKeyResponse;
interface Webhook {
    id: string;
    url: string;
    events: string[];
    secret?: string;
    description?: string;
    is_active: boolean;
    created_at: string;
    updated_at?: string;
    user_id: string;
}
interface CreateWebhookRequest {
    url: string;
    events: string[];
    description?: string;
    secret?: string;
}
interface UpdateWebhookRequest {
    url?: string;
    events?: string[];
    description?: string;
    is_active?: boolean;
}
interface ListWebhooksResponse {
    webhooks: Webhook[];
    total: number;
}
interface TestWebhookResponse {
    success: boolean;
    status_code?: number;
    response_body?: string;
    error?: string;
}
interface WebhookDelivery {
    id: string;
    webhook_id: string;
    event: string;
    payload: Record<string, unknown>;
    status_code?: number;
    response_body?: string;
    error?: string;
    created_at: string;
    delivered_at?: string;
}
interface ListWebhookDeliveriesResponse {
    deliveries: WebhookDelivery[];
}
interface DeleteWebhookResponse {
    message: string;
}
interface Invitation {
    id: string;
    email: string;
    role: string;
    token?: string;
    invited_by: string;
    accepted_at?: string;
    expires_at: string;
    created_at: string;
    revoked_at?: string;
}
interface CreateInvitationRequest {
    email: string;
    role: "instance_admin" | "tenant_admin" | "dashboard_user";
    expiry_duration?: number;
}
interface CreateInvitationResponse {
    invitation: Invitation;
    invite_link: string;
    email_sent: boolean;
    email_status?: string;
}
interface ValidateInvitationResponse {
    valid: boolean;
    invitation?: Invitation;
    error?: string;
}
interface AcceptInvitationRequest {
    password: string;
    name: string;
}
interface AcceptInvitationResponse {
    user: AdminUser;
    access_token: string;
    refresh_token: string;
    expires_in: number;
}
interface ListInvitationsOptions {
    include_accepted?: boolean;
    include_expired?: boolean;
}
interface ListInvitationsResponse {
    invitations: Invitation[];
}
interface RevokeInvitationResponse {
    message: string;
}
/**
 * Override information for a setting controlled by environment variable
 */
interface SettingOverride {
    is_overridden: boolean;
    env_var: string;
}
/**
 * System setting with key-value storage
 */
interface SystemSetting {
    id: string;
    key: string;
    value: Record<string, unknown>;
    description?: string;
    /** True if this setting is overridden by an environment variable */
    is_overridden?: boolean;
    /** The environment variable name if overridden */
    override_source?: string;
    created_at: string;
    updated_at: string;
}
/**
 * Request to update a system setting
 */
interface UpdateSystemSettingRequest {
    value: Record<string, unknown>;
    description?: string;
}
/**
 * Response containing all system settings
 */
interface ListSystemSettingsResponse {
    settings: SystemSetting[];
}
/**
 * Custom setting with flexible key-value storage and role-based editing permissions
 */
interface CustomSetting {
    id: string;
    key: string;
    value: Record<string, unknown>;
    value_type: "string" | "number" | "boolean" | "json";
    description?: string;
    editable_by: string[];
    metadata?: Record<string, unknown>;
    created_by?: string;
    updated_by?: string;
    created_at: string;
    updated_at: string;
}
/**
 * Metadata for a secret setting (value is never exposed via API)
 * Secret values can only be accessed server-side (in edge functions, jobs, handlers)
 */
interface SecretSettingMetadata {
    id: string;
    key: string;
    description?: string;
    user_id?: string;
    created_by?: string;
    updated_by?: string;
    created_at: string;
    updated_at: string;
}
/**
 * A user's non-encrypted setting
 * These settings are stored per-user and can be read/written via SDK
 */
interface UserSetting {
    id: string;
    key: string;
    value: Record<string, unknown>;
    description?: string;
    user_id: string;
    created_at: string;
    updated_at: string;
}
/**
 * A setting with source information (user or system)
 * Returned when fetching a setting with user -> system fallback
 */
interface UserSettingWithSource {
    key: string;
    value: Record<string, unknown>;
    /** Where the value came from: "user" = user's own setting, "system" = system default */
    source: "user" | "system";
}
/**
 * Request to create or update a user setting
 */
interface CreateUserSettingRequest {
    value: Record<string, unknown>;
    description?: string;
}
/**
 * Authentication settings for the application
 */
interface AuthenticationSettings {
    enable_signup: boolean;
    enable_magic_link: boolean;
    password_min_length: number;
    require_email_verification: boolean;
    password_require_uppercase: boolean;
    password_require_lowercase: boolean;
    password_require_number: boolean;
    password_require_special: boolean;
    session_timeout_minutes: number;
    max_sessions_per_user: number;
}
/**
 * Feature flags for the application
 */
interface FeatureSettings {
    enable_realtime: boolean;
    enable_storage: boolean;
    enable_functions: boolean;
    enable_ai: boolean;
    enable_jobs: boolean;
    enable_rpc: boolean;
}
/**
 * SMTP email provider configuration
 */
interface SMTPSettings {
    host: string;
    port: number;
    username: string;
    password: string;
    use_tls: boolean;
}
/**
 * SendGrid email provider configuration
 */
interface SendGridSettings {
    api_key: string;
}
/**
 * Mailgun email provider configuration
 */
interface MailgunSettings {
    api_key: string;
    domain: string;
    eu_region: boolean;
}
/**
 * AWS SES email provider configuration
 */
interface SESSettings {
    access_key_id: string;
    secret_access_key: string;
    region: string;
}
/**
 * Email configuration settings
 */
interface EmailSettings {
    enabled: boolean;
    provider: "smtp" | "sendgrid" | "mailgun" | "ses";
    from_address?: string;
    from_name?: string;
    reply_to_address?: string;
    smtp?: SMTPSettings;
    sendgrid?: SendGridSettings;
    mailgun?: MailgunSettings;
    ses?: SESSettings;
}
/**
 * Security settings for the application
 */
interface SecuritySettings {
    enable_global_rate_limit: boolean;
}
/**
 * Indicates which settings are overridden by environment variables (read-only)
 */
interface SettingOverrides {
    authentication?: Record<string, boolean>;
    features?: Record<string, boolean>;
    email?: Record<string, boolean>;
    security?: Record<string, boolean>;
}
/**
 * Complete application settings structure
 */
interface AppSettings {
    authentication: AuthenticationSettings;
    features: FeatureSettings;
    email: EmailSettings;
    security: SecuritySettings;
    /** Settings overridden by environment variables (read-only, cannot be modified via API) */
    overrides?: SettingOverrides;
}
/**
 * Request to update application settings
 * All fields are optional for partial updates
 */
interface UpdateAppSettingsRequest {
    authentication?: Partial<AuthenticationSettings>;
    features?: Partial<FeatureSettings>;
    email?: Partial<EmailSettings>;
    security?: Partial<SecuritySettings>;
}
/**
 * Email template type
 */
type EmailTemplateType = "magic_link" | "verify_email" | "reset_password" | "invite_user";
/**
 * Email template structure
 */
interface EmailTemplate {
    id: string;
    template_type: EmailTemplateType;
    subject: string;
    html_body: string;
    text_body?: string;
    is_custom: boolean;
    created_at: string;
    updated_at: string;
}
/**
 * Request to update an email template
 */
interface UpdateEmailTemplateRequest {
    subject: string;
    html_body: string;
    text_body?: string;
}
/**
 * Request to test an email template
 */
interface TestEmailTemplateRequest {
    recipient_email: string;
}
/**
 * Response when listing email templates
 */
interface ListEmailTemplatesResponse {
    templates: EmailTemplate[];
}
/**
 * Override information for a setting controlled by environment variable
 */
interface EmailSettingOverride {
    is_overridden: boolean;
    env_var: string;
}
/**
 * Email provider settings response from /api/v1/admin/email/settings
 *
 * This is the flat structure returned by the admin API, which differs from
 * the nested EmailSettings structure used in AppSettings.
 */
interface EmailProviderSettings {
    enabled: boolean;
    provider: "smtp" | "sendgrid" | "mailgun" | "ses";
    from_address: string;
    from_name: string;
    smtp_host: string;
    smtp_port: number;
    smtp_username: string;
    smtp_password_set: boolean;
    smtp_tls: boolean;
    sendgrid_api_key_set: boolean;
    mailgun_api_key_set: boolean;
    mailgun_domain: string;
    ses_access_key_set: boolean;
    ses_secret_key_set: boolean;
    ses_region: string;
    /** Settings overridden by environment variables */
    _overrides: Record<string, EmailSettingOverride>;
}
/**
 * Tenant-level email provider settings with source information
 *
 * Extends EmailProviderSettings with per-field source tracking,
 * showing whether each value comes from instance, tenant, config, or default.
 */
interface TenantEmailProviderSettings extends EmailProviderSettings {
    /** Source of each field: "instance" | "tenant" | "config" | "default" */
    _sources: Record<string, string>;
}
/**
 * Request to update email provider settings
 *
 * All fields are optional - only provided fields will be updated.
 * Secret fields (passwords, client keys) are only updated if provided.
 */
interface UpdateEmailProviderSettingsRequest {
    enabled?: boolean;
    provider?: "smtp" | "sendgrid" | "mailgun" | "ses";
    from_address?: string;
    from_name?: string;
    smtp_host?: string;
    smtp_port?: number;
    smtp_username?: string;
    smtp_password?: string;
    smtp_tls?: boolean;
    sendgrid_api_key?: string;
    mailgun_api_key?: string;
    mailgun_domain?: string;
    ses_access_key?: string;
    ses_secret_key?: string;
    ses_region?: string;
}
/**
 * Response from testing email settings
 */
interface TestEmailSettingsResponse {
    success: boolean;
    message: string;
}
/**
 * OAuth provider configuration
 */
interface OAuthProvider {
    id: string;
    provider_name: string;
    display_name: string;
    enabled: boolean;
    client_id: string;
    client_secret?: string;
    redirect_url: string;
    scopes: string[];
    is_custom: boolean;
    authorization_url?: string;
    token_url?: string;
    user_info_url?: string;
    created_at: string;
    updated_at: string;
}
/**
 * Request to create a new OAuth provider
 */
interface CreateOAuthProviderRequest {
    provider_name: string;
    display_name: string;
    enabled: boolean;
    client_id: string;
    client_secret: string;
    redirect_url: string;
    scopes: string[];
    is_custom: boolean;
    authorization_url?: string;
    token_url?: string;
    user_info_url?: string;
}
/**
 * Response after creating an OAuth provider
 */
interface CreateOAuthProviderResponse {
    success: boolean;
    id: string;
    provider: string;
    message: string;
    created_at: string;
    updated_at: string;
}
/**
 * Request to update an OAuth provider
 */
interface UpdateOAuthProviderRequest {
    display_name?: string;
    enabled?: boolean;
    client_id?: string;
    client_secret?: string;
    redirect_url?: string;
    scopes?: string[];
    authorization_url?: string;
    token_url?: string;
    user_info_url?: string;
}
/**
 * Response after updating an OAuth provider
 */
interface UpdateOAuthProviderResponse {
    success: boolean;
    message: string;
}
/**
 * Response after deleting an OAuth provider
 */
interface DeleteOAuthProviderResponse {
    success: boolean;
    message: string;
}
/**
 * Response for listing OAuth providers
 */
interface ListOAuthProvidersResponse {
    providers: OAuthProvider[];
}
/**
 * Authentication settings configuration
 */
interface AuthSettings {
    enable_signup: boolean;
    require_email_verification: boolean;
    enable_magic_link: boolean;
    password_min_length: number;
    password_require_uppercase: boolean;
    password_require_lowercase: boolean;
    password_require_number: boolean;
    password_require_special: boolean;
    session_timeout_minutes: number;
    max_sessions_per_user: number;
    disable_dashboard_password_login: boolean;
    disable_app_password_login: boolean;
    /** Settings overridden by environment variables (read-only, cannot be modified via API) */
    _overrides?: Record<string, SettingOverride>;
}
/**
 * Request to update authentication settings
 */
interface UpdateAuthSettingsRequest {
    enable_signup?: boolean;
    require_email_verification?: boolean;
    enable_magic_link?: boolean;
    password_min_length?: number;
    password_require_uppercase?: boolean;
    password_require_lowercase?: boolean;
    password_require_number?: boolean;
    password_require_special?: boolean;
    session_timeout_minutes?: number;
    max_sessions_per_user?: number;
    disable_dashboard_password_login?: boolean;
    disable_app_password_login?: boolean;
}
/**
 * Response after updating authentication settings
 */
interface UpdateAuthSettingsResponse {
    success: boolean;
    message: string;
}
/**
 * Column definition for creating a table
 */
interface CreateColumnRequest {
    name: string;
    type: string;
    nullable?: boolean;
    primaryKey?: boolean;
    defaultValue?: string;
}
/**
 * Request to create a new database schema
 */
interface CreateSchemaRequest {
    name: string;
}
/**
 * Response after creating a schema
 */
interface CreateSchemaResponse {
    message: string;
    schema: string;
}
/**
 * Request to create a new table
 */
interface CreateTableRequest {
    schema: string;
    name: string;
    columns: CreateColumnRequest[];
}
/**
 * Response after creating a table
 */
interface CreateTableResponse {
    message: string;
    schema: string;
    table: string;
}
/**
 * Response after deleting a table
 */
interface DeleteTableResponse {
    message: string;
}
/**
 * Database schema information
 */
interface Schema {
    name: string;
    owner?: string;
}
/**
 * Response for listing schemas
 */
interface ListSchemasResponse {
    schemas: Schema[];
}
/**
 * Property definition within a JSONB schema
 */
interface JSONBProperty {
    /** Property type (string, number, boolean, object, array, null) */
    type: string;
    /** Human-readable description of the property */
    description?: string;
    /** Nested properties for object types */
    properties?: Record<string, JSONBProperty>;
    /** Item schema for array types */
    items?: JSONBProperty;
}
/**
 * Schema definition for a JSONB column
 * Allows AI agents to understand the structure of JSONB data
 */
interface JSONBSchema {
    /** Map of property names to their definitions */
    properties?: Record<string, JSONBProperty>;
    /** List of required property names */
    required?: string[];
}
/**
 * Table column information
 */
interface Column {
    name: string;
    type: string;
    nullable: boolean;
    default_value?: string;
    is_primary_key?: boolean;
    /** Column description from PostgreSQL comment */
    description?: string;
    /** JSONB schema if this is a JSONB/JSON column with schema annotation */
    jsonb_schema?: JSONBSchema;
}
/**
 * Database table information
 */
interface Table {
    schema: string;
    name: string;
    columns?: Column[];
}
/**
 * Response for listing tables
 */
interface ListTablesResponse {
    tables: Table[];
}
/**
 * Impersonation type
 */
type ImpersonationType = "user" | "anon" | "service";
/**
 * Target user information for impersonation
 */
interface ImpersonationTargetUser {
    id: string;
    email: string;
    role: string;
}
/**
 * Impersonation session information
 */
interface ImpersonationSession {
    id: string;
    admin_user_id: string;
    target_user_id: string | null;
    impersonation_type: ImpersonationType;
    target_role: string;
    reason: string;
    started_at: string;
    ended_at: string | null;
    is_active: boolean;
    ip_address: string | null;
    user_agent: string | null;
}
/**
 * Request to start impersonating a specific user
 */
interface ImpersonateUserRequest {
    target_user_id: string;
    reason: string;
}
/**
 * Request to start impersonating as anonymous user
 */
interface ImpersonateAnonRequest {
    reason: string;
}
/**
 * Request to start impersonating with service role
 */
interface ImpersonateServiceRequest {
    reason: string;
}
/**
 * Response after starting impersonation
 */
interface StartImpersonationResponse {
    session: ImpersonationSession;
    target_user: ImpersonationTargetUser | null;
    access_token: string;
    refresh_token: string;
    expires_in: number;
}
/**
 * Response after stopping impersonation
 */
interface StopImpersonationResponse {
    success: boolean;
    message: string;
}
/**
 * Response for getting current impersonation session
 */
interface GetImpersonationResponse {
    session: ImpersonationSession | null;
    target_user: ImpersonationTargetUser | null;
}
/**
 * Options for listing impersonation sessions
 */
interface ListImpersonationSessionsOptions {
    limit?: number;
    offset?: number;
    admin_user_id?: string;
    target_user_id?: string;
    impersonation_type?: ImpersonationType;
    is_active?: boolean;
}
/**
 * Response for listing impersonation sessions
 */
interface ListImpersonationSessionsResponse {
    sessions: ImpersonationSession[];
    total: number;
}
/**
 * Fit mode for image transformations
 * - cover: Resize to cover target dimensions, cropping if needed (default)
 * - contain: Resize to fit within target dimensions, letterboxing if needed
 * - fill: Stretch to exactly fill target dimensions
 * - inside: Resize to fit within target, only scale down
 * - outside: Resize to be at least as large as target
 */
type ImageFitMode = "cover" | "contain" | "fill" | "inside" | "outside";
/**
 * Output format for image transformations
 */
type ImageFormat = "webp" | "jpg" | "png" | "avif";
/**
 * Options for on-the-fly image transformations
 * Applied to storage downloads via query parameters
 */
interface TransformOptions {
    /** Target width in pixels (0 or undefined = auto based on height) */
    width?: number;
    /** Target height in pixels (0 or undefined = auto based on width) */
    height?: number;
    /** Output format (defaults to original format) */
    format?: ImageFormat;
    /** Output quality 1-100 (default: 80) */
    quality?: number;
    /** How to fit the image within target dimensions (default: cover) */
    fit?: ImageFitMode;
}
/**
 * CAPTCHA provider types supported by Fluxbase
 * - hcaptcha: Privacy-focused visual challenge
 * - recaptcha_v3: Google's invisible risk-based CAPTCHA
 * - turnstile: Cloudflare's invisible CAPTCHA
 * - cap: Self-hosted proof-of-work CAPTCHA (https://capjs.js.org/)
 */
type CaptchaProvider = "hcaptcha" | "recaptcha_v3" | "turnstile" | "cap";
/**
 * Public CAPTCHA configuration returned from the server
 * Used by clients to know which CAPTCHA provider to load
 */
interface CaptchaConfig {
    /** Whether CAPTCHA is enabled */
    enabled: boolean;
    /** CAPTCHA provider name */
    provider?: CaptchaProvider;
    /** Public site key for the CAPTCHA widget (hcaptcha, recaptcha, turnstile) */
    site_key?: string;
    /** Endpoints that require CAPTCHA verification */
    endpoints?: string[];
    /** Cap server URL - only present when provider is 'cap' */
    cap_server_url?: string;
}
/**
 * Request for pre-flight CAPTCHA check (adaptive trust)
 * Use this to determine if CAPTCHA is required before attempting auth
 */
interface CaptchaCheckRequest {
    /** Endpoint to check: signup, login, password_reset, magic_link */
    endpoint: "signup" | "login" | "password_reset" | "magic_link";
    /** Email address for trust lookup (optional) */
    email?: string;
    /** Device fingerprint for trust tracking (optional) */
    deviceFingerprint?: string;
    /** Trust token from a previous CAPTCHA verification (optional) */
    trustToken?: string;
}
/**
 * Response from pre-flight CAPTCHA check
 * Contains whether CAPTCHA is required and challenge tracking info
 */
interface CaptchaCheckResponse {
    /** Whether CAPTCHA verification is required */
    captcha_required: boolean;
    /** Reason for the decision (e.g., "trusted", "new_ip_address", "sensitive_action") */
    reason?: string;
    /** Trust score (0-100, higher means more trusted) */
    trust_score?: number;
    /** CAPTCHA provider (only if captcha_required=true) */
    provider?: CaptchaProvider;
    /** Public site key for CAPTCHA widget (only if captcha_required=true) */
    site_key?: string;
    /** Challenge ID to include in auth request */
    challenge_id: string;
    /** When the challenge expires (ISO 8601 format) */
    expires_at: string;
}
/**
 * Public OAuth provider information
 */
interface OAuthProviderPublic {
    /** Provider identifier (e.g., "google", "github") */
    provider: string;
    /** Display name for UI */
    display_name: string;
    /** Authorization URL to initiate OAuth flow */
    authorize_url: string;
}
/**
 * Public SAML provider information (for auth config response)
 */
interface SAMLProviderInfo {
    /** Provider identifier */
    provider: string;
    /** Display name for UI */
    display_name: string;
}
/**
 * Comprehensive authentication configuration
 * Returns all public auth settings from the server
 */
interface AuthConfig {
    /** Whether user signup is enabled */
    signup_enabled: boolean;
    /** Whether email verification is required after signup */
    require_email_verification: boolean;
    /** Whether magic link authentication is enabled */
    magic_link_enabled: boolean;
    /** Whether password login is enabled for app users */
    password_login_enabled: boolean;
    /** Whether MFA/2FA is available (always true, users opt-in) */
    mfa_available: boolean;
    /** Minimum password length requirement */
    password_min_length: number;
    /** Whether passwords must contain uppercase letters */
    password_require_uppercase: boolean;
    /** Whether passwords must contain lowercase letters */
    password_require_lowercase: boolean;
    /** Whether passwords must contain numbers */
    password_require_number: boolean;
    /** Whether passwords must contain special characters */
    password_require_special: boolean;
    /** Available OAuth providers for authentication */
    oauth_providers: OAuthProviderPublic[];
    /** Available SAML providers for enterprise SSO */
    saml_providers: SAMLProviderInfo[];
    /** CAPTCHA configuration */
    captcha: CaptchaConfig | null;
}
/**
 * Auth state change events
 */
type AuthChangeEvent = "SIGNED_IN" | "SIGNED_OUT" | "TOKEN_REFRESHED" | "USER_UPDATED" | "PASSWORD_RECOVERY" | "MFA_CHALLENGE_VERIFIED";
/**
 * Callback for auth state changes
 */
type AuthStateChangeCallback = (event: AuthChangeEvent, session: AuthSession | null) => void;
/**
 * Subscription object returned by onAuthStateChange
 */
interface AuthSubscription {
    /**
     * Unsubscribe from auth state changes
     */
    unsubscribe: () => void;
}
/**
 * Options for invoking an edge function
 */
interface FunctionInvokeOptions {
    /**
     * Request body to send to the function
     */
    body?: unknown;
    /**
     * Custom headers to include in the request
     */
    headers?: Record<string, string>;
    /**
     * HTTP method to use
     * @default 'POST'
     */
    method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
    /**
     * Namespace of the function to invoke
     * If not provided, the first function with the given name is used (alphabetically by namespace)
     */
    namespace?: string;
}
/**
 * Edge function metadata
 */
interface EdgeFunction {
    id: string;
    name: string;
    namespace: string;
    description?: string;
    code: string;
    version: number;
    enabled: boolean;
    timeout_seconds: number;
    memory_limit_mb: number;
    allow_net: boolean;
    allow_env: boolean;
    allow_read: boolean;
    allow_write: boolean;
    allow_unauthenticated: boolean;
    cron_schedule?: string;
    created_at: string;
    updated_at: string;
    created_by?: string;
}
/**
 * Request to create a new edge function
 */
interface CreateFunctionRequest {
    name: string;
    description?: string;
    code: string;
    enabled?: boolean;
    timeout_seconds?: number;
    memory_limit_mb?: number;
    allow_net?: boolean;
    allow_env?: boolean;
    allow_read?: boolean;
    allow_write?: boolean;
    allow_unauthenticated?: boolean;
    cron_schedule?: string;
}
/**
 * Request to update an existing edge function
 */
interface UpdateFunctionRequest {
    description?: string;
    code?: string;
    enabled?: boolean;
    timeout_seconds?: number;
    memory_limit_mb?: number;
    allow_net?: boolean;
    allow_env?: boolean;
    allow_read?: boolean;
    allow_write?: boolean;
    allow_unauthenticated?: boolean;
    cron_schedule?: string;
}
/**
 * Edge function execution record
 */
interface EdgeFunctionExecution {
    id: string;
    function_id: string;
    trigger_type: string;
    status: "success" | "error";
    status_code?: number;
    duration_ms?: number;
    result?: string;
    logs?: string;
    error_message?: string;
    executed_at: string;
    completed_at?: string;
}
/**
 * Function specification for bulk sync operations
 */
interface FunctionSpec {
    name: string;
    description?: string;
    code: string;
    /** If true, code is already bundled and server will skip bundling */
    is_pre_bundled?: boolean;
    /** Original source code (for debugging when pre-bundled) */
    original_code?: string;
    /** Source directory for resolving relative imports during bundling (used by syncWithBundling) */
    sourceDir?: string;
    /** Additional paths to search for node_modules during bundling (used by syncWithBundling) */
    nodePaths?: string[];
    enabled?: boolean;
    timeout_seconds?: number;
    memory_limit_mb?: number;
    allow_net?: boolean;
    allow_env?: boolean;
    allow_read?: boolean;
    allow_write?: boolean;
    allow_unauthenticated?: boolean;
    is_public?: boolean;
    cron_schedule?: string;
}
/**
 * Options for syncing functions
 */
interface SyncFunctionsOptions {
    /** Namespace to sync functions to (defaults to "default") */
    namespace?: string;
    /** Functions to sync */
    functions: FunctionSpec[];
    /** Options for sync operation */
    options?: {
        /** Delete functions in namespace that are not in the sync payload */
        delete_missing?: boolean;
        /** Preview changes without applying them */
        dry_run?: boolean;
    };
}
/**
 * Sync operation error details
 */
interface SyncError {
    /** Name of the function that failed */
    function: string;
    /** Error message */
    error: string;
    /** Operation that failed */
    action: "create" | "update" | "delete" | "bundle";
}
/**
 * Result of a function sync operation
 */
interface SyncFunctionsResult {
    /** Status message */
    message: string;
    /** Namespace that was synced */
    namespace: string;
    /** Summary counts */
    summary: {
        created: number;
        updated: number;
        deleted: number;
        unchanged: number;
        errors: number;
    };
    /** Detailed results */
    details: {
        created: string[];
        updated: string[];
        deleted: string[];
        unchanged: string[];
    };
    /** Errors encountered */
    errors: SyncError[];
    /** Whether this was a dry run */
    dry_run: boolean;
}
/**
 * Job function metadata
 */
interface JobFunction {
    id: string;
    name: string;
    namespace: string;
    description?: string;
    code?: string;
    original_code?: string;
    is_bundled: boolean;
    bundle_error?: string;
    enabled: boolean;
    schedule?: string;
    timeout_seconds: number;
    memory_limit_mb: number;
    max_retries: number;
    progress_timeout_seconds: number;
    allow_net: boolean;
    allow_env: boolean;
    allow_read: boolean;
    allow_write: boolean;
    require_role?: string;
    version: number;
    created_by?: string;
    created_at: string;
    updated_at: string;
}
/**
 * Job execution status
 */
type JobStatus = "pending" | "running" | "completed" | "failed" | "cancelled" | "timeout";
/**
 * Job execution record
 */
interface Job {
    id: string;
    namespace: string;
    job_function_id?: string;
    job_name: string;
    status: JobStatus;
    payload?: unknown;
    result?: unknown;
    error?: string;
    logs?: string;
    priority: number;
    max_duration_seconds?: number;
    progress_timeout_seconds?: number;
    progress_percent?: number;
    progress_message?: string;
    progress_data?: unknown;
    max_retries: number;
    retry_count: number;
    worker_id?: string;
    created_by?: string;
    user_role?: string;
    user_email?: string;
    created_at: string;
    started_at?: string;
    completed_at?: string;
    scheduled_at?: string;
    last_progress_at?: string;
    /** Estimated completion time (computed, only for running jobs with progress > 0) */
    estimated_completion_at?: string;
    /** Estimated seconds remaining (computed, only for running jobs with progress > 0) */
    estimated_seconds_left?: number;
}
/**
 * User context for submitting jobs on behalf of another user.
 * Only available when using service_role authentication.
 */
interface OnBehalfOf {
    /** User ID (UUID) to submit the job as */
    user_id: string;
    /** Optional email address of the user */
    user_email?: string;
    /** Optional role of the user (defaults to "authenticated") */
    user_role?: string;
}
/**
 * Job statistics
 */
interface JobStats {
    namespace?: string;
    pending: number;
    running: number;
    completed: number;
    failed: number;
    cancelled: number;
    total: number;
}
/**
 * Job worker information
 */
interface JobWorker {
    id: string;
    hostname: string;
    status: "active" | "idle" | "dead";
    current_jobs: number;
    total_completed: number;
    started_at: string;
    last_heartbeat_at: string;
}
/**
 * Job function specification for sync operations
 */
interface JobFunctionSpec {
    name: string;
    description?: string;
    code: string;
    /** If true, code is already bundled and server will skip bundling */
    is_pre_bundled?: boolean;
    /** Original source code (for debugging when pre-bundled) */
    original_code?: string;
    /** Source directory for resolving relative imports during bundling (used by syncWithBundling) */
    sourceDir?: string;
    /** Additional paths to search for node_modules during bundling (used by syncWithBundling) */
    nodePaths?: string[];
    enabled?: boolean;
    schedule?: string;
    timeout_seconds?: number;
    memory_limit_mb?: number;
    max_retries?: number;
    progress_timeout_seconds?: number;
    allow_net?: boolean;
    allow_env?: boolean;
    allow_read?: boolean;
    allow_write?: boolean;
    require_role?: string;
}
/**
 * Options for syncing job functions
 */
interface SyncJobsOptions {
    namespace: string;
    functions?: JobFunctionSpec[];
    options?: {
        delete_missing?: boolean;
        dry_run?: boolean;
    };
}
/**
 * Result of a job sync operation
 */
interface SyncJobsResult {
    message: string;
    namespace: string;
    summary: {
        created: number;
        updated: number;
        deleted: number;
        unchanged: number;
        errors: number;
    };
    details: {
        created: string[];
        updated: string[];
        deleted: string[];
        unchanged: string[];
    };
    errors: SyncError[];
    dry_run: boolean;
}
/**
 * Database migration metadata
 */
interface Migration {
    id: string;
    namespace: string;
    name: string;
    description?: string;
    up_sql: string;
    down_sql?: string;
    version: number;
    status: "pending" | "applied" | "failed" | "rolled_back";
    created_by?: string;
    applied_by?: string;
    created_at: string;
    updated_at: string;
    applied_at?: string;
    rolled_back_at?: string;
}
/**
 * Request to create a new migration
 */
interface CreateMigrationRequest {
    namespace?: string;
    name: string;
    description?: string;
    up_sql: string;
    down_sql?: string;
}
/**
 * Request to update a migration (only if pending)
 */
interface UpdateMigrationRequest {
    description?: string;
    up_sql?: string;
    down_sql?: string;
}
/**
 * Migration execution record (audit log)
 */
interface MigrationExecution {
    id: string;
    migration_id: string;
    action: "apply" | "rollback";
    status: "success" | "failed";
    duration_ms?: number;
    error_message?: string;
    logs?: string;
    executed_at: string;
    executed_by?: string;
}
/**
 * Request to apply a migration
 */
interface ApplyMigrationRequest {
    namespace?: string;
}
/**
 * Request to rollback a migration
 */
interface RollbackMigrationRequest {
    namespace?: string;
}
/**
 * Request to apply pending migrations
 */
interface ApplyPendingRequest {
    namespace?: string;
}
/**
 * Options for syncing migrations
 */
interface SyncMigrationsOptions {
    /** Update pending migrations if SQL content changed */
    update_if_changed?: boolean;
    /** Automatically apply new migrations after sync */
    auto_apply?: boolean;
    /** Preview changes without applying them */
    dry_run?: boolean;
}
/**
 * Result of a migration sync operation
 */
interface SyncMigrationsResult {
    /** Status message */
    message: string;
    /** Namespace that was synced */
    namespace: string;
    /** Summary counts */
    summary: {
        created: number;
        updated: number;
        unchanged: number;
        skipped: number;
        applied: number;
        errors: number;
    };
    /** Detailed results */
    details: {
        created: string[];
        updated: string[];
        unchanged: string[];
        skipped: string[];
        applied: string[];
        errors: string[];
    };
    /** Whether this was a dry run */
    dry_run: boolean;
    /** Warning messages */
    warnings?: string[];
}
/**
 * AI provider type
 */
type AIProviderType = "openai" | "azure" | "ollama";
/**
 * AI provider configuration
 */
interface AIProvider {
    id: string;
    name: string;
    display_name: string;
    provider_type: AIProviderType;
    is_default: boolean;
    /** When true, this provider is explicitly used for embeddings. null means auto (follow default provider) */
    use_for_embeddings: boolean | null;
    /** Embedding model for this provider. null means use provider-specific default */
    embedding_model: string | null;
    enabled: boolean;
    config: Record<string, string>;
    /** True if provider was configured via environment variables or fluxbase.yaml */
    from_config?: boolean;
    /** @deprecated Use from_config instead */
    read_only?: boolean;
    created_at: string;
    updated_at: string;
}
/**
 * Request to create an AI provider
 * Note: config values can be strings, numbers, or booleans - they will be converted to strings automatically
 */
interface CreateAIProviderRequest {
    name: string;
    display_name: string;
    provider_type: AIProviderType;
    is_default?: boolean;
    enabled?: boolean;
    /** Embedding model for this provider. null or omit to use provider-specific default */
    embedding_model?: string | null;
    config: Record<string, string | number | boolean>;
}
/**
 * Request to update an AI provider
 * Note: config values can be strings, numbers, or booleans - they will be converted to strings automatically
 */
interface UpdateAIProviderRequest {
    display_name?: string;
    config?: Record<string, string | number | boolean>;
    enabled?: boolean;
    /** Embedding model for this provider. null to reset to provider-specific default */
    embedding_model?: string | null;
}
/**
 * AI chatbot summary (list view)
 */
interface AIChatbotSummary {
    id: string;
    name: string;
    namespace: string;
    description?: string;
    enabled: boolean;
    is_public: boolean;
    allowed_tables: string[];
    allowed_operations: string[];
    allowed_schemas: string[];
    version: number;
    source: string;
    created_at: string;
    updated_at: string;
}
/**
 * AI chatbot full details
 */
interface AIChatbot extends AIChatbotSummary {
    code: string;
    original_code?: string;
    max_tokens: number;
    temperature: number;
    provider_id?: string;
    persist_conversations: boolean;
    conversation_ttl_hours: number;
    max_conversation_turns: number;
    rate_limit_per_minute: number;
    daily_request_limit: number;
    daily_token_budget: number;
    allow_unauthenticated: boolean;
}
/**
 * Chatbot specification for sync operations
 */
interface ChatbotSpec {
    name: string;
    description?: string;
    code: string;
    original_code?: string;
    is_pre_bundled?: boolean;
    enabled?: boolean;
    allowed_tables?: string[];
    allowed_operations?: string[];
    allowed_schemas?: string[];
    max_tokens?: number;
    temperature?: number;
    persist_conversations?: boolean;
    conversation_ttl_hours?: number;
    max_conversation_turns?: number;
    rate_limit_per_minute?: number;
    daily_request_limit?: number;
    daily_token_budget?: number;
    allow_unauthenticated?: boolean;
    is_public?: boolean;
}
/**
 * Options for syncing chatbots
 */
interface SyncChatbotsOptions {
    namespace?: string;
    chatbots?: ChatbotSpec[];
    options?: {
        delete_missing?: boolean;
        dry_run?: boolean;
    };
}
/**
 * Result of a chatbot sync operation
 */
interface SyncChatbotsResult {
    message: string;
    namespace: string;
    summary: {
        created: number;
        updated: number;
        deleted: number;
        unchanged: number;
        errors: number;
    };
    details: {
        created: string[];
        updated: string[];
        deleted: string[];
        unchanged: string[];
    };
    errors: SyncError[];
    dry_run: boolean;
}
/**
 * Response from chatbot lookup by name (smart namespace resolution)
 */
interface AIChatbotLookupResponse {
    /** The chatbot if found (unique or resolved from default namespace) */
    chatbot?: AIChatbotSummary;
    /** True if multiple chatbots with this name exist in different namespaces */
    ambiguous: boolean;
    /** List of namespaces where the chatbot exists (when ambiguous) */
    namespaces?: string[];
    /** Error message if lookup failed */
    error?: string;
}
/**
 * AI chat message role
 */
type AIChatMessageRole = "user" | "assistant" | "system" | "tool";
/**
 * AI chat message for WebSocket
 */
interface AIChatClientMessage {
    type: "start_chat" | "message" | "cancel";
    chatbot?: string;
    namespace?: string;
    conversation_id?: string;
    content?: string;
    impersonate_user_id?: string;
}
/**
 * AI chat server message
 */
interface AIChatServerMessage {
    type: "chat_started" | "progress" | "content" | "query_result" | "tool_result" | "done" | "error" | "cancelled";
    conversation_id?: string;
    message_id?: string;
    chatbot?: string;
    step?: string;
    message?: string;
    delta?: string;
    query?: string;
    summary?: string;
    row_count?: number;
    data?: Record<string, unknown>[];
    usage?: AIUsageStats;
    /** Intent rules that fired for this turn (Ask 5). Empty when none match. */
    matched_intent_rules?: AIMatchedIntentRule[];
    /** Per-user daily quota snapshot at turn end (Ask 2). Omitted when no limits configured. */
    daily_quota?: AIDailyQuotaSnapshot;
    error?: string;
    code?: string;
}
/**
 * AI token usage statistics
 */
interface AIUsageStats {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens?: number;
    /**
     * Subset of prompt_tokens served from the provider's prompt cache
     * (OpenAI automatic prefix caching, Anthropic prompt caching). 0 when
     * caching didn't fire or the provider doesn't report it. (Ask 4)
     */
    cached_tokens?: number;
}
/**
 * One intent rule that fired for a user message (Ask 5). Mirrors the
 * chatbot's @fluxbase:intent-rules entry plus the specific keyword that matched.
 */
interface AIMatchedIntentRule {
    keyword: string;
    required_table?: string;
    forbidden_table?: string;
    required_tool?: string;
    forbidden_tool?: string;
}
/**
 * Per-user daily quota snapshot returned in the done event (Ask 2) and by
 * fluxbase.ai.getUsage(). Counts are best-effort in-memory; they reset on
 * server restart and are per-instance in multi-replica deployments.
 */
interface AIDailyQuotaSnapshot {
    requests: AIQuota;
    tokens: AIQuota;
    /** RFC3339 timestamp of when the counters roll over to zero. */
    resets_at?: string;
}
/** One half of AIDailyQuotaSnapshot. */
interface AIQuota {
    used: number;
    /** Configured limit; 0 means unlimited. */
    limit: number;
}
/**
 * AI conversation summary
 */
interface AIConversation {
    id: string;
    chatbot_id: string;
    user_id?: string;
    session_id?: string;
    title?: string;
    status: "active" | "archived";
    turn_count: number;
    total_prompt_tokens: number;
    total_completion_tokens: number;
    created_at: string;
    updated_at: string;
    last_message_at: string;
    expires_at?: string;
}
/**
 * AI conversation message
 */
interface AIConversationMessage {
    id: string;
    conversation_id: string;
    role: AIChatMessageRole;
    content: string;
    tool_call_id?: string;
    tool_name?: string;
    executed_sql?: string;
    sql_result_summary?: string;
    sql_row_count?: number;
    sql_error?: string;
    sql_duration_ms?: number;
    prompt_tokens?: number;
    completion_tokens?: number;
    created_at: string;
    sequence_number: number;
}
/**
 * User's conversation summary (list view)
 */
interface AIUserConversationSummary {
    id: string;
    chatbot: string;
    namespace: string;
    title?: string;
    preview: string;
    message_count: number;
    created_at: string;
    updated_at: string;
}
/**
 * Query result data in a user message
 */
interface AIUserQueryResult {
    query?: string;
    summary: string;
    row_count: number;
    data?: Record<string, unknown>[];
}
/**
 * Token usage stats in a user message
 */
interface AIUserUsageStats {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens?: number;
}
/**
 * User's message in conversation detail view
 */
interface AIUserMessage {
    id: string;
    role: "user" | "assistant";
    content: string;
    timestamp: string;
    query_results?: AIUserQueryResult[];
    usage?: AIUserUsageStats;
}
/**
 * User's conversation detail with messages
 */
interface AIUserConversationDetail {
    id: string;
    chatbot: string;
    namespace: string;
    title?: string;
    created_at: string;
    updated_at: string;
    messages: AIUserMessage[];
}
/**
 * Options for listing user conversations
 */
interface ListConversationsOptions {
    /** Filter by chatbot name */
    chatbot?: string;
    /** Filter by namespace */
    namespace?: string;
    /** Number of conversations to return (default: 50, max: 100) */
    limit?: number;
    /** Offset for pagination */
    offset?: number;
}
/**
 * Result of listing user conversations
 */
interface ListConversationsResult {
    conversations: AIUserConversationSummary[];
    total: number;
    has_more: boolean;
}
/**
 * Options for updating a conversation
 */
interface UpdateConversationOptions {
    /** New title for the conversation */
    title: string;
}
/**
 * Knowledge base summary
 */
interface KnowledgeBaseSummary {
    id: string;
    name: string;
    namespace: string;
    description: string;
    enabled: boolean;
    document_count: number;
    total_chunks: number;
    embedding_model: string;
    created_at: string;
    updated_at: string;
}
/**
 * Knowledge base full details
 */
interface KnowledgeBase extends KnowledgeBaseSummary {
    embedding_dimensions: number;
    chunk_size: number;
    chunk_overlap: number;
    chunk_strategy: string;
    source: string;
    created_by?: string;
}
/**
 * Request to create a knowledge base
 */
interface CreateKnowledgeBaseRequest {
    name: string;
    namespace?: string;
    description?: string;
    embedding_model?: string;
    embedding_dimensions?: number;
    chunk_size?: number;
    chunk_overlap?: number;
    chunk_strategy?: string;
}
/**
 * Request to update a knowledge base
 */
interface UpdateKnowledgeBaseRequest {
    name?: string;
    description?: string;
    embedding_model?: string;
    embedding_dimensions?: number;
    chunk_size?: number;
    chunk_overlap?: number;
    chunk_strategy?: string;
    enabled?: boolean;
}
/**
 * Document status
 */
type DocumentStatus = "pending" | "processing" | "indexed" | "failed";
/**
 * Document in a knowledge base
 */
interface KnowledgeBaseDocument {
    id: string;
    knowledge_base_id: string;
    title: string;
    source_url?: string;
    source_type?: string;
    mime_type: string;
    content_hash: string;
    chunk_count: number;
    status: DocumentStatus;
    error_message?: string;
    metadata?: Record<string, string>;
    tags?: string[];
    created_at: string;
    updated_at: string;
}
/**
 * Request to add a document
 */
interface AddDocumentRequest {
    title?: string;
    content: string;
    source?: string;
    mime_type?: string;
    metadata?: Record<string, string>;
}
/**
 * Response after adding a document
 */
interface AddDocumentResponse {
    document_id: string;
    status: string;
    message: string;
}
/**
 * Response after uploading a document file
 */
interface UploadDocumentResponse {
    document_id: string;
    status: string;
    message: string;
    filename: string;
    extracted_length: number;
    mime_type: string;
}
/**
 * Chatbot-knowledge base link
 */
interface ChatbotKnowledgeBaseLink {
    id: string;
    chatbot_id: string;
    knowledge_base_id: string;
    enabled: boolean;
    max_chunks: number;
    similarity_threshold: number;
    priority: number;
    created_at: string;
}
/**
 * Request to link a knowledge base to a chatbot
 */
interface LinkKnowledgeBaseRequest {
    knowledge_base_id: string;
    priority?: number;
    max_chunks?: number;
    similarity_threshold?: number;
}
/**
 * Request to update a chatbot-knowledge base link
 */
interface UpdateChatbotKnowledgeBaseRequest {
    priority?: number;
    max_chunks?: number;
    similarity_threshold?: number;
    enabled?: boolean;
}
/**
 * Search result from knowledge base
 */
interface KnowledgeBaseSearchResult {
    chunk_id: string;
    document_id: string;
    document_title: string;
    knowledge_base_name?: string;
    content: string;
    similarity: number;
    metadata?: Record<string, unknown>;
}
/**
 * Request to search a knowledge base
 */
interface SearchKnowledgeBaseRequest {
    query: string;
    max_chunks?: number;
    threshold?: number;
}
/**
 * Response from knowledge base search
 */
interface SearchKnowledgeBaseResponse {
    results: KnowledgeBaseSearchResult[];
    count: number;
    query: string;
}
/**
 * Entity type classification (matching backend EntityType)
 */
type EntityType = "person" | "organization" | "location" | "concept" | "product" | "event" | "table" | "url" | "api_endpoint" | "datetime" | "code_reference" | "error" | "other";
/**
 * Extracted entity from knowledge base documents
 */
interface Entity {
    id: string;
    knowledge_base_id: string;
    entity_type: EntityType;
    name: string;
    canonical_name: string;
    aliases: string[];
    metadata: Record<string, unknown>;
    document_count?: number;
    created_at: string;
    updated_at: string;
}
/**
 * Relationship between two entities
 */
interface EntityRelationship {
    id: string;
    knowledge_base_id: string;
    source_entity_id: string;
    target_entity_id: string;
    relationship_type: string;
    confidence?: number;
    metadata: Record<string, unknown>;
    created_at: string;
    source_entity?: Entity;
    target_entity?: Entity;
}
/**
 * Knowledge graph data with entities and relationships
 */
interface KnowledgeGraphData {
    entities: Entity[];
    relationships: EntityRelationship[];
    entity_count: number;
    relationship_count: number;
}
/**
 * Request to update a document
 */
interface UpdateDocumentRequest {
    title?: string;
    tags?: string[];
    metadata?: Record<string, string>;
}
/**
 * Request to delete documents by filter
 */
interface DeleteDocumentsByFilterRequest {
    tags?: string[];
    metadata?: Record<string, string>;
    metadata_filter?: Record<string, string>;
}
/**
 * Response from deleting documents by filter
 */
interface DeleteDocumentsByFilterResponse {
    deleted_count: number;
}
/**
 * Column information for a table
 */
interface TableColumn {
    name: string;
    data_type: string;
    is_nullable: boolean;
    default_value?: string;
    is_primary_key: boolean;
    is_foreign_key: boolean;
    is_unique: boolean;
    max_length?: number;
    position: number;
    /** Column description from PostgreSQL comment */
    description?: string;
    /** JSONB schema if this is a JSONB/JSON column with schema annotation */
    jsonb_schema?: JSONBSchema;
}
/**
 * Foreign key information for a table
 */
interface TableForeignKey {
    name: string;
    column_name: string;
    referenced_schema: string;
    referenced_table: string;
    referenced_column: string;
    on_delete: string;
    on_update: string;
}
/**
 * Index information for a table
 */
interface TableIndex {
    name: string;
    columns: string[];
    is_unique: boolean;
    is_primary: boolean;
}
/**
 * Detailed table information including columns
 */
interface TableDetails {
    schema: string;
    name: string;
    type: string;
    columns: TableColumn[];
    primary_key: string[];
    foreign_keys: TableForeignKey[];
    indexes: TableIndex[];
    rls_enabled: boolean;
}
/**
 * System health status response from public /health endpoint
 * Services are represented as booleans indicating availability
 */
interface HealthResponse {
    status: string;
    services: {
        database: boolean;
        realtime: boolean;
        database_size?: string;
    };
    timestamp?: string;
}
/**
 * Storage bucket information (admin API)
 */
interface AdminBucket {
    id: string;
    name: string;
    public: boolean;
    allowed_mime_types: string[] | null;
    max_file_size: number | null;
    created_at: string;
    updated_at: string;
}
/**
 * Response from listing buckets (admin API)
 */
interface AdminListBucketsResponse {
    buckets: AdminBucket[];
}
/**
 * Storage object information (admin API)
 */
interface AdminStorageObject {
    id: string;
    bucket: string;
    path: string;
    mime_type: string;
    size: number;
    metadata: Record<string, unknown> | null;
    owner_id: string | null;
    created_at: string;
    updated_at: string;
}
/**
 * Response from listing objects (admin API)
 */
interface AdminListObjectsResponse {
    bucket: string;
    objects: AdminStorageObject[] | null;
    prefixes: string[];
    truncated: boolean;
}
/**
 * Base Fluxbase response type (Supabase-compatible)
 * Returns either `{ data, error: null }` on success or `{ data: null, error }` on failure
 */
type FluxbaseResponse<T> = {
    data: T;
    error: null;
} | {
    data: null;
    error: Error;
};
/**
 * Response type for operations that don't return data (void operations)
 */
type VoidResponse = {
    error: Error | null;
};
/**
 * Weak password information (Supabase-compatible)
 */
interface WeakPassword {
    reasons: string[];
}
/**
 * Auth response with user and session (Supabase-compatible)
 */
type AuthResponseData = {
    user: User;
    session: AuthSession | null;
    weakPassword?: WeakPassword;
};
/**
 * Fluxbase auth response
 */
type FluxbaseAuthResponse = FluxbaseResponse<AuthResponseData>;
/**
 * User response
 */
type UserResponse = FluxbaseResponse<{
    user: User;
}>;
/**
 * Session response
 */
type SessionResponse = FluxbaseResponse<{
    session: AuthSession;
}>;
/**
 * Generic data response
 */
type DataResponse<T> = FluxbaseResponse<T>;
/**
 * RPC procedure summary for listings
 */
interface RPCProcedureSummary {
    id: string;
    name: string;
    namespace: string;
    description?: string;
    allowed_tables: string[];
    allowed_schemas: string[];
    max_execution_time_seconds: number;
    require_role?: string;
    is_public: boolean;
    enabled: boolean;
    version: number;
    source: string;
    created_at: string;
    updated_at: string;
}
/**
 * Full RPC procedure details
 */
interface RPCProcedure extends RPCProcedureSummary {
    sql_query: string;
    original_code?: string;
    input_schema?: Record<string, string>;
    output_schema?: Record<string, string>;
    created_by?: string;
}
/**
 * RPC execution status
 */
type RPCExecutionStatus = "pending" | "running" | "completed" | "failed" | "cancelled" | "timeout";
/**
 * RPC execution record
 */
interface RPCExecution {
    id: string;
    procedure_id?: string;
    procedure_name: string;
    namespace: string;
    status: RPCExecutionStatus;
    input_params?: Record<string, unknown>;
    result?: unknown;
    error_message?: string;
    rows_returned?: number;
    duration_ms?: number;
    user_id?: string;
    user_role?: string;
    user_email?: string;
    is_async: boolean;
    created_at: string;
    started_at?: string;
    completed_at?: string;
}
/**
 * RPC invocation response
 */
interface RPCInvokeResponse<T = unknown> {
    execution_id: string;
    status: RPCExecutionStatus;
    result?: T;
    rows_returned?: number;
    duration_ms?: number;
    error?: string;
}
/**
 * Execution log entry (shared by jobs, RPC, and functions)
 */
interface ExecutionLog {
    /** Unique log entry ID */
    id: number;
    /** ID of the execution (job ID, RPC execution ID, or function execution ID) */
    execution_id: string;
    /** Line number within the execution log */
    line_number: number;
    /** Log level (debug, info, warn, error) */
    level: string;
    /** Log message content */
    message: string;
    /** Timestamp of the log entry */
    timestamp: string;
    /** Additional structured fields */
    fields?: Record<string, unknown>;
}
/**
 * RPC execution log entry
 * @deprecated Use ExecutionLog instead
 */
type RPCExecutionLog = ExecutionLog;
/**
 * RPC procedure specification for sync operations
 */
interface RPCProcedureSpec {
    name: string;
    code: string;
    description?: string;
    enabled?: boolean;
}
/**
 * Options for syncing RPC procedures
 */
interface SyncRPCOptions {
    namespace?: string;
    procedures?: RPCProcedureSpec[];
    options?: {
        delete_missing?: boolean;
        dry_run?: boolean;
    };
}
/**
 * Result of RPC sync operation
 */
interface SyncRPCResult {
    message: string;
    namespace: string;
    summary: {
        created: number;
        updated: number;
        deleted: number;
        unchanged: number;
        errors: number;
    };
    details: {
        created: string[];
        updated: string[];
        deleted: string[];
        unchanged: string[];
    };
    errors: Array<{
        procedure: string;
        error: string;
    }>;
    dry_run: boolean;
}
/**
 * Options for updating an RPC procedure
 */
interface UpdateRPCProcedureRequest {
    description?: string;
    enabled?: boolean;
    is_public?: boolean;
    require_role?: string;
    max_execution_time_seconds?: number;
    allowed_tables?: string[];
    allowed_schemas?: string[];
}
/**
 * Filters for listing RPC executions
 */
interface RPCExecutionFilters {
    namespace?: string;
    procedure?: string;
    status?: RPCExecutionStatus;
    user_id?: string;
    limit?: number;
    offset?: number;
}
/**
 * Vector distance metric for similarity search
 * - l2: Euclidean distance (L2 norm) - lower is more similar
 * - cosine: Cosine distance - lower is more similar (1 - cosine similarity)
 * - inner_product: Negative inner product - lower is more similar
 */
type VectorMetric = "l2" | "cosine" | "inner_product";
/**
 * Options for vector similarity ordering
 */
interface VectorOrderOptions {
    /** The vector to compare against */
    vector: number[];
    /** Distance metric to use */
    metric?: VectorMetric;
}
/**
 * Request for vector embedding generation
 */
interface EmbedRequest {
    /** Text to embed (single) */
    text?: string;
    /** Multiple texts to embed */
    texts?: string[];
    /** Embedding model to use (defaults to configured model) */
    model?: string;
    /** Provider ID to use for embedding (admin-only, defaults to configured embedding provider) */
    provider?: string;
}
/**
 * Response from vector embedding generation
 */
interface EmbedResponse {
    /** Generated embeddings (one per input text) */
    embeddings: number[][];
    /** Model used for embedding */
    model: string;
    /** Dimensions of the embeddings */
    dimensions: number;
    /** Token usage information */
    usage?: {
        prompt_tokens: number;
        total_tokens: number;
    };
}
/**
 * Options for vector search via the convenience endpoint
 */
interface VectorSearchOptions {
    /** Table to search in */
    table: string;
    /** Vector column to search */
    column: string;
    /** Text query to search for (will be auto-embedded) */
    query?: string;
    /** Direct vector input (alternative to text query) */
    vector?: number[];
    /** Distance metric to use */
    metric?: VectorMetric;
    /** Minimum similarity threshold (0-1 for cosine, varies for others) */
    match_threshold?: number;
    /** Maximum number of results */
    match_count?: number;
    /** Columns to select (default: all) */
    select?: string;
    /** Additional filters to apply */
    filters?: QueryFilter[];
}
/**
 * Result from vector search
 */
interface VectorSearchResult<T = Record<string, unknown>> {
    /** Matched records */
    data: T[];
    /** Distance scores for each result */
    distances: number[];
    /** Embedding model used (if query text was embedded) */
    model?: string;
}
/**
 * Log level for execution logs
 */
type ExecutionLogLevel = "debug" | "info" | "warn" | "error";
/**
 * Execution type for log subscriptions
 */
type ExecutionType = "function" | "job" | "rpc";
/**
 * Execution log event received from realtime subscription
 */
interface ExecutionLogEvent {
    /** Unique execution ID */
    execution_id: string;
    /** Type of execution */
    execution_type: ExecutionType;
    /** Line number in the execution log */
    line_number: number;
    /** Log level */
    level: ExecutionLogLevel;
    /** Log message content */
    message: string;
    /** Timestamp of the log entry */
    timestamp: string;
    /** Additional fields */
    fields?: Record<string, unknown>;
}
/**
 * Callback for execution log events
 */
type ExecutionLogCallback = (log: ExecutionLogEvent) => void;
/**
 * Configuration for execution log subscription
 */
interface ExecutionLogConfig {
    /** Execution ID to subscribe to */
    execution_id: string;
    /** Type of execution (function, job, rpc) */
    type?: ExecutionType;
}
/**
 * Branch status
 */
type BranchStatus = "creating" | "ready" | "migrating" | "error" | "deleting" | "deleted";
/**
 * Branch type
 */
type BranchType = "main" | "preview" | "persistent";
/**
 * Data clone mode when creating a branch
 */
type DataCloneMode = "schema_only" | "full_clone" | "seed_data";
/**
 * Database branch information
 */
interface Branch {
    /** Unique branch identifier */
    id: string;
    /** Display name of the branch */
    name: string;
    /** URL-safe slug for the branch */
    slug: string;
    /** Actual database name */
    database_name: string;
    /** Current status of the branch */
    status: BranchStatus;
    /** Type of branch */
    type: BranchType;
    /** Parent branch ID (for feature branches) */
    parent_branch_id?: string;
    /** How data was cloned when branch was created */
    data_clone_mode: DataCloneMode;
    /** GitHub PR number if this is a preview branch */
    github_pr_number?: number;
    /** GitHub PR URL */
    github_pr_url?: string;
    /** GitHub repository (owner/repo) */
    github_repo?: string;
    /** Error message if status is 'error' */
    error_message?: string;
    /** User ID who created the branch */
    created_by?: string;
    /** When the branch was created */
    created_at: string;
    /** When the branch was last updated */
    updated_at: string;
    /** When the branch will automatically expire */
    expires_at?: string;
}
/**
 * Options for creating a new branch
 */
interface CreateBranchOptions {
    /** Parent branch to clone from (defaults to main) */
    parentBranchId?: string;
    /** How to clone data */
    dataCloneMode?: DataCloneMode;
    /** Branch type */
    type?: BranchType;
    /** GitHub PR number (for preview branches) */
    githubPRNumber?: number;
    /** GitHub PR URL */
    githubPRUrl?: string;
    /** GitHub repository (owner/repo) */
    githubRepo?: string;
    /** Duration until branch expires (e.g., "24h", "7d") */
    expiresIn?: string;
}
/**
 * Options for listing branches
 */
interface ListBranchesOptions {
    /** Filter by branch status */
    status?: BranchStatus;
    /** Filter by branch type */
    type?: BranchType;
    /** Filter by GitHub repository */
    githubRepo?: string;
    /** Only show branches created by the current user */
    mine?: boolean;
    /** Maximum number of branches to return */
    limit?: number;
    /** Offset for pagination */
    offset?: number;
}
/**
 * Response from listing branches
 */
interface ListBranchesResponse {
    branches: Branch[];
    total: number;
    limit: number;
    offset: number;
}
/**
 * Branch activity log entry
 */
interface BranchActivity {
    /** Activity ID */
    id: string;
    /** Branch ID */
    branch_id: string;
    /** Action performed */
    action: string;
    /** Activity status */
    status: "success" | "failed" | "pending";
    /** Additional details */
    details?: Record<string, unknown>;
    /** User who performed the action */
    executed_by?: string;
    /** When the activity occurred */
    created_at: string;
}
/**
 * Connection pool statistics
 */
interface BranchPoolStats {
    /** Branch slug */
    slug: string;
    /** Number of active connections */
    active_connections: number;
    /** Number of idle connections */
    idle_connections: number;
    /** Total connections created */
    total_connections: number;
    /** When the pool was created */
    created_at: string;
}
/**
 * Request to enable realtime on a table
 */
interface EnableRealtimeRequest {
    /** Schema name (default: 'public') */
    schema: string;
    /** Table name */
    table: string;
    /** Events to track (default: ['INSERT', 'UPDATE', 'DELETE']) */
    events?: ("INSERT" | "UPDATE" | "DELETE")[];
    /** Columns to exclude from notifications */
    exclude?: string[];
}
/**
 * Response after enabling realtime on a table
 */
interface EnableRealtimeResponse {
    /** Schema name */
    schema: string;
    /** Table name */
    table: string;
    /** Events being tracked */
    events: string[];
    /** Name of the created trigger */
    trigger_name: string;
    /** Columns excluded from notifications */
    exclude?: string[];
}
/**
 * Status of realtime for a table
 */
interface RealtimeTableStatus {
    /** Registry ID */
    id?: number;
    /** Schema name */
    schema: string;
    /** Table name */
    table: string;
    /** Whether realtime is enabled */
    realtime_enabled: boolean;
    /** Events being tracked */
    events: string[];
    /** Columns excluded from notifications */
    excluded_columns?: string[];
    /** When realtime was enabled */
    created_at?: string;
    /** When configuration was last updated */
    updated_at?: string;
}
/**
 * Response listing realtime-enabled tables
 */
interface ListRealtimeTablesResponse {
    /** List of tables with realtime enabled */
    tables: RealtimeTableStatus[];
    /** Total count */
    count: number;
}
/**
 * Request to update realtime configuration
 */
interface UpdateRealtimeConfigRequest {
    /** Events to track */
    events?: ("INSERT" | "UPDATE" | "DELETE")[];
    /** Columns to exclude from notifications */
    exclude?: string[];
}
/**
 * Tenant status
 */
type TenantStatus = "creating" | "active" | "deleting" | "error";
/**
 * Tenant in the system
 */
interface Tenant {
    /** Unique identifier for the tenant */
    id: string;
    /** URL-friendly identifier (e.g., "acme-corp") */
    slug: string;
    /** Display name */
    name: string;
    /** Database name (null = uses main database, for backward compatibility) */
    db_name?: string | null;
    /** Current status of the tenant */
    status: TenantStatus;
    /** Whether this is the default tenant */
    is_default: boolean;
    /** Arbitrary metadata */
    metadata?: Record<string, unknown>;
    /** Creation timestamp */
    created_at: string;
    /** Last update timestamp */
    updated_at?: string;
    /** Soft delete timestamp */
    deleted_at?: string | null;
}
/**
 * Tenant admin assignment
 * With database-per-tenant, admins are assigned to tenants (no roles needed)
 */
interface TenantAdminAssignment {
    /** Unique identifier for the assignment */
    id: string;
    /** Tenant ID */
    tenant_id: string;
    /** User ID */
    user_id: string;
    /** Creation timestamp */
    created_at: string;
}
/**
 * Admin with user details (returned by listAdmins)
 */
interface TenantAdminWithUser extends TenantAdminAssignment {
    /** User's email */
    email: string;
    /** User's dashboard role */
    dashboard_role: string;
}
/**
 * Tenant with user's role (for "my tenants" endpoint)
 */
interface TenantWithRole extends Tenant {
    /** Current user's role in this tenant (always tenant_admin with database-per-tenant) */
    my_role: "tenant_admin";
}
/**
 * Options for creating a tenant
 */
interface CreateTenantOptions {
    /** URL-friendly identifier (lowercase letters, numbers, hyphens) */
    slug: string;
    /** Display name */
    name: string;
    /** Optional metadata */
    metadata?: Record<string, unknown>;
}
/**
 * Options for updating a tenant
 */
interface UpdateTenantOptions {
    /** New display name */
    name?: string;
    /** Updated metadata */
    metadata?: Record<string, unknown>;
}
/**
 * Options for assigning an admin to a tenant
 */
interface AssignAdminOptions {
    /** User ID to assign as admin */
    user_id: string;
}
/**
 * Service key for API authentication
 * Each tenant has their own service_keys table in their database
 */
interface ServiceKey {
    /** Unique identifier */
    id: string;
    /** Display name */
    name: string;
    /** Description */
    description?: string;
    /** Key prefix (first 16 chars, for identification) */
    key_prefix: string;
    /** Key type: anon (anonymous access) or service (elevated privileges) */
    key_type: "anon" | "service";
    /** Permission scopes */
    scopes: string[];
    /** Allowed table namespaces */
    allowed_namespaces?: string[];
    /** Whether the key is enabled */
    enabled: boolean;
    /** Rate limit per minute */
    rate_limit_per_minute?: number;
    /** Rate limit per hour */
    rate_limit_per_hour?: number;
    /** User who created the key */
    created_by?: string;
    /** Creation timestamp */
    created_at: string;
    /** Last usage timestamp */
    last_used_at?: string;
    /** Expiration timestamp */
    expires_at?: string;
    /** Revocation timestamp */
    revoked_at?: string;
    /** Deprecation timestamp (for key rotation) */
    deprecated_at?: string;
    /** Grace period end for deprecated keys */
    grace_period_ends_at?: string;
    /** ID of replacement key (after rotation) */
    replaced_by?: string;
}
/**
 * Service key with the full key value (only returned on creation)
 */
interface ServiceKeyWithKey extends ServiceKey {
    /** The full key value - only shown once at creation */
    key: string;
}
/**
 * Options for creating a service key
 */
interface CreateServiceKeyRequest {
    /** Display name */
    name: string;
    /** Description */
    description?: string;
    /** Key type: anon or service */
    key_type: "anon" | "service";
    /** Permission scopes (default: ['*'] for service, ['read'] for anon) */
    scopes?: string[];
    /** Allowed table namespaces */
    allowed_namespaces?: string[];
    /** Rate limit per minute */
    rate_limit_per_minute?: number;
    /** Rate limit per hour */
    rate_limit_per_hour?: number;
    /** Expiration timestamp */
    expires_at?: string;
}
/**
 * Options for updating a service key
 */
interface UpdateServiceKeyRequest {
    /** New display name */
    name?: string;
    /** New description */
    description?: string;
    /** New permission scopes */
    scopes?: string[];
    /** New allowed namespaces */
    allowed_namespaces?: string[];
    /** Enable/disable the key */
    enabled?: boolean;
    /** New rate limit per minute */
    rate_limit_per_minute?: number;
    /** New rate limit per hour */
    rate_limit_per_hour?: number;
}
/**
 * Options for revoking a service key
 */
interface RevokeServiceKeyRequest {
    /** Reason for revocation */
    reason?: string;
}
/**
 * Options for deprecating a service key
 */
interface DeprecateServiceKeyRequest {
    /** Reason for deprecation */
    reason?: string;
    /** Grace period in hours before key is disabled */
    grace_period_hours?: number;
}

/**
 * Realtime subscriptions using WebSockets
 */

declare class RealtimeChannel {
    private ws;
    private url;
    private token;
    private channelName;
    private callbacks;
    private presenceCallbacks;
    private broadcastCallbacks;
    private executionLogCallbacks;
    private subscriptionConfigs;
    private subscriptionIds;
    private executionLogConfig;
    private _presenceState;
    private myPresenceKey;
    private config;
    private reconnectAttempts;
    private maxReconnectAttempts;
    private reconnectDelay;
    private shouldReconnect;
    private heartbeatInterval;
    private pendingAcks;
    private messageIdCounter;
    private onTokenRefreshNeeded;
    private isRefreshingToken;
    constructor(url: string, channelName: string, token?: string | null, config?: RealtimeChannelConfig);
    /**
     * Set callback to request a token refresh when connection fails due to auth
     * @internal
     */
    setTokenRefreshCallback(callback: () => Promise<string | null>): void;
    /**
     * Listen to postgres_changes with optional row-level filtering
     *
     * @param event - 'postgres_changes'
     * @param config - Configuration including optional filter
     * @param callback - Function to call when changes occur
     * @returns This channel for chaining
     *
     * @example
     * ```typescript
     * channel.on('postgres_changes', {
     *   event: '*',
     *   schema: 'public',
     *   table: 'jobs',
     *   filter: 'created_by=eq.user123'
     * }, (payload) => {
     *   console.log('Job updated:', payload)
     * })
     * ```
     */
    on(event: "postgres_changes", config: PostgresChangesConfig, callback: RealtimeCallback): this;
    /**
     * Listen to a specific event type (backwards compatibility)
     *
     * @param event - The event type (INSERT, UPDATE, DELETE, or '*' for all)
     * @param callback - The callback function
     * @returns This channel for chaining
     *
     * @example
     * ```typescript
     * channel.on('INSERT', (payload) => {
     *   console.log('New record inserted:', payload.new_record)
     * })
     * ```
     */
    on(event: "INSERT" | "UPDATE" | "DELETE" | "*", callback: RealtimeCallback): this;
    /**
     * Listen to broadcast messages
     *
     * @param event - 'broadcast'
     * @param config - Configuration with event name
     * @param callback - Function to call when broadcast received
     * @returns This channel for chaining
     *
     * @example
     * ```typescript
     * channel.on('broadcast', { event: 'cursor-pos' }, (payload) => {
     *   console.log('Cursor moved:', payload)
     * })
     * ```
     */
    on(event: "broadcast", config: {
        event: string;
    }, callback: BroadcastCallback): this;
    /**
     * Listen to presence events
     *
     * @param event - 'presence'
     * @param config - Configuration with event type (sync, join, leave)
     * @param callback - Function to call when presence changes
     * @returns This channel for chaining
     *
     * @example
     * ```typescript
     * channel.on('presence', { event: 'sync' }, (payload) => {
     *   console.log('Presence synced:', payload)
     * })
     * ```
     */
    on(event: "presence", config: {
        event: "sync" | "join" | "leave";
    }, callback: PresenceCallback): this;
    /**
     * Listen to execution log events
     *
     * @param event - 'execution_log'
     * @param config - Configuration with execution_id and optional type
     * @param callback - Function to call when log entries are received
     * @returns This channel for chaining
     *
     * @example
     * ```typescript
     * channel.on('execution_log', { execution_id: 'abc123', type: 'function' }, (log) => {
     *   console.log(`[${log.level}] ${log.message}`)
     * })
     * ```
     */
    on(event: "execution_log", config: {
        execution_id: string;
        type?: ExecutionType;
    }, callback: ExecutionLogCallback): this;
    /**
     * Remove a callback
     */
    off(event: "INSERT" | "UPDATE" | "DELETE" | "*", callback: RealtimeCallback): this;
    /**
     * Subscribe to the channel
     * @param callback - Optional status callback (Supabase-compatible)
     * @param _timeout - Optional timeout in milliseconds (currently unused)
     */
    subscribe(callback?: (status: "SUBSCRIBED" | "CHANNEL_ERROR" | "TIMED_OUT" | "CLOSED", err?: Error) => void, _timeout?: number): this;
    /**
     * Unsubscribe from the channel
     * @param timeout - Optional timeout in milliseconds
     * @returns Promise resolving to status string (Supabase-compatible)
     */
    unsubscribe(timeout?: number): Promise<"ok" | "timed out" | "error">;
    /**
     * Send a broadcast message to all subscribers on this channel
     *
     * @param message - Broadcast message with type, event, and payload
     * @returns Promise resolving to status
     *
     * @example
     * ```typescript
     * await channel.send({
     *   type: 'broadcast',
     *   event: 'cursor-pos',
     *   payload: { x: 100, y: 200 }
     * })
     * ```
     */
    send(message: BroadcastMessage): Promise<"ok" | "error">;
    /**
     * Track user presence on this channel
     *
     * @param state - Presence state to track
     * @returns Promise resolving to status
     *
     * @example
     * ```typescript
     * await channel.track({
     *   user_id: 123,
     *   status: 'online'
     * })
     * ```
     */
    track(state: PresenceState): Promise<"ok" | "error">;
    /**
     * Stop tracking presence on this channel
     *
     * @returns Promise resolving to status
     *
     * @example
     * ```typescript
     * await channel.untrack()
     * ```
     */
    untrack(): Promise<"ok" | "error">;
    /**
     * Get current presence state for all users on this channel
     *
     * @returns Current presence state
     *
     * @example
     * ```typescript
     * const state = channel.presenceState()
     * console.log('Online users:', Object.keys(state).length)
     * ```
     */
    presenceState(): Record<string, PresenceState[]>;
    /**
     * Check if the current token is expired or about to expire
     */
    private isTokenExpired;
    /**
     * Internal: Connect to WebSocket
     */
    private connect;
    /**
     * Internal: Actually establish the WebSocket connection
     */
    private connectWithToken;
    /**
     * Internal: Disconnect WebSocket
     */
    private disconnect;
    /**
     * Internal: Send a message
     */
    private sendMessage;
    /**
     * Internal: Handle incoming message
     */
    private handleMessage;
    /**
     * Internal: Handle execution log message
     */
    private handleExecutionLog;
    /**
     * Internal: Handle broadcast message
     */
    private handleBroadcastMessage;
    /**
     * Internal: Handle presence message
     */
    private handlePresenceMessage;
    /**
     * Internal: Handle postgres_changes message
     */
    private handlePostgresChanges;
    /**
     * Internal: Start heartbeat interval
     */
    private startHeartbeat;
    /**
     * Internal: Stop heartbeat interval
     */
    private stopHeartbeat;
    /**
     * Update the authentication token on an existing connection
     * Sends an access_token message to the server to update auth context
     * On failure, silently triggers a reconnect
     *
     * @param token - The new JWT access token
     * @internal
     */
    updateToken(token: string | null): void;
    /**
     * Internal: Attempt to reconnect
     */
    private attemptReconnect;
}
declare class FluxbaseRealtime {
    private url;
    private token;
    private channels;
    private tokenRefreshCallback;
    constructor(url: string, token?: string | null);
    /**
     * Set callback to request a token refresh when connections fail due to auth
     * This callback should refresh the auth token and return the new access token
     * @internal
     */
    setTokenRefreshCallback(callback: () => Promise<string | null>): void;
    /**
     * Create or get a channel with optional configuration
     *
     * @param channelName - Channel name (e.g., 'table:public.products')
     * @param config - Optional channel configuration
     * @returns RealtimeChannel instance
     *
     * @example
     * ```typescript
     * const channel = realtime.channel('room-1', {
     *   broadcast: { self: true, ack: true },
     *   presence: { key: 'user-123' }
     * })
     * ```
     */
    channel(channelName: string, config?: RealtimeChannelConfig): RealtimeChannel;
    /**
     * Remove a specific channel
     *
     * @param channel - The channel to remove
     * @returns Promise resolving to status
     *
     * @example
     * ```typescript
     * const channel = realtime.channel('room-1')
     * await realtime.removeChannel(channel)
     * ```
     */
    removeChannel(channel: RealtimeChannel): Promise<"ok" | "error">;
    /**
     * Remove all channels
     */
    removeAllChannels(): void;
    /**
     * Update auth token for all channels
     * Updates both the stored token for new channels and propagates
     * the token to all existing connected channels.
     *
     * @param token - The new auth token
     */
    setAuth(token: string | null): void;
    /**
     * Create an execution log subscription channel
     *
     * This provides a cleaner API for subscribing to execution logs
     * (functions, jobs, or RPC procedures).
     *
     * @param executionId - The execution ID to subscribe to
     * @param type - The type of execution ('function', 'job', 'rpc')
     * @returns ExecutionLogsChannel instance with fluent API
     *
     * @example
     * ```typescript
     * const channel = client.realtime.executionLogs('exec-123', 'function')
     *   .onLog((log) => {
     *     console.log(`[${log.level}] ${log.message}`)
     *   })
     *   .subscribe()
     * ```
     */
    executionLogs(executionId: string, type?: ExecutionType): ExecutionLogsChannel;
}
/**
 * Specialized channel for execution log subscriptions
 * Provides a cleaner API than the generic RealtimeChannel
 */
declare class ExecutionLogsChannel {
    private channel;
    private executionId;
    private executionType;
    private logCallbacks;
    constructor(url: string, executionId: string, type: ExecutionType, token: string | null, tokenRefreshCallback: (() => Promise<string | null>) | null);
    /**
     * Register a callback for log events
     *
     * @param callback - Function to call when log entries are received
     * @returns This channel for chaining
     *
     * @example
     * ```typescript
     * channel.onLog((log) => {
     *   console.log(`[${log.level}] Line ${log.line_number}: ${log.message}`)
     * })
     * ```
     */
    onLog(callback: ExecutionLogCallback): this;
    /**
     * Subscribe to execution logs
     *
     * @param callback - Optional status callback
     * @returns Promise that resolves when subscribed
     *
     * @example
     * ```typescript
     * await channel.subscribe()
     * ```
     */
    subscribe(callback?: (status: "SUBSCRIBED" | "CHANNEL_ERROR" | "TIMED_OUT" | "CLOSED", err?: Error) => void): this;
    /**
     * Unsubscribe from execution logs
     *
     * @returns Promise resolving to status
     *
     * @example
     * ```typescript
     * await channel.unsubscribe()
     * ```
     */
    unsubscribe(): Promise<"ok" | "timed out" | "error">;
}

/**
 * HTTP client for making requests to the Fluxbase API
 */

interface FetchOptions {
    method: HttpMethod;
    headers?: Record<string, string>;
    body?: unknown;
    timeout?: number;
    /** Skip automatic token refresh on 401 (used for auth endpoints) */
    skipAutoRefresh?: boolean;
}
/**
 * Response with headers included (for count queries)
 */
interface FetchResponseWithHeaders<T> {
    data: T;
    headers: Headers;
    status: number;
}
/** Callback type for automatic token refresh on 401 errors */
type RefreshTokenCallback = () => Promise<boolean>;
/** Callback type for modifying headers before each request */
type BeforeRequestCallback = (headers: Record<string, string>) => void;
declare class FluxbaseFetch {
    private baseUrl;
    private defaultHeaders;
    private timeout;
    private debug;
    private refreshTokenCallback;
    private isRefreshing;
    private refreshPromise;
    private anonKey;
    private beforeRequestCallback;
    constructor(baseUrl: string, options?: {
        headers?: Record<string, string>;
        timeout?: number;
        debug?: boolean;
    });
    getBaseUrl(): string;
    getDefaultHeaders(): Record<string, string>;
    /**
     * Register a callback to refresh the token when a 401 error occurs
     * The callback should return true if refresh was successful, false otherwise
     */
    setRefreshTokenCallback(callback: RefreshTokenCallback | null): void;
    /**
     * Register a callback to be called before every request.
     * The callback receives the headers object and can modify it in place.
     * This is useful for dynamically injecting headers at request time.
     */
    setBeforeRequestCallback(callback: BeforeRequestCallback | null): void;
    /**
     * Set the anon key for fallback authentication
     * When setAuthToken(null) is called, the Authorization header will be
     * restored to use this anon key instead of being deleted
     */
    setAnonKey(key: string): void;
    /**
     * Update the authorization header
     * When token is null, restores to anon key if available
     */
    setAuthToken(token: string | null): void;
    /**
     * Set a custom header on all requests
     */
    setHeader(name: string, value: string): void;
    /**
     * Remove a custom header
     */
    removeHeader(name: string): void;
    /**
     * Make an HTTP request
     */
    request<T = unknown>(path: string, options: FetchOptions): Promise<T>;
    /**
     * Full request implementation returning response with headers, status, and data.
     * Used by both requestInternal and requestWithHeadersInternal.
     */
    private requestFull;
    /**
     * Handle token refresh with deduplication
     * Multiple concurrent requests that fail with 401 will share the same refresh operation
     */
    private handleTokenRefresh;
    /**
     * Execute the actual token refresh
     */
    private executeRefresh;
    /**
     * Internal request implementation with retry capability
     */
    private requestInternal;
    /**
     * Internal request implementation that returns response with headers
     */
    private requestWithHeadersInternal;
    /**
     * GET request
     */
    get<T = unknown>(path: string, options?: Omit<FetchOptions, "method">): Promise<T>;
    /**
     * GET request that returns response with headers (for count queries)
     */
    getWithHeaders<T = unknown>(path: string, options?: Omit<FetchOptions, "method">): Promise<FetchResponseWithHeaders<T>>;
    /**
     * POST request that returns response with headers (for POST-based queries with count)
     */
    postWithHeaders<T = unknown>(path: string, body?: unknown, options?: Omit<FetchOptions, "method" | "body">): Promise<FetchResponseWithHeaders<T>>;
    /**
     * Make an HTTP request and return response with headers
     */
    requestWithHeaders<T = unknown>(path: string, options: FetchOptions): Promise<FetchResponseWithHeaders<T>>;
    /**
     * POST request
     */
    post<T = unknown>(path: string, body?: unknown, options?: Omit<FetchOptions, "method" | "body">): Promise<T>;
    /**
     * PUT request
     */
    put<T = unknown>(path: string, body?: unknown, options?: Omit<FetchOptions, "method" | "body">): Promise<T>;
    /**
     * PATCH request
     */
    patch<T = unknown>(path: string, body?: unknown, options?: Omit<FetchOptions, "method" | "body">): Promise<T>;
    /**
     * DELETE request
     */
    delete<T = unknown>(path: string, options?: Omit<FetchOptions, "method">): Promise<T>;
    /**
     * HEAD request
     */
    head(path: string, options?: Omit<FetchOptions, "method">): Promise<Headers>;
    /**
     * GET request that returns response as Blob (for file downloads)
     */
    getBlob(path: string, options?: Omit<FetchOptions, "method">): Promise<Blob>;
}

/**
 * Authentication module for Fluxbase SDK
 */

declare class FluxbaseAuth {
    private fetch;
    private session;
    private persist;
    private autoRefresh;
    private refreshTimer;
    private stateChangeListeners;
    private storage;
    constructor(fetch: FluxbaseFetch, autoRefresh?: boolean, persist?: boolean);
    /**
     * Get the current session (Supabase-compatible)
     * Returns the session from the client-side cache without making a network request
     */
    getSession(): Promise<FluxbaseResponse<{
        session: AuthSession | null;
    }>>;
    /**
     * Get the current user (Supabase-compatible)
     * Returns the user from the client-side session without making a network request
     * For server-side validation, use getCurrentUser() instead
     */
    getUser(): Promise<FluxbaseResponse<{
        user: User | null;
    }>>;
    /**
     * Get the current access token
     */
    getAccessToken(): string | null;
    /**
     * Listen to auth state changes (Supabase-compatible)
     * @param callback - Function called when auth state changes
     * @returns Object containing subscription data
     *
     * @example
     * ```typescript
     * const { data: { subscription } } = client.auth.onAuthStateChange((event, session) => {
     *   console.log('Auth event:', event, session)
     * })
     *
     * // Later, to unsubscribe:
     * subscription.unsubscribe()
     * ```
     */
    onAuthStateChange(callback: AuthStateChangeCallback): {
        data: {
            subscription: AuthSubscription;
        };
    };
    /**
     * Start the automatic token refresh timer
     * This is called automatically when autoRefresh is enabled and a session exists
     * Only works in browser environments
     */
    startAutoRefresh(): void;
    /**
     * Stop the automatic token refresh timer
     * Call this when you want to disable auto-refresh without signing out
     */
    stopAutoRefresh(): void;
    /**
     * Sign in with email and password (Supabase-compatible)
     * Returns { user, session } if successful, or SignInWith2FAResponse if 2FA is required
     */
    signIn(credentials: SignInCredentials): Promise<FluxbaseResponse<AuthResponseData | SignInWith2FAResponse>>;
    /**
     * Sign in with email and password (Supabase-compatible)
     * Alias for signIn() to maintain compatibility with common authentication patterns
     * Returns { user, session } if successful, or SignInWith2FAResponse if 2FA is required
     */
    signInWithPassword(credentials: SignInCredentials): Promise<FluxbaseResponse<AuthResponseData | SignInWith2FAResponse>>;
    /**
     * Sign up with email and password (Supabase-compatible)
     * Returns session when email confirmation is disabled
     * Returns null session when email confirmation is required
     */
    signUp(credentials: SignUpCredentials): Promise<FluxbaseAuthResponse>;
    /**
     * Get CAPTCHA configuration from the server
     * Use this to determine which CAPTCHA provider to load and configure
     * @returns Promise with CAPTCHA configuration (provider, site key, enabled endpoints)
     */
    getCaptchaConfig(): Promise<DataResponse<CaptchaConfig>>;
    /**
     * Check if CAPTCHA is required for an authentication action (adaptive trust)
     *
     * This pre-flight check evaluates trust signals (known IP, device, previous CAPTCHA)
     * to determine if CAPTCHA verification is needed. Use this before showing auth forms
     * to provide a better user experience for trusted users.
     *
     * @param request - Check request with endpoint and optional trust signals
     * @returns Promise with whether CAPTCHA is required and challenge tracking info
     *
     * @example
     * ```typescript
     * // Check if CAPTCHA is needed for login
     * const { data, error } = await client.auth.checkCaptcha({
     *   endpoint: 'login',
     *   email: 'user@example.com'
     * });
     *
     * if (data?.captcha_required) {
     *   // Show CAPTCHA widget using data.provider and data.site_key
     *   const captchaToken = await showCaptchaWidget(data.provider, data.site_key);
     *
     *   // Include challenge_id and captcha token in sign in
     *   await client.auth.signIn({
     *     email: 'user@example.com',
     *     password: 'password',
     *     captchaToken,
     *     challengeId: data.challenge_id
     *   });
     * } else {
     *   // No CAPTCHA needed - trusted user
     *   await client.auth.signIn({
     *     email: 'user@example.com',
     *     password: 'password',
     *     challengeId: data?.challenge_id // Still include challenge_id
     *   });
     * }
     * ```
     */
    checkCaptcha(request: CaptchaCheckRequest): Promise<DataResponse<CaptchaCheckResponse>>;
    /**
     * Get comprehensive authentication configuration from the server
     * Returns all public auth settings including signup status, OAuth providers,
     * SAML providers, password requirements, and CAPTCHA config in a single request.
     *
     * Use this to:
     * - Conditionally render signup forms based on signup_enabled
     * - Display available OAuth/SAML provider buttons
     * - Show password requirements to users
     * - Configure CAPTCHA widgets
     *
     * @returns Promise with complete authentication configuration
     * @example
     * ```typescript
     * const { data, error } = await client.auth.getAuthConfig();
     * if (data) {
     *   console.log('Signup enabled:', data.signup_enabled);
     *   console.log('OAuth providers:', data.oauth_providers);
     *   console.log('Password min length:', data.password_min_length);
     * }
     * ```
     */
    getAuthConfig(): Promise<DataResponse<AuthConfig>>;
    /**
     * Sign out the current user
     */
    signOut(): Promise<VoidResponse>;
    /**
     * Refresh the session (Supabase-compatible)
     * Returns a new session with refreshed tokens
     */
    refreshSession(): Promise<FluxbaseResponse<{
        user: User;
        session: AuthSession;
    }>>;
    /**
     * Refresh the session (Supabase-compatible alias)
     * Alias for refreshSession() to maintain compatibility with Supabase naming
     * Returns a new session with refreshed tokens
     */
    refreshToken(): Promise<FluxbaseResponse<{
        user: User;
        session: AuthSession;
    }>>;
    /**
     * Get the current user from the server
     */
    getCurrentUser(): Promise<UserResponse>;
    /**
     * Update the current user (Supabase-compatible)
     * @param attributes - User attributes to update (email, password, data for metadata)
     */
    updateUser(attributes: UpdateUserAttributes): Promise<UserResponse>;
    /**
     * Set the session manually (Supabase-compatible)
     * Useful for restoring a session from storage or SSR scenarios
     * @param session - Object containing access_token and refresh_token
     * @returns Promise with session data
     */
    setSession(session: {
        access_token: string;
        refresh_token: string;
    }): Promise<FluxbaseAuthResponse>;
    /**
     * Setup 2FA for the current user (Supabase-compatible)
     * Enrolls a new MFA factor and returns TOTP details
     * @param issuer - Optional custom issuer name for the QR code (e.g., "MyApp"). If not provided, uses server default.
     * @returns Promise with factor id, type, and TOTP setup details
     */
    setup2FA(issuer?: string): Promise<DataResponse<TwoFactorSetupResponse>>;
    /**
     * Enable 2FA after verifying the TOTP code (Supabase-compatible)
     * Verifies the TOTP code and returns new tokens with MFA session
     * @param code - TOTP code from authenticator app
     * @returns Promise with access_token, refresh_token, and user
     */
    enable2FA(code: string): Promise<DataResponse<TwoFactorEnableResponse>>;
    /**
     * Disable 2FA for the current user (Supabase-compatible)
     * Unenrolls the MFA factor
     * @param password - User password for confirmation
     * @returns Promise with unenrolled factor id
     */
    disable2FA(password: string): Promise<DataResponse<TwoFactorDisableResponse>>;
    /**
     * Check 2FA status for the current user (Supabase-compatible)
     * Lists all enrolled MFA factors
     * @returns Promise with all factors and TOTP factors
     */
    get2FAStatus(): Promise<DataResponse<TwoFactorStatusResponse>>;
    /**
     * Verify 2FA code during login (Supabase-compatible)
     * Call this after signIn returns requires_2fa: true
     * @param request - User ID and TOTP code
     * @returns Promise with access_token, refresh_token, and user
     */
    verify2FA(request: TwoFactorVerifyRequest): Promise<DataResponse<TwoFactorLoginResponse>>;
    /**
     * Send password reset email (Supabase-compatible)
     * Sends a password reset link to the provided email address
     * @param email - Email address to send reset link to
     * @param options - Optional configuration including redirect URL and CAPTCHA token
     * @returns Promise with OTP-style response
     */
    sendPasswordReset(email: string, options?: {
        redirectTo?: string;
        captchaToken?: string;
    }): Promise<DataResponse<PasswordResetResponse>>;
    /**
     * Supabase-compatible alias for sendPasswordReset()
     * @param email - Email address to send reset link to
     * @param options - Optional redirect and CAPTCHA configuration
     * @returns Promise with OTP-style response
     */
    resetPasswordForEmail(email: string, options?: {
        redirectTo?: string;
        captchaToken?: string;
    }): Promise<DataResponse<PasswordResetResponse>>;
    /**
     * Verify password reset token
     * Check if a password reset token is valid before allowing password reset
     * @param token - Password reset token to verify
     */
    verifyResetToken(token: string): Promise<DataResponse<VerifyResetTokenResponse>>;
    /**
     * Reset password with token (Supabase-compatible)
     * Complete the password reset process with a valid token
     * @param token - Password reset token
     * @param newPassword - New password to set
     * @returns Promise with user and new session
     */
    resetPassword(token: string, newPassword: string): Promise<DataResponse<ResetPasswordResponse>>;
    /**
     * Send magic link for passwordless authentication (Supabase-compatible)
     * @param email - Email address to send magic link to
     * @param options - Optional configuration for magic link
     * @returns Promise with OTP-style response
     */
    sendMagicLink(email: string, options?: MagicLinkOptions): Promise<DataResponse<MagicLinkResponse>>;
    /**
     * Verify magic link token and sign in
     * @param token - Magic link token from email
     */
    verifyMagicLink(token: string): Promise<FluxbaseAuthResponse>;
    /**
     * Sign in anonymously
     * Creates a temporary anonymous user session
     */
    signInAnonymously(): Promise<FluxbaseAuthResponse>;
    /**
     * Get list of enabled OAuth providers
     */
    getOAuthProviders(): Promise<DataResponse<OAuthProvidersResponse>>;
    /**
     * Get OAuth authorization URL for a provider
     * @param provider - OAuth provider name (e.g., 'google', 'github')
     * @param options - Optional OAuth configuration
     */
    getOAuthUrl(provider: string, options?: OAuthOptions): Promise<DataResponse<OAuthUrlResponse>>;
    /**
     * Exchange OAuth authorization code for session
     * This is typically called in your OAuth callback handler
     * @param code - Authorization code from OAuth callback
     * @param state - State parameter from OAuth callback (for CSRF protection)
     */
    exchangeCodeForSession(code: string, state?: string): Promise<FluxbaseAuthResponse>;
    /**
     * Convenience method to initiate OAuth sign-in
     * Redirects the user to the OAuth provider's authorization page
     * @param provider - OAuth provider name (e.g., 'google', 'github')
     * @param options - Optional OAuth configuration
     */
    signInWithOAuth(provider: string, options?: OAuthOptions): Promise<DataResponse<{
        provider: string;
        url: string;
    }>>;
    /**
     * Get OAuth logout URL for a provider
     * Use this to get the logout URL without automatically redirecting
     * @param provider - OAuth provider name (e.g., 'google', 'github')
     * @param options - Optional logout configuration
     * @returns Promise with OAuth logout response including redirect URL if applicable
     *
     * @example
     * ```typescript
     * const { data, error } = await client.auth.getOAuthLogoutUrl('google')
     * if (!error && data.redirect_url) {
     *   // Redirect user to complete logout at provider
     *   window.location.href = data.redirect_url
     * }
     * ```
     */
    getOAuthLogoutUrl(provider: string, options?: OAuthLogoutOptions): Promise<DataResponse<OAuthLogoutResponse>>;
    /**
     * Sign out with OAuth provider logout
     * Revokes tokens at the OAuth provider and optionally redirects for OIDC logout
     * @param provider - OAuth provider name (e.g., 'google', 'github')
     * @param options - Optional logout configuration
     * @returns Promise with OAuth logout response
     *
     * @example
     * ```typescript
     * // This will revoke tokens and redirect to provider's logout page if supported
     * await client.auth.signOutWithOAuth('google', {
     *   redirect_url: 'https://myapp.com/logged-out'
     * })
     * ```
     */
    signOutWithOAuth(provider: string, options?: OAuthLogoutOptions): Promise<DataResponse<OAuthLogoutResponse>>;
    /**
     * Get provider OAuth tokens for calling external APIs
     *
     * Retrieves the stored OAuth tokens for a provider (e.g., Google, GitHub) that
     * the user has previously authenticated with. Use these tokens to call provider
     * APIs directly (e.g., Google Drive API).
     *
     * The access_token is automatically refreshed if it has expired or is about to expire.
     *
     * @param provider - OAuth provider name (e.g., 'google', 'github')
     * @returns Promise with provider tokens (access_token, refresh_token, etc.)
     *
     * @example
     * ```typescript
     * // Get Google tokens to call Google Drive API
     * const { data, error } = await client.auth.getProviderToken('google')
     *
     * if (error) {
     *   if (error.error_code === 'oauth_token_not_found') {
     *     // User needs to sign in with Google first
     *     window.location.href = error.authorize_url
     *   }
     *   return
     * }
     *
     * // Use the access token to call Google Drive API
     * const response = await fetch('https://www.googleapis.com/drive/v3/files', {
     *   headers: {
     *     'Authorization': `Bearer ${data.access_token}`
     *   }
     * })
     * const files = await response.json()
     * ```
     *
     * @example
     * ```typescript
     * // Check token expiry before making API calls
     * const { data } = await client.auth.getProviderToken('google')
     *
     * if (data.expires_in < 60) {
     *   console.warn('Token expires soon, consider caching and refreshing')
     * }
     *
     * // Token expiry is also available as ISO timestamp
     * console.log('Token expires at:', data.token_expiry)
     * ```
     */
    getProviderToken(provider: string): Promise<DataResponse<ProviderTokenResponse>>;
    /**
     * Sign in with OTP (One-Time Password) - Supabase-compatible
     * Sends a one-time password via email or SMS for passwordless authentication
     * @param credentials - Email or phone number and optional configuration
     * @returns Promise with OTP-style response
     */
    signInWithOtp(credentials: SignInWithOtpCredentials): Promise<DataResponse<OTPResponse>>;
    /**
     * Verify OTP (One-Time Password) - Supabase-compatible
     * Verify OTP tokens for various authentication flows
     * @param params - OTP verification parameters including token and type
     * @returns Promise with user and session if successful
     */
    verifyOtp(params: VerifyOtpParams): Promise<FluxbaseAuthResponse>;
    /**
     * Resend OTP (One-Time Password) - Supabase-compatible
     * Resend OTP code when user doesn't receive it
     * @param params - Resend parameters including type and email/phone
     * @returns Promise with OTP-style response
     */
    resendOtp(params: ResendOtpParams): Promise<DataResponse<OTPResponse>>;
    /**
     * Get user identities (linked OAuth providers) - Supabase-compatible
     * Lists all OAuth identities linked to the current user
     * @returns Promise with list of user identities
     */
    getUserIdentities(): Promise<DataResponse<UserIdentitiesResponse>>;
    /**
     * Link an OAuth identity to current user - Supabase-compatible
     * Links an additional OAuth provider to the existing account
     * @param credentials - Provider to link
     * @returns Promise with OAuth URL to complete linking
     */
    linkIdentity(credentials: LinkIdentityCredentials): Promise<DataResponse<OAuthUrlResponse>>;
    /**
     * Unlink an OAuth identity from current user - Supabase-compatible
     * Removes a linked OAuth provider from the account
     * @param params - Identity to unlink
     * @returns Promise with void response
     */
    unlinkIdentity(params: UnlinkIdentityParams): Promise<VoidResponse>;
    /**
     * Reauthenticate to get security nonce - Supabase-compatible
     * Get a security nonce for sensitive operations (password change, etc.)
     * @returns Promise with nonce for reauthentication
     */
    reauthenticate(): Promise<DataResponse<ReauthenticateResponse>>;
    /**
     * Sign in with ID token (for native mobile apps) - Supabase-compatible
     * Authenticate using native mobile app ID tokens (Google, Apple)
     * @param credentials - Provider, ID token, and optional nonce
     * @returns Promise with user and session
     */
    signInWithIdToken(credentials: SignInWithIdTokenCredentials): Promise<FluxbaseAuthResponse>;
    /**
     * Get list of available SAML SSO providers
     * @returns Promise with list of configured SAML providers
     *
     * @example
     * ```typescript
     * const { data, error } = await client.auth.getSAMLProviders()
     * if (!error) {
     *   console.log('Available providers:', data.providers)
     * }
     * ```
     */
    getSAMLProviders(): Promise<DataResponse<SAMLProvidersResponse>>;
    /**
     * Get SAML login URL for a specific provider
     * Use this to redirect the user to the IdP for authentication
     * @param provider - SAML provider name/ID
     * @param options - Optional login configuration
     * @returns Promise with SAML login URL
     *
     * @example
     * ```typescript
     * const { data, error } = await client.auth.getSAMLLoginUrl('okta')
     * if (!error) {
     *   window.location.href = data.url
     * }
     * ```
     */
    getSAMLLoginUrl(provider: string, options?: SAMLLoginOptions): Promise<DataResponse<SAMLLoginResponse>>;
    /**
     * Initiate SAML login and redirect to IdP
     * This is a convenience method that redirects the user to the SAML IdP
     * @param provider - SAML provider name/ID
     * @param options - Optional login configuration
     * @returns Promise with provider and URL (browser will redirect)
     *
     * @example
     * ```typescript
     * // In browser, this will redirect to the SAML IdP
     * await client.auth.signInWithSAML('okta')
     * ```
     */
    signInWithSAML(provider: string, options?: SAMLLoginOptions): Promise<DataResponse<{
        provider: string;
        url: string;
    }>>;
    /**
     * Handle SAML callback after IdP authentication
     * Call this from your SAML callback page to complete authentication
     * @param samlResponse - Base64-encoded SAML response from the ACS endpoint
     * @param provider - SAML provider name (optional, extracted from RelayState)
     * @returns Promise with user and session
     *
     * @example
     * ```typescript
     * // In your SAML callback page
     * const urlParams = new URLSearchParams(window.location.search)
     * const samlResponse = urlParams.get('SAMLResponse')
     *
     * if (samlResponse) {
     *   const { data, error } = await client.auth.handleSAMLCallback(samlResponse)
     *   if (!error) {
     *     console.log('Logged in:', data.user)
     *   }
     * }
     * ```
     */
    handleSAMLCallback(samlResponse: string, provider?: string): Promise<FluxbaseAuthResponse>;
    /**
     * Get SAML Service Provider metadata for a specific provider configuration
     * Use this when configuring your IdP to download the SP metadata XML
     * @param provider - SAML provider name/ID
     * @returns Promise with SP metadata URL
     *
     * @example
     * ```typescript
     * const metadataUrl = client.auth.getSAMLMetadataUrl('okta')
     * // Share this URL with your IdP administrator
     * ```
     */
    getSAMLMetadataUrl(provider: string): string;
    /**
     * Internal: Set the session and persist it
     */
    private setSessionInternal;
    /**
     * Internal: Clear the session
     */
    private clearSession;
    /**
     * Internal: Save session to storage
     */
    private saveSession;
    /**
     * Internal: Schedule automatic token refresh
     * Only runs in browser environments when autoRefresh is enabled
     */
    private scheduleTokenRefresh;
    /**
     * Internal: Attempt to refresh the token with retry logic
     * Uses exponential backoff: 1s, 2s, 4s delays between retries
     */
    private attemptRefresh;
    /**
     * Internal: Emit auth state change event to all listeners
     */
    private emitAuthChange;
}

/**
 * Storage client for file operations
 */

declare class StorageBucket {
    private fetch;
    private bucketName;
    constructor(fetch: FluxbaseFetch, bucketName: string);
    /**
     * Upload a file to the bucket
     * @param path - The path/key for the file
     * @param file - The file to upload (File, Blob, ArrayBuffer, or ArrayBufferView like Uint8Array)
     * @param options - Upload options
     */
    upload(path: string, file: File | Blob | ArrayBuffer | ArrayBufferView, options?: UploadOptions): Promise<{
        data: {
            id: string;
            path: string;
            fullPath: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Upload with progress tracking using XMLHttpRequest
     * @private
     */
    private uploadWithProgress;
    /**
     * Upload a file using streaming for reduced memory usage.
     * This method bypasses FormData buffering and streams data directly to the server.
     * Ideal for large files where memory efficiency is important.
     *
     * @param path - The path/key for the file
     * @param stream - ReadableStream of the file data
     * @param size - The size of the file in bytes (required for Content-Length header)
     * @param options - Upload options
     *
     * @example
     * ```typescript
     * // Upload from a File's stream
     * const file = new File([...], 'large-video.mp4');
     * const { data, error } = await storage
     *   .from('videos')
     *   .uploadStream('video.mp4', file.stream(), file.size, {
     *     contentType: 'video/mp4',
     *   });
     *
     * // Upload from a fetch response stream
     * const response = await fetch('https://example.com/data.zip');
     * const size = parseInt(response.headers.get('content-length') || '0');
     * const { data, error } = await storage
     *   .from('files')
     *   .uploadStream('data.zip', response.body!, size, {
     *     contentType: 'application/zip',
     *   });
     * ```
     */
    uploadStream(path: string, stream: ReadableStream<Uint8Array>, size: number, options?: StreamUploadOptions): Promise<{
        data: {
            id: string;
            path: string;
            fullPath: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Upload a large file using streaming for reduced memory usage.
     * This is a convenience method that converts a File or Blob to a stream.
     *
     * @param path - The path/key for the file
     * @param file - The File or Blob to upload
     * @param options - Upload options
     *
     * @example
     * ```typescript
     * const file = new File([...], 'large-video.mp4');
     * const { data, error } = await storage
     *   .from('videos')
     *   .uploadLargeFile('video.mp4', file, {
     *     contentType: 'video/mp4',
     *     onUploadProgress: (p) => console.log(`${p.percentage}% complete`),
     *   });
     * ```
     */
    uploadLargeFile(path: string, file: File | Blob, options?: StreamUploadOptions): Promise<{
        data: {
            id: string;
            path: string;
            fullPath: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Download a file from the bucket
     * @param path - The path/key of the file
     *
     * @example
     * ```typescript
     * // Default: returns Blob
     * const { data: blob } = await storage.from('bucket').download('file.pdf');
     *
     * // Streaming: returns { stream, size } for progress tracking
     * const { data } = await storage.from('bucket').download('large.json', { stream: true });
     * console.log(`File size: ${data.size} bytes`);
     * // Process data.stream...
     * ```
     */
    download(path: string): Promise<{
        data: Blob | null;
        error: Error | null;
    }>;
    download(path: string, options: {
        stream: true;
        timeout?: number;
        signal?: AbortSignal;
    }): Promise<{
        data: StreamDownloadData | null;
        error: Error | null;
    }>;
    download(path: string, options: {
        stream?: false;
        timeout?: number;
        signal?: AbortSignal;
    }): Promise<{
        data: Blob | null;
        error: Error | null;
    }>;
    /**
     * Download a file with resumable chunked downloads for large files.
     * Returns a ReadableStream that abstracts the chunking internally.
     *
     * Features:
     * - Downloads file in chunks using HTTP Range headers
     * - Automatically retries failed chunks with exponential backoff
     * - Reports progress via callback
     * - Falls back to regular streaming if Range not supported
     *
     * @param path - The file path within the bucket
     * @param options - Download options including chunk size, retries, and progress callback
     * @returns A ReadableStream and file size (consumer doesn't need to know about chunking)
     *
     * @example
     * ```typescript
     * const { data, error } = await storage.from('bucket').downloadResumable('large.json', {
     *   chunkSize: 5 * 1024 * 1024, // 5MB chunks
     *   maxRetries: 3,
     *   onProgress: (progress) => console.log(`${progress.percentage}% complete`)
     * });
     * if (data) {
     *   console.log(`File size: ${data.size} bytes`);
     *   // Process data.stream...
     * }
     * ```
     */
    downloadResumable(path: string, options?: ResumableDownloadOptions): Promise<{
        data: ResumableDownloadData | null;
        error: Error | null;
    }>;
    /**
     * Upload a large file with resumable chunked uploads.
     *
     * Features:
     * - Uploads file in chunks for reliability
     * - Automatically retries failed chunks with exponential backoff
     * - Reports progress via callback with chunk-level granularity
     * - Can resume interrupted uploads using session ID
     *
     * @param path - The file path within the bucket
     * @param file - The File or Blob to upload
     * @param options - Upload options including chunk size, retries, and progress callback
     * @returns Upload result with file info
     *
     * @example
     * const { data, error } = await storage.from('uploads').uploadResumable('large.zip', file, {
     *   chunkSize: 5 * 1024 * 1024, // 5MB chunks
     *   maxRetries: 3,
     *   onProgress: (p) => {
     *     console.log(`${p.percentage}% (chunk ${p.currentChunk}/${p.totalChunks})`);
     *     console.log(`Speed: ${(p.bytesPerSecond / 1024 / 1024).toFixed(2)} MB/s`);
     *     console.log(`Session ID (for resume): ${p.sessionId}`);
     *   }
     * });
     *
     * // To resume an interrupted upload:
     * const { data, error } = await storage.from('uploads').uploadResumable('large.zip', file, {
     *   resumeSessionId: 'previous-session-id',
     * });
     */
    uploadResumable(path: string, file: File | Blob, options?: ResumableUploadOptions): Promise<{
        data: {
            id: string;
            path: string;
            fullPath: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Abort an in-progress resumable upload
     * @param sessionId - The upload session ID to abort
     */
    abortResumableUpload(sessionId: string): Promise<{
        error: Error | null;
    }>;
    /**
     * Get the status of a resumable upload session
     * @param sessionId - The upload session ID to check
     */
    getResumableUploadStatus(sessionId: string): Promise<{
        data: ChunkedUploadSession | null;
        error: Error | null;
    }>;
    /**
     * List files in the bucket
     * Supports both Supabase-style list(path, options) and Fluxbase-style list(options)
     * @param pathOrOptions - The folder path or list options
     * @param maybeOptions - List options when first param is a path
     */
    list(pathOrOptions?: string | ListOptions, maybeOptions?: ListOptions): Promise<{
        data: FileObject[] | null;
        error: Error | null;
    }>;
    /**
     * Remove files from the bucket
     * @param paths - Array of file paths to remove
     */
    remove(paths: string[]): Promise<{
        data: FileObject[] | null;
        error: Error | null;
    }>;
    /**
     * Copy a file to a new path
     *
     * @param fromPath - Source file path
     * @param toPath - Destination file path
     * @returns Promise resolving to { data, error } tuple
     */
    copy(fromPath: string, toPath: string): Promise<{
        data: unknown;
        error: Error | null;
    }>;
    /**
     * Move a file to a new path
     *
     * @param fromPath - Source file path
     * @param toPath - Destination file path
     * @returns Promise resolving to { data, error } tuple
     */
    move(fromPath: string, toPath: string): Promise<{
        data: unknown;
        error: Error | null;
    }>;
    /**
     * Get a public URL for a file
     * @param path - The file path
     */
    getPublicUrl(path: string): {
        data: {
            publicUrl: string;
        };
    };
    /**
     * Build query string from transform options
     * @private
     */
    private buildTransformQuery;
    /**
     * Get a public URL for a file with image transformations applied
     * Only works for image files (JPEG, PNG, WebP, GIF, AVIF, etc.)
     *
     * @param path - The file path
     * @param transform - Transformation options (width, height, format, quality, fit)
     *
     * @example
     * ```typescript
     * // Get a 300x200 WebP thumbnail
     * const url = storage.from('images').getTransformUrl('photo.jpg', {
     *   width: 300,
     *   height: 200,
     *   format: 'webp',
     *   quality: 85,
     *   fit: 'cover'
     * });
     *
     * // Get a resized image maintaining aspect ratio
     * const url = storage.from('images').getTransformUrl('photo.jpg', {
     *   width: 800,
     *   format: 'webp'
     * });
     * ```
     */
    getTransformUrl(path: string, transform: TransformOptions): string;
    /**
     * Create a signed URL for temporary access to a file
     * Optionally include image transformation parameters
     *
     * @param path - The file path
     * @param options - Signed URL options including expiration and transforms
     *
     * @example
     * ```typescript
     * // Simple signed URL (1 hour expiry)
     * const { data, error } = await storage.from('images').createSignedUrl('photo.jpg');
     *
     * // Signed URL with custom expiry
     * const { data, error } = await storage.from('images').createSignedUrl('photo.jpg', {
     *   expiresIn: 7200 // 2 hours
     * });
     *
     * // Signed URL with image transformation
     * const { data, error } = await storage.from('images').createSignedUrl('photo.jpg', {
     *   expiresIn: 3600,
     *   transform: {
     *     width: 400,
     *     height: 300,
     *     format: 'webp',
     *     quality: 85,
     *     fit: 'cover'
     *   }
     * });
     * ```
     */
    createSignedUrl(path: string, options?: SignedUrlOptions): Promise<{
        data: {
            signedUrl: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Share a file with another user (RLS)
     * @param path - The file path
     * @param options - Share options (userId and permission)
     */
    share(path: string, options: ShareFileOptions): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Revoke file access from a user (RLS)
     * @param path - The file path
     * @param userId - The user ID to revoke access from
     */
    revokeShare(path: string, userId: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * List users a file is shared with (RLS)
     * @param path - The file path
     */
    listShares(path: string): Promise<{
        data: FileShare[] | null;
        error: Error | null;
    }>;
}
declare class FluxbaseStorage {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Get a reference to a storage bucket
     * @param bucketName - The name of the bucket
     */
    from(bucketName: string): StorageBucket;
    /**
     * List all buckets
     */
    listBuckets(): Promise<{
        data: Array<{
            name: string;
            created_at: string;
        }> | null;
        error: Error | null;
    }>;
    /**
     * Create a new bucket
     * @param bucketName - The name of the bucket to create
     */
    createBucket(bucketName: string): Promise<{
        data: {
            name: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Delete a bucket
     * @param bucketName - The name of the bucket to delete
     */
    deleteBucket(bucketName: string): Promise<{
        data: {
            message: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Empty a bucket (delete all files)
     * @param bucketName - The name of the bucket to empty
     */
    emptyBucket(bucketName: string): Promise<{
        data: {
            message: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Update bucket settings (RLS - requires admin or service key)
     * @param bucketName - The name of the bucket
     * @param settings - Bucket settings to update
     */
    updateBucketSettings(bucketName: string, settings: BucketSettings): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Get bucket details
     * @param bucketName - The name of the bucket
     */
    getBucket(bucketName: string): Promise<{
        data: Bucket | null;
        error: Error | null;
    }>;
}

/**
 * Edge Functions module for Fluxbase SDK
 * Compatible with Supabase Functions API
 *
 * @example
 * ```typescript
 * // Invoke a function
 * const { data, error } = await client.functions.invoke('hello-world', {
 *   body: { name: 'Alice' }
 * })
 *
 * // With custom headers
 * const { data, error } = await client.functions.invoke('api-call', {
 *   body: { query: 'data' },
 *   headers: { 'X-Custom-Header': 'value' },
 *   method: 'POST'
 * })
 * ```
 */

/**
 * Edge Functions client for invoking serverless functions
 * API-compatible with Supabase Functions
 *
 * For admin operations (create, update, delete, sync), use client.admin.functions
 *
 * @category Functions
 */
declare class FluxbaseFunctions {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Invoke an edge function
     *
     * This method is fully compatible with Supabase's functions.invoke() API.
     *
     * @param functionName - The name of the function to invoke
     * @param options - Invocation options including body, headers, HTTP method, and namespace
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * // Simple invocation (uses first matching function by namespace alphabetically)
     * const { data, error } = await client.functions.invoke('hello', {
     *   body: { name: 'World' }
     * })
     *
     * // Invoke a specific namespace's function
     * const { data, error } = await client.functions.invoke('hello', {
     *   body: { name: 'World' },
     *   namespace: 'my-app'
     * })
     *
     * // With GET method
     * const { data, error } = await client.functions.invoke('get-data', {
     *   method: 'GET'
     * })
     *
     * // With custom headers
     * const { data, error } = await client.functions.invoke('api-proxy', {
     *   body: { query: 'search' },
     *   headers: { 'Authorization': 'Bearer token' },
     *   method: 'POST'
     * })
     * ```
     */
    invoke<T = unknown>(functionName: string, options?: FunctionInvokeOptions): Promise<{
        data: T | null;
        error: Error | null;
    }>;
    /**
     * List all public edge functions
     *
     * @returns Promise resolving to { data, error } tuple with array of public functions
     *
     * @example
     * ```typescript
     * const { data, error } = await client.functions.list()
     * if (data) {
     *   console.log('Functions:', data.map(f => f.name))
     * }
     * ```
     */
    list(): Promise<{
        data: EdgeFunction[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific edge function
     *
     * @param name - Function name
     * @returns Promise resolving to { data, error } tuple with function metadata
     *
     * @example
     * ```typescript
     * const { data, error } = await client.functions.get('my-function')
     * if (data) {
     *   console.log('Function version:', data.version)
     * }
     * ```
     */
    get(name: string): Promise<{
        data: EdgeFunction | null;
        error: Error | null;
    }>;
}

/**
 * Jobs module for Fluxbase SDK
 * Client-facing API for submitting and monitoring background jobs
 *
 * @example
 * ```typescript
 * // Submit a job
 * const { data, error } = await client.jobs.submit('process-data', {
 *   items: [1, 2, 3]
 * })
 *
 * // Get job status
 * const { data: job, error } = await client.jobs.get(data.id)
 * console.log('Job status:', job.status)
 *
 * // Cancel a running job
 * await client.jobs.cancel(data.id)
 * ```
 */

/**
 * Jobs client for submitting and monitoring background jobs
 *
 * For admin operations (create job functions, manage workers, view all jobs),
 * use client.admin.jobs
 *
 * @category Jobs
 */
declare class FluxbaseJobs {
    private fetch;
    private cachedRole;
    private readonly ROLE_CACHE_TTL;
    private isServiceRole;
    constructor(fetch: FluxbaseFetch, isServiceRole?: boolean);
    /**
     * Get the current user's role from user_profiles table
     * This is used to auto-populate the onBehalfOf parameter when submitting jobs
     *
     * @returns Promise resolving to the user's role or null if not found
     */
    private getCurrentUserRole;
    /**
     * Submit a new job for execution
     *
     * @param jobName - Name of the job function to execute
     * @param payload - Job input data
     * @param options - Additional options (priority, namespace, scheduled time, onBehalfOf)
     * @returns Promise resolving to { data, error } tuple with submitted job details
     *
     * @example
     * ```typescript
     * // Submit a simple job
     * const { data, error } = await client.jobs.submit('send-email', {
     *   to: 'user@example.com',
     *   subject: 'Hello',
     *   body: 'Welcome!'
     * })
     *
     * if (data) {
     *   console.log('Job submitted:', data.id)
     *   console.log('Status:', data.status)
     * }
     *
     * // Submit with priority
     * const { data } = await client.jobs.submit('high-priority-task', payload, {
     *   priority: 10
     * })
     *
     * // Schedule for later
     * const { data } = await client.jobs.submit('scheduled-task', payload, {
     *   scheduled: '2025-01-01T00:00:00Z'
     * })
     *
     * // Submit on behalf of a user (service_role only)
     * const { data } = await serviceClient.jobs.submit('user-task', payload, {
     *   onBehalfOf: {
     *     user_id: 'user-uuid',
     *     user_email: 'user@example.com'
     *   }
     * })
     * ```
     */
    submit(jobName: string, payload?: unknown, options?: {
        priority?: number;
        namespace?: string;
        scheduled?: string;
        /**
         * Submit job on behalf of another user (service_role only).
         * The job will be created with the specified user's identity,
         * allowing them to see the job and its logs via RLS.
         *
         * If not provided, the current user's identity and role from user_profiles
         * will be automatically included.
         */
        onBehalfOf?: OnBehalfOf;
    }): Promise<{
        data: Job | null;
        error: Error | null;
    }>;
    /**
     * Get status and details of a specific job
     *
     * @param jobId - Job ID
     * @returns Promise resolving to { data, error } tuple with job details
     *
     * @example
     * ```typescript
     * const { data: job, error } = await client.jobs.get('550e8400-e29b-41d4-a716-446655440000')
     *
     * if (job) {
     *   console.log('Status:', job.status)
     *   console.log('Progress:', job.progress_percent + '%')
     *   console.log('Result:', job.result)
     *   console.log('Logs:', job.logs)
     * }
     * ```
     */
    get(jobId: string): Promise<{
        data: Job | null;
        error: Error | null;
    }>;
    /**
     * List jobs submitted by the current user
     *
     * @param filters - Optional filters (status, namespace, limit, offset)
     * @returns Promise resolving to { data, error } tuple with array of jobs
     *
     * @example
     * ```typescript
     * // List all your jobs
     * const { data: jobs, error } = await client.jobs.list()
     *
     * // Filter by status
     * const { data: running } = await client.jobs.list({
     *   status: 'running'
     * })
     *
     * // Paginate
     * const { data: page } = await client.jobs.list({
     *   limit: 20,
     *   offset: 40
     * })
     * ```
     */
    list(filters?: {
        status?: string;
        namespace?: string;
        limit?: number;
        offset?: number;
        includeResult?: boolean;
    }): Promise<{
        data: Job[] | null;
        error: Error | null;
    }>;
    /**
     * Cancel a pending or running job
     *
     * @param jobId - Job ID to cancel
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { error } = await client.jobs.cancel('550e8400-e29b-41d4-a716-446655440000')
     *
     * if (!error) {
     *   console.log('Job cancelled successfully')
     * }
     * ```
     */
    cancel(jobId: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Retry a failed job
     *
     * Creates a new job execution with the same parameters
     *
     * @param jobId - Job ID to retry
     * @returns Promise resolving to { data, error } tuple with new job
     *
     * @example
     * ```typescript
     * const { data: newJob, error } = await client.jobs.retry('550e8400-e29b-41d4-a716-446655440000')
     *
     * if (newJob) {
     *   console.log('Job retried, new ID:', newJob.id)
     * }
     * ```
     */
    retry(jobId: string): Promise<{
        data: Job | null;
        error: Error | null;
    }>;
    /**
     * Get execution logs for a job
     *
     * Returns logs for the specified job. Only returns logs for jobs
     * owned by the authenticated user (unless using service_role).
     *
     * @param jobId - Job ID
     * @param afterLine - Optional line number to get logs after (for polling/streaming)
     * @returns Promise resolving to { data, error } tuple with execution logs
     *
     * @example
     * ```typescript
     * // Get all logs for a job
     * const { data: logs, error } = await client.jobs.getLogs('550e8400-e29b-41d4-a716-446655440000')
     *
     * if (logs) {
     *   for (const log of logs) {
     *     console.log(`[${log.level}] ${log.message}`)
     *   }
     * }
     *
     * // Backfill + stream pattern
     * const { data: logs } = await client.jobs.getLogs(jobId)
     * let lastLine = Math.max(...(logs?.map(l => l.line_number) ?? []), 0)
     *
     * const channel = client.realtime
     *   .executionLogs(jobId, 'job')
     *   .onLog((log) => {
     *     if (log.line_number > lastLine) {
     *       displayLog(log)
     *       lastLine = log.line_number
     *     }
     *   })
     *   .subscribe()
     * ```
     */
    getLogs(jobId: string, afterLine?: number): Promise<{
        data: ExecutionLog[] | null;
        error: Error | null;
    }>;
}

/**
 * RPC (Remote Procedure Call) module for invoking SQL-based procedures
 */

/**
 * Options for invoking an RPC procedure
 */
interface RPCInvokeOptions {
    /** Namespace of the procedure (defaults to 'default') */
    namespace?: string;
    /** Execute asynchronously (returns execution ID immediately) */
    async?: boolean;
    /** Request timeout in milliseconds (default: 30000) */
    timeout?: number;
}
/**
 * Fetch interface for RPC operations
 */
interface RPCFetch {
    get: <T>(path: string) => Promise<T>;
    post: <T>(path: string, body?: unknown, options?: {
        timeout?: number;
    }) => Promise<T>;
}
/**
 * FluxbaseRPC provides methods for invoking RPC procedures
 *
 * @example
 * ```typescript
 * // Invoke a procedure synchronously
 * const { data, error } = await fluxbase.rpc.invoke('get-user-orders', {
 *   user_id: '123',
 *   limit: 10
 * });
 *
 * // Invoke asynchronously
 * const { data: asyncResult } = await fluxbase.rpc.invoke('long-running-report', {
 *   start_date: '2024-01-01'
 * }, { async: true });
 *
 * // Poll for status
 * const { data: status } = await fluxbase.rpc.getStatus(asyncResult.execution_id);
 * ```
 */
declare class FluxbaseRPC {
    private fetch;
    constructor(fetch: RPCFetch);
    /**
     * List available RPC procedures (public, enabled)
     *
     * @param namespace - Optional namespace filter
     * @returns Promise resolving to { data, error } tuple with array of procedure summaries
     */
    list(namespace?: string): Promise<{
        data: RPCProcedureSummary[] | null;
        error: Error | null;
    }>;
    /**
     * Invoke an RPC procedure
     *
     * @param name - Procedure name
     * @param params - Optional parameters to pass to the procedure
     * @param options - Optional invocation options
     * @returns Promise resolving to { data, error } tuple with invocation response
     *
     * @example
     * ```typescript
     * // Synchronous invocation
     * const { data, error } = await fluxbase.rpc.invoke('get-user-orders', {
     *   user_id: '123',
     *   limit: 10
     * });
     * console.log(data.result); // Query results
     *
     * // Asynchronous invocation
     * const { data: asyncData } = await fluxbase.rpc.invoke('generate-report', {
     *   year: 2024
     * }, { async: true });
     * console.log(asyncData.execution_id); // Use to poll status
     * ```
     */
    invoke<T = unknown>(name: string, params?: Record<string, unknown>, options?: RPCInvokeOptions): Promise<{
        data: RPCInvokeResponse<T> | null;
        error: Error | null;
    }>;
    /**
     * Get execution status (for async invocations or checking history)
     *
     * @param executionId - The execution ID returned from async invoke
     * @returns Promise resolving to { data, error } tuple with execution details
     *
     * @example
     * ```typescript
     * const { data, error } = await fluxbase.rpc.getStatus('execution-uuid');
     * if (data.status === 'completed') {
     *   console.log('Result:', data.result);
     * } else if (data.status === 'running') {
     *   console.log('Still running...');
     * }
     * ```
     */
    getStatus(executionId: string): Promise<{
        data: RPCExecution | null;
        error: Error | null;
    }>;
    /**
     * Get execution logs (for debugging and monitoring)
     *
     * @param executionId - The execution ID
     * @param afterLine - Optional line number to get logs after (for polling)
     * @returns Promise resolving to { data, error } tuple with execution logs
     *
     * @example
     * ```typescript
     * const { data: logs } = await fluxbase.rpc.getLogs('execution-uuid');
     * for (const log of logs) {
     *   console.log(`[${log.level}] ${log.message}`);
     * }
     * ```
     */
    getLogs(executionId: string, afterLine?: number): Promise<{
        data: RPCExecutionLog[] | null;
        error: Error | null;
    }>;
    /**
     * Poll for execution completion with exponential backoff
     *
     * @param executionId - The execution ID to poll
     * @param options - Polling options
     * @returns Promise resolving to final execution state
     *
     * @example
     * ```typescript
     * const { data: result } = await fluxbase.rpc.invoke('long-task', {}, { async: true });
     * const { data: final } = await fluxbase.rpc.waitForCompletion(result.execution_id, {
     *   maxWaitMs: 60000, // Wait up to 1 minute
     *   onProgress: (exec) => console.log(`Status: ${exec.status}`)
     * });
     * console.log('Final result:', final.result);
     * ```
     */
    waitForCompletion(executionId: string, options?: {
        /** Maximum time to wait in milliseconds (default: 30000) */
        maxWaitMs?: number;
        /** Initial polling interval in milliseconds (default: 500) */
        initialIntervalMs?: number;
        /** Maximum polling interval in milliseconds (default: 5000) */
        maxIntervalMs?: number;
        /** Callback for progress updates */
        onProgress?: (execution: RPCExecution) => void;
    }): Promise<{
        data: RPCExecution | null;
        error: Error | null;
    }>;
}

/**
 * System Settings Manager
 *
 * Manages low-level system settings with key-value storage.
 * For application-level settings, use AppSettingsManager instead.
 *
 * @example
 * ```typescript
 * const settings = client.admin.settings.system
 *
 * // List all system settings
 * const { settings } = await settings.list()
 *
 * // Get specific setting
 * const setting = await settings.get('app.auth.enable_signup')
 *
 * // Update setting
 * await settings.update('app.auth.enable_signup', {
 *   value: { value: true },
 *   description: 'Enable user signup'
 * })
 *
 * // Delete setting
 * await settings.delete('app.auth.enable_signup')
 * ```
 */
declare class SystemSettingsManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all system settings
     *
     * @returns Promise resolving to ListSystemSettingsResponse
     *
     * @example
     * ```typescript
     * const response = await client.admin.settings.system.list()
     * console.log(response.settings)
     * ```
     */
    list(): Promise<ListSystemSettingsResponse>;
    /**
     * Get a specific system setting by key
     *
     * @param key - Setting key (e.g., 'app.auth.enable_signup')
     * @returns Promise resolving to SystemSetting
     *
     * @example
     * ```typescript
     * const setting = await client.admin.settings.system.get('app.auth.enable_signup')
     * console.log(setting.value)
     * ```
     */
    get(key: string): Promise<SystemSetting>;
    /**
     * Update or create a system setting
     *
     * @param key - Setting key
     * @param request - Update request with value and optional description
     * @returns Promise resolving to SystemSetting
     *
     * @example
     * ```typescript
     * const updated = await client.admin.settings.system.update('app.auth.enable_signup', {
     *   value: { value: true },
     *   description: 'Enable user signup'
     * })
     * ```
     */
    update(key: string, request: UpdateSystemSettingRequest): Promise<SystemSetting>;
    /**
     * Delete a system setting
     *
     * @param key - Setting key to delete
     * @returns Promise<void>
     *
     * @example
     * ```typescript
     * await client.admin.settings.system.delete('app.auth.enable_signup')
     * ```
     */
    delete(key: string): Promise<void>;
}
/**
 * Application Settings Manager
 *
 * Manages high-level application settings with a structured API.
 * Provides type-safe access to authentication, features, email, and security settings.
 *
 * @example
 * ```typescript
 * const settings = client.admin.settings.app
 *
 * // Get all app settings
 * const appSettings = await settings.get()
 * console.log(appSettings.authentication.enable_signup)
 *
 * // Update specific settings
 * const updated = await settings.update({
 *   authentication: {
 *     enable_signup: true,
 *     password_min_length: 12
 *   }
 * })
 * ```
 */
declare class AppSettingsManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Get all application settings
     *
     * Returns structured settings for authentication, features, email, and security.
     *
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * const settings = await client.admin.settings.app.get()
     *
     * console.log('Signup enabled:', settings.authentication.enable_signup)
     * console.log('Realtime enabled:', settings.features.enable_realtime)
     * console.log('Email provider:', settings.email.provider)
     * ```
     */
    get(): Promise<AppSettings>;
    /**
     * Update application settings
     *
     * Supports partial updates - only provide the fields you want to change.
     *
     * @param request - Settings to update (partial update supported)
     * @returns Promise resolving to AppSettings - Updated settings
     *
     * @example
     * ```typescript
     * // Update authentication settings
     * const updated = await client.admin.settings.app.update({
     *   authentication: {
     *     enable_signup: true,
     *     password_min_length: 12
     *   }
     * })
     *
     * // Update multiple categories
     * await client.admin.settings.app.update({
     *   authentication: { enable_signup: false },
     *   features: { enable_realtime: true },
     *   security: { enable_global_rate_limit: true }
     * })
     * ```
     */
    update(request: UpdateAppSettingsRequest): Promise<AppSettings>;
    /**
     * Enable user signup
     *
     * Convenience method to enable user registration.
     *
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.enableSignup()
     * ```
     */
    enableSignup(): Promise<AppSettings>;
    /**
     * Disable user signup
     *
     * Convenience method to disable user registration.
     *
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.disableSignup()
     * ```
     */
    disableSignup(): Promise<AppSettings>;
    /**
     * Update password minimum length
     *
     * Convenience method to set password requirements.
     *
     * @param length - Minimum password length (8-128 characters)
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.setPasswordMinLength(12)
     * ```
     */
    setPasswordMinLength(length: number): Promise<AppSettings>;
    /**
     * Enable or disable a feature
     *
     * Convenience method to toggle feature flags.
     *
     * @param feature - Feature name ('realtime' | 'storage' | 'functions')
     * @param enabled - Whether to enable or disable the feature
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * // Enable realtime
     * await client.admin.settings.app.setFeature('realtime', true)
     *
     * // Disable storage
     * await client.admin.settings.app.setFeature('storage', false)
     * ```
     */
    setFeature(feature: "realtime" | "storage" | "functions", enabled: boolean): Promise<AppSettings>;
    /**
     * Enable or disable global rate limiting
     *
     * Convenience method to toggle global rate limiting.
     *
     * @param enabled - Whether to enable rate limiting
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.setRateLimiting(true)
     * ```
     */
    setRateLimiting(enabled: boolean): Promise<AppSettings>;
    /**
     * Configure SMTP email provider
     *
     * Convenience method to set up SMTP email delivery.
     *
     * @param config - SMTP configuration
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.configureSMTP({
     *   host: 'smtp.gmail.com',
     *   port: 587,
     *   username: 'your-email@gmail.com',
     *   password: 'your-app-password',
     *   use_tls: true,
     *   from_address: 'noreply@yourapp.com',
     *   from_name: 'Your App'
     * })
     * ```
     */
    configureSMTP(config: {
        host: string;
        port: number;
        username: string;
        password: string;
        use_tls: boolean;
        from_address?: string;
        from_name?: string;
        reply_to_address?: string;
    }): Promise<AppSettings>;
    /**
     * Configure SendGrid email provider
     *
     * Convenience method to set up SendGrid email delivery.
     *
     * @param apiKey - SendGrid API key
     * @param options - Optional from address, name, and reply-to
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.configureSendGrid('SG.xxx', {
     *   from_address: 'noreply@yourapp.com',
     *   from_name: 'Your App'
     * })
     * ```
     */
    configureSendGrid(apiKey: string, options?: {
        from_address?: string;
        from_name?: string;
        reply_to_address?: string;
    }): Promise<AppSettings>;
    /**
     * Configure Mailgun email provider
     *
     * Convenience method to set up Mailgun email delivery.
     *
     * @param apiKey - Mailgun API key
     * @param domain - Mailgun domain
     * @param options - Optional EU region flag and email addresses
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.configureMailgun('key-xxx', 'mg.yourapp.com', {
     *   eu_region: false,
     *   from_address: 'noreply@yourapp.com',
     *   from_name: 'Your App'
     * })
     * ```
     */
    configureMailgun(apiKey: string, domain: string, options?: {
        eu_region?: boolean;
        from_address?: string;
        from_name?: string;
        reply_to_address?: string;
    }): Promise<AppSettings>;
    /**
     * Configure AWS SES email provider
     *
     * Convenience method to set up AWS SES email delivery.
     *
     * @param accessKeyId - AWS access key ID
     * @param secretAccessKey - AWS secret access key
     * @param region - AWS region (e.g., 'us-east-1')
     * @param options - Optional email addresses
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.configureSES(
     *   'AKIAIOSFODNN7EXAMPLE',
     *   'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
     *   'us-east-1',
     *   {
     *     from_address: 'noreply@yourapp.com',
     *     from_name: 'Your App'
     *   }
     * )
     * ```
     */
    configureSES(accessKeyId: string, secretAccessKey: string, region: string, options?: {
        from_address?: string;
        from_name?: string;
        reply_to_address?: string;
    }): Promise<AppSettings>;
    /**
     * Enable or disable email functionality
     *
     * Convenience method to toggle email system on/off.
     *
     * @param enabled - Whether to enable email
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.setEmailEnabled(true)
     * ```
     */
    setEmailEnabled(enabled: boolean): Promise<AppSettings>;
    /**
     * Configure password complexity requirements
     *
     * Convenience method to set password validation rules.
     *
     * @param requirements - Password complexity requirements
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.setPasswordComplexity({
     *   min_length: 12,
     *   require_uppercase: true,
     *   require_lowercase: true,
     *   require_number: true,
     *   require_special: true
     * })
     * ```
     */
    setPasswordComplexity(requirements: {
        min_length?: number;
        require_uppercase?: boolean;
        require_lowercase?: boolean;
        require_number?: boolean;
        require_special?: boolean;
    }): Promise<AppSettings>;
    /**
     * Configure session settings
     *
     * Convenience method to set session timeout and limits.
     *
     * @param timeoutMinutes - Session timeout in minutes (0 for no timeout)
     * @param maxSessionsPerUser - Maximum concurrent sessions per user (0 for unlimited)
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * // 30 minute sessions, max 3 devices per user
     * await client.admin.settings.app.setSessionSettings(30, 3)
     * ```
     */
    setSessionSettings(timeoutMinutes: number, maxSessionsPerUser: number): Promise<AppSettings>;
    /**
     * Enable or disable email verification requirement
     *
     * Convenience method to require email verification for new signups.
     *
     * @param required - Whether to require email verification
     * @returns Promise resolving to AppSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.setEmailVerificationRequired(true)
     * ```
     */
    setEmailVerificationRequired(required: boolean): Promise<AppSettings>;
    /**
     * Get a specific custom setting's value only (without metadata)
     *
     * Convenience method that returns just the value field instead of the full CustomSetting object.
     *
     * @param key - Setting key (e.g., 'billing.tiers', 'features.beta_enabled')
     * @returns Promise resolving to the setting's value
     *
     * @example
     * ```typescript
     * const tiers = await client.admin.settings.app.getSetting('billing.tiers')
     * console.log(tiers) // { free: 1000, pro: 10000, enterprise: 100000 }
     * ```
     */
    getSetting(key: string): Promise<any>;
    /**
     * Get multiple custom settings' values by keys
     *
     * Fetches multiple settings in a single request and returns only their values.
     *
     * @param keys - Array of setting keys to fetch
     * @returns Promise resolving to object mapping keys to values
     *
     * @example
     * ```typescript
     * const values = await client.admin.settings.app.getSettings([
     *   'billing.tiers',
     *   'features.beta_enabled'
     * ])
     * console.log(values)
     * // {
     * //   'billing.tiers': { free: 1000, pro: 10000 },
     * //   'features.beta_enabled': { enabled: true }
     * // }
     * ```
     */
    getSettings(keys: string[]): Promise<Record<string, any>>;
    /**
     * Set or create a custom setting
     *
     * Creates a new custom setting or updates an existing one.
     *
     * @param key - Setting key
     * @param value - Setting value (any JSON-serializable value)
     * @param options - Optional configuration (description, is_public, is_secret, etc.)
     * @returns Promise resolving to CustomSetting
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.setSetting('billing.tiers', {
     *   free: 1000,
     *   pro: 10000,
     *   enterprise: 100000
     * }, {
     *   description: 'API quotas per billing tier',
     *   is_public: false
     * })
     * ```
     */
    setSetting(key: string, value: any, options?: {
        description?: string;
        is_public?: boolean;
        is_secret?: boolean;
        value_type?: string;
    }): Promise<CustomSetting>;
    /**
     * List all custom settings
     *
     * @returns Promise resolving to array of CustomSetting objects
     *
     * @example
     * ```typescript
     * const settings = await client.admin.settings.app.listSettings()
     * settings.forEach(s => console.log(s.key, s.value))
     * ```
     */
    listSettings(): Promise<CustomSetting[]>;
    /**
     * Delete a custom setting
     *
     * @param key - Setting key to delete
     * @returns Promise<void>
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.deleteSetting('billing.tiers')
     * ```
     */
    deleteSetting(key: string): Promise<void>;
    /**
     * Set a system-level secret setting (encrypted)
     *
     * Creates or updates an encrypted system secret. The value is encrypted server-side
     * and can only be accessed by edge functions, background jobs, or custom handlers.
     * The SDK never returns the decrypted value.
     *
     * @param key - Secret key
     * @param value - Secret value (will be encrypted server-side)
     * @param options - Optional description
     * @returns Promise resolving to SecretSettingMetadata (never includes the value)
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.setSecretSetting('stripe_api_key', 'sk-live-xxx', {
     *   description: 'Stripe API key for payment processing'
     * })
     * ```
     */
    setSecretSetting(key: string, value: string, options?: {
        description?: string;
    }): Promise<SecretSettingMetadata>;
    /**
     * Get metadata for a system secret setting (never returns the value)
     *
     * @param key - Secret key
     * @returns Promise resolving to SecretSettingMetadata
     *
     * @example
     * ```typescript
     * const metadata = await client.admin.settings.app.getSecretSetting('stripe_api_key')
     * console.log(metadata.key, metadata.updated_at)
     * // Note: metadata.value is never included
     * ```
     */
    getSecretSetting(key: string): Promise<SecretSettingMetadata>;
    /**
     * List all system secret settings (metadata only, never includes values)
     *
     * @returns Promise resolving to array of SecretSettingMetadata
     *
     * @example
     * ```typescript
     * const secrets = await client.admin.settings.app.listSecretSettings()
     * secrets.forEach(s => console.log(s.key, s.description))
     * ```
     */
    listSecretSettings(): Promise<SecretSettingMetadata[]>;
    /**
     * Delete a system secret setting
     *
     * @param key - Secret key to delete
     * @returns Promise<void>
     *
     * @example
     * ```typescript
     * await client.admin.settings.app.deleteSecretSetting('stripe_api_key')
     * ```
     */
    deleteSecretSetting(key: string): Promise<void>;
    /**
     * Get the decrypted value of a user's secret setting
     *
     * This is a privileged operation that requires service_role.
     * Use this to retrieve user-specific secrets when running as a service
     * (e.g., in edge functions or background jobs).
     *
     * @param userId - The user ID whose secret to retrieve
     * @param key - Secret key
     * @returns Promise resolving to the decrypted secret value
     *
     * @example
     * ```typescript
     * // In an edge function, get a user's API key for validation
     * const apiKey = await fluxbaseService.admin.settings.app.getUserSecretValue(
     *   userId,
     *   'owntracks_api_key'
     * )
     * if (apiKey !== providedKey) {
     *   throw new Error('Invalid API key')
     * }
     * ```
     */
    getUserSecretValue(userId: string, key: string): Promise<string>;
    /**
     * Reset all application settings to their default values
     *
     * @returns Promise resolving to the default app settings
     */
    reset(): Promise<AppSettings>;
}
/**
 * Email Template Manager
 *
 * Manages email templates for authentication and user communication.
 * Supports customizing templates for magic links, email verification, password resets, and user invitations.
 *
 * @example
 * ```typescript
 * const templates = client.admin.emailTemplates
 *
 * // List all templates
 * const { templates: allTemplates } = await templates.list()
 *
 * // Get specific template
 * const magicLink = await templates.get('magic_link')
 *
 * // Update template
 * await templates.update('magic_link', {
 *   subject: 'Sign in to ' + '{{.AppName}}',
 *   html_body: '<html>Custom template with ' + '{{.MagicLink}}' + '</html>',
 *   text_body: 'Click here: ' + '{{.MagicLink}}'
 * })
 *
 * // Test template (sends to specified email)
 * await templates.test('magic_link', 'test@example.com')
 *
 * // Reset to default
 * await templates.reset('magic_link')
 * ```
 */
declare class EmailTemplateManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all email templates
     *
     * @returns Promise resolving to ListEmailTemplatesResponse
     *
     * @example
     * ```typescript
     * const response = await client.admin.emailTemplates.list()
     * console.log(response.templates)
     * ```
     */
    list(): Promise<ListEmailTemplatesResponse>;
    /**
     * Get a specific email template by type
     *
     * @param type - Template type (magic_link | verify_email | reset_password | invite_user)
     * @returns Promise resolving to EmailTemplate
     *
     * @example
     * ```typescript
     * const template = await client.admin.emailTemplates.get('magic_link')
     * console.log(template.subject)
     * console.log(template.html_body)
     * ```
     */
    get(type: EmailTemplateType): Promise<EmailTemplate>;
    /**
     * Update an email template
     *
     * Available template variables:
     * - magic_link: `{{.MagicLink}}`, `{{.AppName}}`, `{{.ExpiryMinutes}}`
     * - verify_email: `{{.VerificationLink}}`, `{{.AppName}}`
     * - reset_password: `{{.ResetLink}}`, `{{.AppName}}`, `{{.ExpiryMinutes}}`
     * - invite_user: `{{.InviteLink}}`, `{{.AppName}}`, `{{.InviterName}}`
     *
     * @param type - Template type to update
     * @param request - Update request with subject, html_body, and optional text_body
     * @returns Promise resolving to EmailTemplate
     *
     * @example
     * ```typescript
     * const updated = await client.admin.emailTemplates.update('magic_link', {
     *   subject: 'Your Magic Link - Sign in to ' + '{{.AppName}}',
     *   html_body: '<html><body><h1>Welcome!</h1><a href="' + '{{.MagicLink}}' + '">Sign In</a></body></html>',
     *   text_body: 'Click here to sign in: ' + '{{.MagicLink}}'
     * })
     * ```
     */
    update(type: EmailTemplateType, request: UpdateEmailTemplateRequest): Promise<EmailTemplate>;
    /**
     * Reset an email template to default
     *
     * Removes any customizations and restores the template to its original state.
     *
     * @param type - Template type to reset
     * @returns Promise resolving to EmailTemplate - The default template
     *
     * @example
     * ```typescript
     * const defaultTemplate = await client.admin.emailTemplates.reset('magic_link')
     * ```
     */
    reset(type: EmailTemplateType): Promise<EmailTemplate>;
    /**
     * Send a test email using the template
     *
     * Useful for previewing template changes before deploying to production.
     *
     * @param type - Template type to test
     * @param recipientEmail - Email address to send test to
     * @returns Promise<void>
     *
     * @example
     * ```typescript
     * await client.admin.emailTemplates.test('magic_link', 'test@example.com')
     * ```
     */
    test(type: EmailTemplateType, recipientEmail: string): Promise<void>;
}
/**
 * Email Settings Manager
 *
 * Manages email provider configuration including SMTP, SendGrid, Mailgun, and AWS SES.
 * Provides direct access to the email settings API with proper handling of sensitive credentials.
 *
 * @example
 * ```typescript
 * const email = client.admin.settings.email
 *
 * // Get current email settings
 * const settings = await email.get()
 * console.log(settings.provider) // 'smtp'
 * console.log(settings.smtp_password_set) // true (password is configured)
 *
 * // Update email settings
 * await email.update({
 *   provider: 'sendgrid',
 *   sendgrid_api_key: 'SG.xxx',
 *   from_address: 'noreply@yourapp.com'
 * })
 *
 * // Test email configuration
 * const result = await email.test('test@example.com')
 * console.log(result.success) // true
 *
 * // Convenience methods
 * await email.enable()
 * await email.disable()
 * await email.setProvider('smtp')
 * ```
 */
declare class EmailSettingsManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Get current email provider settings
     *
     * Returns the current email configuration. Sensitive values (passwords, client keys)
     * are not returned - instead, boolean flags indicate whether they are set.
     *
     * @returns Promise resolving to EmailProviderSettings
     *
     * @example
     * ```typescript
     * const settings = await client.admin.settings.email.get()
     *
     * console.log('Provider:', settings.provider)
     * console.log('From:', settings.from_address)
     * console.log('SMTP password configured:', settings.smtp_password_set)
     *
     * // Check for environment variable overrides
     * if (settings._overrides.provider?.is_overridden) {
     *   console.log('Provider is set by env var:', settings._overrides.provider.env_var)
     * }
     * ```
     */
    get(): Promise<EmailProviderSettings>;
    /**
     * Update email provider settings
     *
     * Supports partial updates - only provide the fields you want to change.
     * Secret fields (passwords, client keys) are only updated if provided.
     *
     * @param request - Settings to update (partial update supported)
     * @returns Promise resolving to EmailProviderSettings - Updated settings
     * @throws Error if a setting is overridden by an environment variable
     *
     * @example
     * ```typescript
     * // Configure SMTP
     * await client.admin.settings.email.update({
     *   enabled: true,
     *   provider: 'smtp',
     *   from_address: 'noreply@yourapp.com',
     *   from_name: 'Your App',
     *   smtp_host: 'smtp.gmail.com',
     *   smtp_port: 587,
     *   smtp_username: 'your-email@gmail.com',
     *   smtp_password: 'your-app-password',
     *   smtp_tls: true
     * })
     *
     * // Configure SendGrid
     * await client.admin.settings.email.update({
     *   provider: 'sendgrid',
     *   sendgrid_api_key: 'SG.xxx'
     * })
     *
     * // Update just the from address (password unchanged)
     * await client.admin.settings.email.update({
     *   from_address: 'new-address@yourapp.com'
     * })
     * ```
     */
    update(request: UpdateEmailProviderSettingsRequest): Promise<EmailProviderSettings>;
    /**
     * Test email configuration by sending a test email
     *
     * Sends a test email to verify that the current email configuration is working.
     *
     * @param recipientEmail - Email address to send the test email to
     * @returns Promise resolving to TestEmailSettingsResponse
     * @throws Error if email sending fails
     *
     * @example
     * ```typescript
     * try {
     *   const result = await client.admin.settings.email.test('admin@yourapp.com')
     *   console.log('Test email sent:', result.message)
     * } catch (error) {
     *   console.error('Email configuration error:', error.message)
     * }
     * ```
     */
    test(recipientEmail: string): Promise<TestEmailSettingsResponse>;
    /**
     * Enable email functionality
     *
     * Convenience method to enable the email system.
     *
     * @returns Promise resolving to EmailProviderSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.email.enable()
     * ```
     */
    enable(): Promise<EmailProviderSettings>;
    /**
     * Disable email functionality
     *
     * Convenience method to disable the email system.
     *
     * @returns Promise resolving to EmailProviderSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.email.disable()
     * ```
     */
    disable(): Promise<EmailProviderSettings>;
    /**
     * Set the email provider
     *
     * Convenience method to change the email provider.
     * Note: You'll also need to configure the provider-specific settings.
     *
     * @param provider - The email provider to use
     * @returns Promise resolving to EmailProviderSettings
     *
     * @example
     * ```typescript
     * await client.admin.settings.email.setProvider('sendgrid')
     * ```
     */
    setProvider(provider: "smtp" | "sendgrid" | "mailgun" | "ses"): Promise<EmailProviderSettings>;
    /**
     * Get tenant-level email settings (resolved through cascade)
     *
     * Returns email settings resolved for the current tenant context,
     * including source information for each field.
     *
     * @returns Promise resolving to TenantEmailProviderSettings
     */
    getForTenant(): Promise<TenantEmailProviderSettings>;
    /**
     * Update tenant-level email settings
     *
     * Only provided fields are updated. These override instance-level defaults.
     *
     * @param request - Settings to update
     * @returns Promise resolving to TenantEmailProviderSettings
     */
    updateForTenant(request: UpdateEmailProviderSettingsRequest): Promise<TenantEmailProviderSettings>;
    /**
     * Delete a tenant-level email setting override
     *
     * Removes the tenant override for a specific field, reverting to the instance default.
     *
     * @param field - The field name to remove the override for
     * @returns Promise resolving to TenantEmailProviderSettings
     */
    deleteTenantOverride(field: string): Promise<TenantEmailProviderSettings>;
    /**
     * Test tenant-level email configuration
     *
     * @param recipientEmail - Email address to send the test email to
     * @returns Promise resolving to TestEmailSettingsResponse
     */
    testForTenant(recipientEmail: string): Promise<TestEmailSettingsResponse>;
}
/**
 * Settings Manager
 *
 * Provides access to system-level, application-level, and email settings.
 * AppSettingsManager handles both structured framework settings and custom key-value settings.
 * EmailSettingsManager provides direct access to email provider configuration.
 *
 * @example
 * ```typescript
 * const settings = client.admin.settings
 *
 * // Access system settings
 * const systemSettings = await settings.system.list()
 *
 * // Access app settings (structured)
 * const appSettings = await settings.app.get()
 * await settings.app.enableSignup()
 *
 * // Access custom settings (key-value)
 * await settings.app.setSetting('billing.tiers', { free: 1000, pro: 10000 })
 * const tiers = await settings.app.getSetting('billing.tiers')
 *
 * // Access email settings
 * const emailSettings = await settings.email.get()
 * await settings.email.update({ provider: 'sendgrid', sendgrid_api_key: 'SG.xxx' })
 * await settings.email.test('admin@yourapp.com')
 * ```
 */
declare class FluxbaseSettings {
    system: SystemSettingsManager;
    app: AppSettingsManager;
    email: EmailSettingsManager;
    constructor(fetch: FluxbaseFetch);
}
/**
 * Public Settings Client
 *
 * Provides read-only access to public settings for non-admin users.
 * Access is controlled by RLS policies on the app.settings table.
 *
 * @example
 * ```typescript
 * const client = new FluxbaseClient(url, userToken)
 *
 * // Get single public setting
 * const betaEnabled = await client.settings.get('features.beta_enabled')
 * console.log(betaEnabled) // { enabled: true }
 *
 * // Get multiple public settings
 * const values = await client.settings.getMany([
 *   'features.beta_enabled',
 *   'features.dark_mode',
 *   'public.app_version'
 * ])
 * console.log(values)
 * // {
 * //   'features.beta_enabled': { enabled: true },
 * //   'features.dark_mode': { enabled: false },
 * //   'public.app_version': '1.0.0'
 * // }
 * ```
 */
declare class SettingsClient {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Get a single setting's value
     *
     * Returns only the value field of the setting.
     * Access is controlled by RLS policies - will return 403 if the user
     * doesn't have permission to read the setting.
     *
     * @param key - Setting key (e.g., 'features.beta_enabled')
     * @returns Promise resolving to the setting's value
     * @throws Error if setting doesn't exist or user lacks permission
     *
     * @example
     * ```typescript
     * // Get public setting (any user)
     * const value = await client.settings.get('features.beta_enabled')
     * console.log(value) // { enabled: true }
     *
     * // Get restricted setting (requires permission)
     * try {
     *   const secret = await client.settings.get('internal.api_key')
     * } catch (error) {
     *   console.error('Access denied:', error)
     * }
     * ```
     */
    get(key: string): Promise<any>;
    /**
     * Get multiple settings' values by keys
     *
     * Fetches multiple settings in a single request.
     * Only returns settings the user has permission to read based on RLS policies.
     * Settings the user can't access will be omitted from the result (no error thrown).
     *
     * @param keys - Array of setting keys to fetch
     * @returns Promise resolving to object mapping keys to values
     *
     * @example
     * ```typescript
     * const values = await client.settings.getMany([
     *   'features.beta_enabled',  // public - will be returned
     *   'features.dark_mode',      // public - will be returned
     *   'internal.api_key'         // secret - will be omitted
     * ])
     * console.log(values)
     * // {
     * //   'features.beta_enabled': { enabled: true },
     * //   'features.dark_mode': { enabled: false }
     * //   // 'internal.api_key' is omitted (no error)
     * // }
     * ```
     */
    getMany(keys: string[]): Promise<Record<string, any>>;
    /**
     * Set a user secret setting (encrypted)
     *
     * Creates or updates an encrypted secret that belongs to the current user.
     * The value is encrypted server-side with a user-specific key and can only be
     * accessed by edge functions, background jobs, or custom handlers running on
     * behalf of this user. Even admins cannot see the decrypted value.
     *
     * @param key - Secret key
     * @param value - Secret value (will be encrypted server-side)
     * @param options - Optional description
     * @returns Promise resolving to SecretSettingMetadata (never includes the value)
     *
     * @example
     * ```typescript
     * // Store user's API key for a third-party service
     * await client.settings.setSecret('openai_api_key', 'sk-abc123', {
     *   description: 'My OpenAI API key'
     * })
     * ```
     */
    setSecret(key: string, value: string, options?: {
        description?: string;
    }): Promise<SecretSettingMetadata>;
    /**
     * Get metadata for a user secret setting (never returns the value)
     *
     * @param key - Secret key
     * @returns Promise resolving to SecretSettingMetadata
     *
     * @example
     * ```typescript
     * const metadata = await client.settings.getSecret('openai_api_key')
     * console.log(metadata.key, metadata.updated_at)
     * // Note: The actual secret value is never returned
     * ```
     */
    getSecret(key: string): Promise<SecretSettingMetadata>;
    /**
     * List all user's secret settings (metadata only, never includes values)
     *
     * @returns Promise resolving to array of SecretSettingMetadata
     *
     * @example
     * ```typescript
     * const secrets = await client.settings.listSecrets()
     * secrets.forEach(s => console.log(s.key, s.description))
     * ```
     */
    listSecrets(): Promise<SecretSettingMetadata[]>;
    /**
     * Delete a user secret setting
     *
     * @param key - Secret key to delete
     * @returns Promise<void>
     *
     * @example
     * ```typescript
     * await client.settings.deleteSecret('openai_api_key')
     * ```
     */
    deleteSecret(key: string): Promise<void>;
    /**
     * Get a setting with user -> system fallback
     *
     * First checks for a user-specific setting, then falls back to system default.
     * Returns both the value and the source ("user" or "system").
     *
     * @param key - Setting key (e.g., 'theme', 'notifications.email')
     * @returns Promise resolving to UserSettingWithSource with value and source
     * @throws Error if setting doesn't exist in either user or system
     *
     * @example
     * ```typescript
     * // Get theme with fallback to system default
     * const { value, source } = await client.settings.getSetting('theme')
     * console.log(value)   // { mode: 'dark' }
     * console.log(source)  // 'system' (from system default)
     *
     * // After user sets their own theme
     * const { value, source } = await client.settings.getSetting('theme')
     * console.log(source)  // 'user' (user's own setting)
     * ```
     */
    getSetting(key: string): Promise<UserSettingWithSource>;
    /**
     * Get only the user's own setting (no fallback to system)
     *
     * Returns the user's own setting for this key, or throws if not found.
     * Use this when you specifically want to check if the user has set a value.
     *
     * @param key - Setting key
     * @returns Promise resolving to UserSetting
     * @throws Error if user has no setting with this key
     *
     * @example
     * ```typescript
     * // Check if user has set their own theme
     * try {
     *   const setting = await client.settings.getUserSetting('theme')
     *   console.log('User theme:', setting.value)
     * } catch (e) {
     *   console.log('User has not set a theme')
     * }
     * ```
     */
    getUserSetting(key: string): Promise<UserSetting>;
    /**
     * Get a system-level setting (no user override)
     *
     * Returns the system default for this key, ignoring any user-specific value.
     * Useful for reading default configurations.
     *
     * @param key - Setting key
     * @returns Promise resolving to the setting value
     * @throws Error if system setting doesn't exist
     *
     * @example
     * ```typescript
     * // Get system default theme
     * const { value } = await client.settings.getSystemSetting('theme')
     * console.log('System default theme:', value)
     * ```
     */
    getSystemSetting(key: string): Promise<{
        key: string;
        value: Record<string, unknown>;
    }>;
    /**
     * Set a user setting (create or update)
     *
     * Creates or updates a non-encrypted user setting.
     * This value will override any system default when using getSetting().
     *
     * @param key - Setting key
     * @param value - Setting value (any JSON-serializable object)
     * @param options - Optional description
     * @returns Promise resolving to UserSetting
     *
     * @example
     * ```typescript
     * // Set user's theme preference
     * await client.settings.setSetting('theme', { mode: 'dark', accent: 'blue' })
     *
     * // Set with description
     * await client.settings.setSetting('notifications', { email: true, push: false }, {
     *   description: 'User notification preferences'
     * })
     * ```
     */
    setSetting(key: string, value: Record<string, unknown>, options?: {
        description?: string;
    }): Promise<UserSetting>;
    /**
     * List all user's own settings
     *
     * Returns all non-encrypted settings the current user has set.
     * Does not include system defaults.
     *
     * @returns Promise resolving to array of UserSetting
     *
     * @example
     * ```typescript
     * const settings = await client.settings.listSettings()
     * settings.forEach(s => console.log(s.key, s.value))
     * ```
     */
    listSettings(): Promise<UserSetting[]>;
    /**
     * Delete a user setting
     *
     * Removes the user's own setting, reverting to system default (if any).
     *
     * @param key - Setting key to delete
     * @returns Promise<void>
     *
     * @example
     * ```typescript
     * // Remove user's theme preference, revert to system default
     * await client.settings.deleteSetting('theme')
     * ```
     */
    deleteSetting(key: string): Promise<void>;
}

/**
 * DDL (Data Definition Language) Manager
 *
 * Provides methods for managing database schemas and tables programmatically.
 * This includes creating schemas, creating tables with custom columns, listing
 * schemas and tables, and deleting tables.
 *
 * @example
 * ```typescript
 * const ddl = client.admin.ddl
 *
 * // Create a new schema
 * await ddl.createSchema('analytics')
 *
 * // Create a table with columns
 * await ddl.createTable('analytics', 'events', [
 *   { name: 'id', type: 'UUID', primaryKey: true, defaultValue: 'gen_random_uuid()' },
 *   { name: 'user_id', type: 'UUID', nullable: false },
 *   { name: 'event_name', type: 'TEXT', nullable: false },
 *   { name: 'event_data', type: 'JSONB' },
 *   { name: 'created_at', type: 'TIMESTAMPTZ', defaultValue: 'NOW()' }
 * ])
 *
 * // List all schemas
 * const { schemas } = await ddl.listSchemas()
 *
 * // List all tables in a schema
 * const { tables } = await ddl.listTables('analytics')
 *
 * // Delete a table
 * await ddl.deleteTable('analytics', 'events')
 * ```
 */
declare class DDLManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Create a new database schema
     *
     * Creates a new schema in the database. Schemas are used to organize tables
     * into logical groups and provide namespace isolation.
     *
     * @param name - Schema name (must be valid PostgreSQL identifier)
     * @returns Promise resolving to CreateSchemaResponse
     *
     * @example
     * ```typescript
     * // Create a schema for analytics data
     * const result = await client.admin.ddl.createSchema('analytics')
     * console.log(result.message) // "Schema created successfully"
     * console.log(result.schema)  // "analytics"
     * ```
     */
    createSchema(name: string): Promise<CreateSchemaResponse>;
    /**
     * List all database schemas
     *
     * Retrieves a list of all schemas in the database. This includes both
     * system schemas (like 'public', 'pg_catalog') and user-created schemas.
     *
     * @returns Promise resolving to ListSchemasResponse
     *
     * @example
     * ```typescript
     * const { schemas } = await client.admin.ddl.listSchemas()
     *
     * schemas.forEach(schema => {
     *   console.log(`Schema: ${schema.name}, Owner: ${schema.owner}`)
     * })
     * ```
     */
    listSchemas(): Promise<ListSchemasResponse>;
    /**
     * Create a new table in a schema
     *
     * Creates a new table with the specified columns. Supports various column
     * options including primary keys, nullability, data types, and default values.
     *
     * @param schema - Schema name where the table will be created
     * @param name - Table name (must be valid PostgreSQL identifier)
     * @param columns - Array of column definitions
     * @returns Promise resolving to CreateTableResponse
     *
     * @example
     * ```typescript
     * // Create a users table
     * await client.admin.ddl.createTable('public', 'users', [
     *   {
     *     name: 'id',
     *     type: 'UUID',
     *     primaryKey: true,
     *     defaultValue: 'gen_random_uuid()'
     *   },
     *   {
     *     name: 'email',
     *     type: 'TEXT',
     *     nullable: false
     *   },
     *   {
     *     name: 'name',
     *     type: 'TEXT'
     *   },
     *   {
     *     name: 'created_at',
     *     type: 'TIMESTAMPTZ',
     *     nullable: false,
     *     defaultValue: 'NOW()'
     *   }
     * ])
     * ```
     *
     * @example
     * ```typescript
     * // Create a products table with JSONB metadata
     * await client.admin.ddl.createTable('public', 'products', [
     *   { name: 'id', type: 'SERIAL', primaryKey: true },
     *   { name: 'name', type: 'TEXT', nullable: false },
     *   { name: 'price', type: 'DECIMAL(10,2)', nullable: false },
     *   { name: 'metadata', type: 'JSONB' },
     *   { name: 'in_stock', type: 'BOOLEAN', defaultValue: 'true' }
     * ])
     * ```
     */
    createTable(schema: string, name: string, columns: CreateColumnRequest[]): Promise<CreateTableResponse>;
    /**
     * List all tables in the database or a specific schema
     *
     * Retrieves a list of all tables. If a schema is specified, only tables
     * from that schema are returned. Otherwise, all tables from all schemas
     * are returned.
     *
     * @param schema - Optional schema name to filter tables
     * @returns Promise resolving to ListTablesResponse
     *
     * @example
     * ```typescript
     * // List all tables in the public schema
     * const { tables } = await client.admin.ddl.listTables('public')
     *
     * tables.forEach(table => {
     *   console.log(`Table: ${table.schema}.${table.name}`)
     *   table.columns?.forEach(col => {
     *     console.log(`  - ${col.name}: ${col.type}`)
     *   })
     * })
     * ```
     *
     * @example
     * ```typescript
     * // List all tables across all schemas
     * const { tables } = await client.admin.ddl.listTables()
     *
     * const tablesBySchema = tables.reduce((acc, table) => {
     *   if (!acc[table.schema]) acc[table.schema] = []
     *   acc[table.schema].push(table.name)
     *   return acc
     * }, {} as Record<string, string[]>)
     *
     * console.log(tablesBySchema)
     * ```
     */
    listTables(schema?: string): Promise<ListTablesResponse>;
    /**
     * Delete a table from a schema
     *
     * Permanently deletes a table and all its data. This operation cannot be undone.
     *
     * @param schema - Schema name containing the table
     * @param name - Table name to delete
     * @returns Promise resolving to DeleteTableResponse
     *
     * @example
     * ```typescript
     * // Delete a table
     * const result = await client.admin.ddl.deleteTable('public', 'old_data')
     * console.log(result.message) // "Table deleted successfully"
     * ```
     *
     * @example
     * ```typescript
     * // Safe deletion with confirmation
     * const confirm = await askUser('Are you sure you want to delete this table?')
     * if (confirm) {
     *   await client.admin.ddl.deleteTable('analytics', 'events')
     *   console.log('Table deleted')
     * }
     * ```
     */
    deleteTable(schema: string, name: string): Promise<DeleteTableResponse>;
}

/**
 * OAuth Provider Manager
 *
 * Manages OAuth provider configurations for third-party authentication.
 * Supports both built-in providers (Google, GitHub, etc.) and custom OAuth2 providers.
 *
 * @example
 * ```typescript
 * const oauth = client.admin.oauth
 *
 * // List all OAuth providers
 * const { providers } = await oauth.listProviders()
 *
 * // Create a new provider
 * await oauth.createProvider({
 *   provider_name: 'github',
 *   display_name: 'GitHub',
 *   enabled: true,
 *   client_id: 'your-client-id',
 *   client_secret: 'your-client-secret',
 *   redirect_url: 'https://yourapp.com/auth/callback',
 *   scopes: ['user:email', 'read:user'],
 *   is_custom: false
 * })
 *
 * // Update a provider
 * await oauth.updateProvider('provider-id', {
 *   enabled: false
 * })
 *
 * // Delete a provider
 * await oauth.deleteProvider('provider-id')
 * ```
 */
declare class OAuthProviderManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all OAuth providers
     *
     * Retrieves all configured OAuth providers including both enabled and disabled providers.
     * Note: Client secrets are not included in the response for security reasons.
     *
     * @returns Promise resolving to ListOAuthProvidersResponse
     *
     * @example
     * ```typescript
     * const { providers } = await client.admin.oauth.listProviders()
     *
     * providers.forEach(provider => {
     *   console.log(`${provider.display_name}: ${provider.enabled ? 'enabled' : 'disabled'}`)
     * })
     * ```
     */
    listProviders(): Promise<OAuthProvider[]>;
    /**
     * Get a specific OAuth provider by ID
     *
     * Retrieves detailed configuration for a single OAuth provider.
     * Note: Client secret is not included in the response.
     *
     * @param providerId - Provider ID (UUID)
     * @returns Promise resolving to OAuthProvider
     *
     * @example
     * ```typescript
     * const provider = await client.admin.oauth.getProvider('provider-uuid')
     *
     * console.log('Provider:', provider.display_name)
     * console.log('Scopes:', provider.scopes.join(', '))
     * console.log('Redirect URL:', provider.redirect_url)
     * ```
     */
    getProvider(providerId: string): Promise<OAuthProvider>;
    /**
     * Create a new OAuth provider
     *
     * Creates a new OAuth provider configuration. For built-in providers (Google, GitHub, etc.),
     * set `is_custom` to false. For custom OAuth2 providers, set `is_custom` to true and provide
     * the authorization, token, and user info URLs.
     *
     * @param request - OAuth provider configuration
     * @returns Promise resolving to CreateOAuthProviderResponse
     *
     * @example
     * ```typescript
     * // Create GitHub provider
     * const result = await client.admin.oauth.createProvider({
     *   provider_name: 'github',
     *   display_name: 'GitHub',
     *   enabled: true,
     *   client_id: process.env.GITHUB_CLIENT_ID,
     *   client_secret: process.env.GITHUB_CLIENT_SECRET,
     *   redirect_url: 'https://yourapp.com/auth/callback',
     *   scopes: ['user:email', 'read:user'],
     *   is_custom: false
     * })
     *
     * console.log('Provider created:', result.id)
     * ```
     *
     * @example
     * ```typescript
     * // Create custom OAuth2 provider
     * await client.admin.oauth.createProvider({
     *   provider_name: 'custom_sso',
     *   display_name: 'Custom SSO',
     *   enabled: true,
     *   client_id: 'client-id',
     *   client_secret: 'client-secret',
     *   redirect_url: 'https://yourapp.com/auth/callback',
     *   scopes: ['openid', 'profile', 'email', 'offline_access'],
     *   is_custom: true,
     *   authorization_url: 'https://sso.example.com/oauth/authorize',
     *   token_url: 'https://sso.example.com/oauth/token',
     *   user_info_url: 'https://sso.example.com/oauth/userinfo'
     * })
     * ```
     */
    createProvider(request: CreateOAuthProviderRequest): Promise<CreateOAuthProviderResponse>;
    /**
     * Update an existing OAuth provider
     *
     * Updates an OAuth provider configuration. All fields are optional - only provided fields
     * will be updated. To update the client secret, provide a non-empty value.
     *
     * @param providerId - Provider ID (UUID)
     * @param request - Fields to update
     * @returns Promise resolving to UpdateOAuthProviderResponse
     *
     * @example
     * ```typescript
     * // Disable a provider
     * await client.admin.oauth.updateProvider('provider-id', {
     *   enabled: false
     * })
     * ```
     *
     * @example
     * ```typescript
     * // Update scopes and redirect URL
     * await client.admin.oauth.updateProvider('provider-id', {
     *   scopes: ['user:email', 'read:user', 'read:org'],
     *   redirect_url: 'https://newdomain.com/auth/callback'
     * })
     * ```
     *
     * @example
     * ```typescript
     * // Rotate client secret
     * await client.admin.oauth.updateProvider('provider-id', {
     *   client_id: 'new-client-id',
     *   client_secret: 'new-client-secret'
     * })
     * ```
     */
    updateProvider(providerId: string, request: UpdateOAuthProviderRequest): Promise<UpdateOAuthProviderResponse>;
    /**
     * Delete an OAuth provider
     *
     * Permanently deletes an OAuth provider configuration. This will prevent users from
     * authenticating with this provider.
     *
     * @param providerId - Provider ID (UUID) to delete
     * @returns Promise resolving to DeleteOAuthProviderResponse
     *
     * @example
     * ```typescript
     * await client.admin.oauth.deleteProvider('provider-id')
     * console.log('Provider deleted')
     * ```
     *
     * @example
     * ```typescript
     * // Safe deletion with confirmation
     * const provider = await client.admin.oauth.getProvider('provider-id')
     * const confirmed = await confirm(`Delete ${provider.display_name}?`)
     *
     * if (confirmed) {
     *   await client.admin.oauth.deleteProvider('provider-id')
     * }
     * ```
     */
    deleteProvider(providerId: string): Promise<DeleteOAuthProviderResponse>;
    /**
     * Enable an OAuth provider
     *
     * Convenience method to enable a provider.
     *
     * @param providerId - Provider ID (UUID)
     * @returns Promise resolving to UpdateOAuthProviderResponse
     *
     * @example
     * ```typescript
     * await client.admin.oauth.enableProvider('provider-id')
     * ```
     */
    enableProvider(providerId: string): Promise<UpdateOAuthProviderResponse>;
    /**
     * Disable an OAuth provider
     *
     * Convenience method to disable a provider.
     *
     * @param providerId - Provider ID (UUID)
     * @returns Promise resolving to UpdateOAuthProviderResponse
     *
     * @example
     * ```typescript
     * await client.admin.oauth.disableProvider('provider-id')
     * ```
     */
    disableProvider(providerId: string): Promise<UpdateOAuthProviderResponse>;
}
/**
 * Authentication Settings Manager
 *
 * Manages global authentication settings including password requirements, session timeouts,
 * and signup configuration.
 *
 * @example
 * ```typescript
 * const authSettings = client.admin.authSettings
 *
 * // Get current settings
 * const settings = await authSettings.get()
 *
 * // Update settings
 * await authSettings.update({
 *   password_min_length: 12,
 *   password_require_uppercase: true,
 *   session_timeout_minutes: 120
 * })
 * ```
 */
declare class AuthSettingsManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Get current authentication settings
     *
     * Retrieves all authentication configuration settings.
     *
     * @returns Promise resolving to AuthSettings
     *
     * @example
     * ```typescript
     * const settings = await client.admin.authSettings.get()
     *
     * console.log('Password min length:', settings.password_min_length)
     * console.log('Signup enabled:', settings.enable_signup)
     * console.log('Session timeout:', settings.session_timeout_minutes, 'minutes')
     * ```
     */
    get(): Promise<AuthSettings>;
    /**
     * Update authentication settings
     *
     * Updates one or more authentication settings. All fields are optional - only provided
     * fields will be updated.
     *
     * @param request - Settings to update
     * @returns Promise resolving to UpdateAuthSettingsResponse
     *
     * @example
     * ```typescript
     * // Strengthen password requirements
     * await client.admin.authSettings.update({
     *   password_min_length: 16,
     *   password_require_uppercase: true,
     *   password_require_lowercase: true,
     *   password_require_number: true,
     *   password_require_special: true
     * })
     * ```
     *
     * @example
     * ```typescript
     * // Extend session timeout
     * await client.admin.authSettings.update({
     *   session_timeout_minutes: 240,
     *   max_sessions_per_user: 10
     * })
     * ```
     *
     * @example
     * ```typescript
     * // Disable email verification during development
     * await client.admin.authSettings.update({
     *   require_email_verification: false
     * })
     * ```
     */
    update(request: UpdateAuthSettingsRequest): Promise<UpdateAuthSettingsResponse>;
}
/**
 * OAuth Configuration Manager
 *
 * Root manager providing access to OAuth provider and authentication settings management.
 *
 * @example
 * ```typescript
 * const oauth = client.admin.oauth
 *
 * // Manage OAuth providers
 * const providers = await oauth.providers.listProviders()
 *
 * // Manage auth settings
 * const settings = await oauth.authSettings.get()
 * ```
 */
declare class FluxbaseOAuth {
    providers: OAuthProviderManager;
    authSettings: AuthSettingsManager;
    constructor(fetch: FluxbaseFetch);
}

/**
 * Impersonation Manager
 *
 * Manages user impersonation for debugging, testing RLS policies, and customer support.
 * Allows admins to view data as different users, anonymous visitors, or with service role permissions.
 *
 * All impersonation sessions are logged in the audit trail for security and compliance.
 *
 * @example
 * ```typescript
 * const impersonation = client.admin.impersonation
 *
 * // Impersonate a specific user
 * const { session, access_token } = await impersonation.impersonateUser({
 *   target_user_id: 'user-uuid',
 *   reason: 'Support ticket #1234'
 * })
 *
 * // Impersonate anonymous user
 * await impersonation.impersonateAnon({
 *   reason: 'Testing public data access'
 * })
 *
 * // Impersonate with service role
 * await impersonation.impersonateService({
 *   reason: 'Administrative query'
 * })
 *
 * // Stop impersonation
 * await impersonation.stop()
 * ```
 */
declare class ImpersonationManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Impersonate a specific user
     *
     * Start an impersonation session as a specific user. This allows you to see data
     * exactly as that user would see it, respecting all RLS policies and permissions.
     *
     * @param request - Impersonation request with target user ID and reason
     * @returns Promise resolving to impersonation session with access token
     *
     * @example
     * ```typescript
     * const result = await client.admin.impersonation.impersonateUser({
     *   target_user_id: 'user-123',
     *   reason: 'Support ticket #5678 - user reports missing data'
     * })
     *
     * console.log('Impersonating:', result.target_user.email)
     * console.log('Session ID:', result.session.id)
     *
     * // Use the access token for subsequent requests
     * // (typically handled automatically by the SDK)
     * ```
     */
    impersonateUser(request: ImpersonateUserRequest): Promise<StartImpersonationResponse>;
    /**
     * Impersonate anonymous user
     *
     * Start an impersonation session as an unauthenticated user. This allows you to see
     * what data is publicly accessible and test RLS policies for anonymous access.
     *
     * @param request - Impersonation request with reason
     * @returns Promise resolving to impersonation session with access token
     *
     * @example
     * ```typescript
     * await client.admin.impersonation.impersonateAnon({
     *   reason: 'Testing public data access for blog posts'
     * })
     *
     * // Now all queries will use anonymous permissions
     * const publicPosts = await client.from('posts').select('*')
     * console.log('Public posts:', publicPosts.length)
     * ```
     */
    impersonateAnon(request: ImpersonateAnonRequest): Promise<StartImpersonationResponse>;
    /**
     * Impersonate with service role
     *
     * Start an impersonation session with service-level permissions. This provides elevated
     * access that may bypass RLS policies, useful for administrative operations.
     *
     * @param request - Impersonation request with reason
     * @returns Promise resolving to impersonation session with access token
     *
     * @example
     * ```typescript
     * await client.admin.impersonation.impersonateService({
     *   reason: 'Administrative data cleanup'
     * })
     *
     * // Now all queries will use service role permissions
     * const allRecords = await client.from('sensitive_data').select('*')
     * console.log('All records:', allRecords.length)
     * ```
     */
    impersonateService(request: ImpersonateServiceRequest): Promise<StartImpersonationResponse>;
    /**
     * Stop impersonation
     *
     * Ends the current impersonation session and returns to admin context.
     * The session is marked as ended in the audit trail.
     *
     * @returns Promise resolving to stop confirmation
     *
     * @example
     * ```typescript
     * await client.admin.impersonation.stop()
     * console.log('Impersonation ended')
     *
     * // Subsequent queries will use admin permissions
     * ```
     */
    stop(): Promise<StopImpersonationResponse>;
    /**
     * Get current impersonation session
     *
     * Retrieves information about the active impersonation session, if any.
     *
     * @returns Promise resolving to current impersonation session or null
     *
     * @example
     * ```typescript
     * const current = await client.admin.impersonation.getCurrent()
     *
     * if (current.session) {
     *   console.log('Currently impersonating:', current.target_user?.email)
     *   console.log('Reason:', current.session.reason)
     *   console.log('Started:', current.session.started_at)
     * } else {
     *   console.log('No active impersonation')
     * }
     * ```
     */
    getCurrent(): Promise<GetImpersonationResponse>;
    /**
     * List impersonation sessions (audit trail)
     *
     * Retrieves a list of impersonation sessions for audit and compliance purposes.
     * Can be filtered by admin user, target user, type, and active status.
     *
     * @param options - Filter and pagination options
     * @returns Promise resolving to list of impersonation sessions
     *
     * @example
     * ```typescript
     * // List all sessions
     * const { sessions, total } = await client.admin.impersonation.listSessions()
     * console.log(`Total sessions: ${total}`)
     *
     * // List active sessions only
     * const active = await client.admin.impersonation.listSessions({
     *   is_active: true
     * })
     * console.log('Active sessions:', active.sessions.length)
     *
     * // List sessions for a specific admin
     * const adminSessions = await client.admin.impersonation.listSessions({
     *   admin_user_id: 'admin-uuid',
     *   limit: 50
     * })
     *
     * // List user impersonation sessions only
     * const userSessions = await client.admin.impersonation.listSessions({
     *   impersonation_type: 'user',
     *   offset: 0,
     *   limit: 100
     * })
     * ```
     *
     * @example
     * ```typescript
     * // Audit trail: Find who impersonated a specific user
     * const userHistory = await client.admin.impersonation.listSessions({
     *   target_user_id: 'user-uuid'
     * })
     *
     * userHistory.sessions.forEach(session => {
     *   console.log(`Admin ${session.admin_user_id} impersonated user`)
     *   console.log(`Reason: ${session.reason}`)
     *   console.log(`Duration: ${session.started_at} - ${session.ended_at}`)
     * })
     * ```
     */
    listSessions(options?: ListImpersonationSessionsOptions): Promise<ListImpersonationSessionsResponse>;
}

/**
 * Client Keys management client
 *
 * Provides methods for managing client keys for service-to-service authentication.
 * Client keys allow external services to authenticate without user credentials.
 *
 * @example
 * ```typescript
 * const client = createClient({ url: 'http://localhost:8080' })
 * await client.auth.login({ email: 'user@example.com', password: 'password' })
 *
 * // Create a client key
 * const { client_key, key } = await client.management.clientKeys.create({
 *   name: 'Production Service',
 *   scopes: ['read:users', 'write:users'],
 *   rate_limit_per_minute: 100
 * })
 *
 * // List client keys
 * const { client_keys } = await client.management.clientKeys.list()
 * ```
 *
 * @category Management
 */
declare class ClientKeysManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Create a new client key
     *
     * @param request - Client key configuration
     * @returns Created client key with the full key value (only shown once)
     *
     * @example
     * ```typescript
     * const { client_key, key } = await client.management.clientKeys.create({
     *   name: 'Production Service',
     *   description: 'Client key for production service',
     *   scopes: ['read:users', 'write:users'],
     *   rate_limit_per_minute: 100,
     *   expires_at: '2025-12-31T23:59:59Z'
     * })
     *
     * // Store the key securely - it won't be shown again
     * console.log('Client Key:', key)
     * ```
     */
    create(request: CreateClientKeyRequest): Promise<CreateClientKeyResponse>;
    /**
     * List all client keys for the authenticated user
     *
     * @returns List of client keys (without full key values)
     *
     * @example
     * ```typescript
     * const { client_keys, total } = await client.management.clientKeys.list()
     *
     * client_keys.forEach(key => {
     *   console.log(`${key.name}: ${key.key_prefix}... (expires: ${key.expires_at})`)
     * })
     * ```
     */
    list(): Promise<ListClientKeysResponse>;
    /**
     * Get a specific client key by ID
     *
     * @param keyId - Client key ID
     * @returns Client key details
     *
     * @example
     * ```typescript
     * const clientKey = await client.management.clientKeys.get('key-uuid')
     * console.log('Last used:', clientKey.last_used_at)
     * ```
     */
    get(keyId: string): Promise<ClientKey>;
    /**
     * Update a client key
     *
     * @param keyId - Client key ID
     * @param updates - Fields to update
     * @returns Updated client key
     *
     * @example
     * ```typescript
     * const updated = await client.management.clientKeys.update('key-uuid', {
     *   name: 'Updated Name',
     *   rate_limit_per_minute: 200
     * })
     * ```
     */
    update(keyId: string, updates: UpdateClientKeyRequest): Promise<ClientKey>;
    /**
     * Revoke a client key
     *
     * Revoked keys can no longer be used but remain in the system for audit purposes.
     *
     * @param keyId - Client key ID
     * @returns Revocation confirmation
     *
     * @example
     * ```typescript
     * await client.management.clientKeys.revoke('key-uuid')
     * console.log('Client key revoked')
     * ```
     */
    revoke(keyId: string): Promise<RevokeClientKeyResponse>;
    /**
     * Delete a client key
     *
     * Permanently removes the client key from the system.
     *
     * @param keyId - Client key ID
     * @returns Deletion confirmation
     *
     * @example
     * ```typescript
     * await client.management.clientKeys.delete('key-uuid')
     * console.log('Client key deleted')
     * ```
     */
    delete(keyId: string): Promise<DeleteClientKeyResponse>;
}
/**
 * @deprecated Use ClientKeysManager instead
 */
declare const APIKeysManager: typeof ClientKeysManager;
/**
 * Webhooks management client
 *
 * Provides methods for managing webhooks to receive real-time event notifications.
 * Webhooks allow your application to be notified when events occur in Fluxbase.
 *
 * @example
 * ```typescript
 * const client = createClient({ url: 'http://localhost:8080' })
 * await client.auth.login({ email: 'user@example.com', password: 'password' })
 *
 * // Create a webhook
 * const webhook = await client.management.webhooks.create({
 *   url: 'https://myapp.com/webhook',
 *   events: ['user.created', 'user.updated'],
 *   secret: 'my-webhook-secret'
 * })
 *
 * // Test the webhook
 * const result = await client.management.webhooks.test(webhook.id)
 * ```
 *
 * @category Management
 */
declare class WebhooksManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Create a new webhook
     *
     * @param request - Webhook configuration
     * @returns Created webhook
     *
     * @example
     * ```typescript
     * const webhook = await client.management.webhooks.create({
     *   url: 'https://myapp.com/webhook',
     *   events: ['user.created', 'user.updated', 'user.deleted'],
     *   description: 'User events webhook',
     *   secret: 'my-webhook-secret'
     * })
     * ```
     */
    create(request: CreateWebhookRequest): Promise<Webhook>;
    /**
     * List all webhooks for the authenticated user
     *
     * @returns List of webhooks
     *
     * @example
     * ```typescript
     * const { webhooks, total } = await client.management.webhooks.list()
     *
     * webhooks.forEach(webhook => {
     *   console.log(`${webhook.url}: ${webhook.is_active ? 'active' : 'inactive'}`)
     * })
     * ```
     */
    list(): Promise<ListWebhooksResponse>;
    /**
     * Get a specific webhook by ID
     *
     * @param webhookId - Webhook ID
     * @returns Webhook details
     *
     * @example
     * ```typescript
     * const webhook = await client.management.webhooks.get('webhook-uuid')
     * console.log('Events:', webhook.events)
     * ```
     */
    get(webhookId: string): Promise<Webhook>;
    /**
     * Update a webhook
     *
     * @param webhookId - Webhook ID
     * @param updates - Fields to update
     * @returns Updated webhook
     *
     * @example
     * ```typescript
     * const updated = await client.management.webhooks.update('webhook-uuid', {
     *   events: ['user.created', 'user.deleted'],
     *   is_active: false
     * })
     * ```
     */
    update(webhookId: string, updates: UpdateWebhookRequest): Promise<Webhook>;
    /**
     * Delete a webhook
     *
     * @param webhookId - Webhook ID
     * @returns Deletion confirmation
     *
     * @example
     * ```typescript
     * await client.management.webhooks.delete('webhook-uuid')
     * console.log('Webhook deleted')
     * ```
     */
    delete(webhookId: string): Promise<DeleteWebhookResponse>;
    /**
     * Test a webhook by sending a test payload
     *
     * @param webhookId - Webhook ID
     * @returns Test result with status and response
     *
     * @example
     * ```typescript
     * const result = await client.management.webhooks.test('webhook-uuid')
     *
     * if (result.success) {
     *   console.log('Webhook test successful')
     * } else {
     *   console.error('Webhook test failed:', result.error)
     * }
     * ```
     */
    test(webhookId: string): Promise<TestWebhookResponse>;
    /**
     * List webhook delivery history
     *
     * @param webhookId - Webhook ID
     * @param limit - Maximum number of deliveries to return (default: 50)
     * @returns List of webhook deliveries
     *
     * @example
     * ```typescript
     * const { deliveries } = await client.management.webhooks.listDeliveries('webhook-uuid', 100)
     *
     * deliveries.forEach(delivery => {
     *   console.log(`Event: ${delivery.event}, Status: ${delivery.status_code}`)
     * })
     * ```
     */
    listDeliveries(webhookId: string, limit?: number): Promise<ListWebhookDeliveriesResponse>;
}
/**
 * Invitations management client
 *
 * Provides methods for creating and managing user invitations.
 * Invitations allow admins to invite new users to join the platform.
 *
 * @example
 * ```typescript
 * const client = createClient({ url: 'http://localhost:8080' })
 * await client.admin.login({ email: 'admin@example.com', password: 'password' })
 *
 * // Create an invitation
 * const invitation = await client.management.invitations.create({
 *   email: 'newuser@example.com',
 *   role: 'dashboard_user'
 * })
 *
 * console.log('Invite link:', invitation.invite_link)
 * ```
 *
 * @category Management
 */
declare class InvitationsManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Create a new invitation (admin only)
     *
     * @param request - Invitation details
     * @returns Created invitation with invite link
     *
     * @example
     * ```typescript
     * const invitation = await client.management.invitations.create({
     *   email: 'newuser@example.com',
     *   role: 'dashboard_user',
     *   expiry_duration: 604800 // 7 days in seconds
     * })
     *
     * // Share the invite link
     * console.log('Send this link to the user:', invitation.invite_link)
     * ```
     */
    create(request: CreateInvitationRequest): Promise<CreateInvitationResponse>;
    /**
     * List all invitations (admin only)
     *
     * @param options - Filter options
     * @returns List of invitations
     *
     * @example
     * ```typescript
     * // List pending invitations only
     * const { invitations } = await client.management.invitations.list({
     *   include_accepted: false,
     *   include_expired: false
     * })
     *
     * // List all invitations including accepted and expired
     * const all = await client.management.invitations.list({
     *   include_accepted: true,
     *   include_expired: true
     * })
     * ```
     */
    list(options?: ListInvitationsOptions): Promise<ListInvitationsResponse>;
    /**
     * Validate an invitation token (public endpoint)
     *
     * @param token - Invitation token
     * @returns Validation result with invitation details
     *
     * @example
     * ```typescript
     * const result = await client.management.invitations.validate('invitation-token')
     *
     * if (result.valid) {
     *   console.log('Valid invitation for:', result.invitation?.email)
     * } else {
     *   console.error('Invalid:', result.error)
     * }
     * ```
     */
    validate(token: string): Promise<ValidateInvitationResponse>;
    /**
     * Accept an invitation and create a new user (public endpoint)
     *
     * @param token - Invitation token
     * @param request - User details (password and name)
     * @returns Created user with authentication tokens
     *
     * @example
     * ```typescript
     * const response = await client.management.invitations.accept('invitation-token', {
     *   password: 'SecurePassword123!',
     *   name: 'John Doe'
     * })
     *
     * // Store tokens
     * localStorage.setItem('access_token', response.access_token)
     * console.log('Welcome:', response.user.name)
     * ```
     */
    accept(token: string, request: AcceptInvitationRequest): Promise<AcceptInvitationResponse>;
    /**
     * Revoke an invitation (admin only)
     *
     * @param token - Invitation token
     * @returns Revocation confirmation
     *
     * @example
     * ```typescript
     * await client.management.invitations.revoke('invitation-token')
     * console.log('Invitation revoked')
     * ```
     */
    revoke(token: string): Promise<RevokeInvitationResponse>;
}
/**
 * Management client for client keys, webhooks, and invitations
 *
 * @category Management
 */
declare class FluxbaseManagement {
    /** Client Keys management */
    clientKeys: ClientKeysManager;
    /** @deprecated Use clientKeys instead */
    apiKeys: ClientKeysManager;
    /** Webhooks management */
    webhooks: WebhooksManager;
    /** Invitations management */
    invitations: InvitationsManager;
    constructor(fetch: FluxbaseFetch);
}

/**
 * esbuild plugin that marks Deno-specific imports as external
 * Use this when bundling functions/jobs with esbuild to handle npm:, https://, and jsr: imports
 *
 * @example
 * ```typescript
 * import { denoExternalPlugin } from '@nimbleflux/fluxbase-sdk'
 * import * as esbuild from 'esbuild'
 *
 * const result = await esbuild.build({
 *   entryPoints: ['./my-function.ts'],
 *   bundle: true,
 *   plugins: [denoExternalPlugin],
 *   // ... other options
 * })
 * ```
 */
declare const denoExternalPlugin: {
    name: string;
    setup(build: {
        onResolve: (opts: {
            filter: RegExp;
        }, cb: (args: {
            path: string;
        }) => {
            path: string;
            external: boolean;
        }) => void;
    }): void;
};
/**
 * Load import map from a deno.json file
 *
 * @param denoJsonPath - Path to deno.json file
 * @returns Import map object or null if not found
 *
 * @example
 * ```typescript
 * const importMap = await loadImportMap('./deno.json')
 * const bundled = await bundleCode({
 *   code: myCode,
 *   importMap,
 * })
 * ```
 */
declare function loadImportMap(denoJsonPath: string): Promise<Record<string, string> | null>;
/**
 * Options for bundling code
 */
interface BundleOptions {
    /** Entry point code */
    code: string;
    /** External modules to exclude from bundle */
    external?: string[];
    /** Source map generation */
    sourcemap?: boolean;
    /** Minify output */
    minify?: boolean;
    /** Import map from deno.json (maps aliases to npm: or file paths) */
    importMap?: Record<string, string>;
    /** Base directory for resolving relative imports (resolveDir in esbuild) */
    baseDir?: string;
    /** Additional paths to search for node_modules (useful when importing from parent directories) */
    nodePaths?: string[];
    /** Custom define values for esbuild (e.g., { 'process.env.NODE_ENV': '"production"' }) */
    define?: Record<string, string>;
}
/**
 * Result of bundling code
 */
interface BundleResult {
    /** Bundled code */
    code: string;
    /** Source map (if enabled) */
    sourceMap?: string;
}
/**
 * Bundle code using esbuild (client-side)
 *
 * Transforms and bundles TypeScript/JavaScript code into a single file
 * that can be executed by the Fluxbase Deno runtime.
 *
 * Requires esbuild as a peer dependency.
 *
 * @param options - Bundle options including source code
 * @returns Promise resolving to bundled code
 * @throws Error if esbuild is not available
 *
 * @example
 * ```typescript
 * import { bundleCode } from '@nimbleflux/fluxbase-sdk'
 *
 * const bundled = await bundleCode({
 *   code: `
 *     import { helper } from './utils'
 *     export default async function handler(req) {
 *       return helper(req.payload)
 *     }
 *   `,
 *   minify: true,
 * })
 *
 * // Use bundled code in sync
 * await client.admin.functions.sync({
 *   namespace: 'default',
 *   functions: [{
 *     name: 'my-function',
 *     code: bundled.code,
 *     is_pre_bundled: true,
 *   }]
 * })
 * ```
 */
declare function bundleCode(options: BundleOptions): Promise<BundleResult>;

/**
 * Admin Functions module for managing edge functions
 * Provides administrative operations for function lifecycle management
 */

/**
 * Admin Functions manager for managing edge functions
 * Provides create, update, delete, and bulk sync operations
 *
 * @category Admin
 */
declare class FluxbaseAdminFunctions {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Create a new edge function
     *
     * @param request - Function configuration and code
     * @returns Promise resolving to { data, error } tuple with created function metadata
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.functions.create({
     *   name: 'my-function',
     *   code: 'export default async function handler(req) { return { hello: "world" } }',
     *   enabled: true
     * })
     * ```
     */
    create(request: CreateFunctionRequest): Promise<{
        data: EdgeFunction | null;
        error: Error | null;
    }>;
    /**
     * List all namespaces that have edge functions
     *
     * @returns Promise resolving to { data, error } tuple with array of namespace strings
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.functions.listNamespaces()
     * if (data) {
     *   console.log('Available namespaces:', data)
     * }
     * ```
     */
    listNamespaces(): Promise<{
        data: string[] | null;
        error: Error | null;
    }>;
    /**
     * List all edge functions (admin view)
     *
     * @param namespace - Optional namespace filter (if not provided, lists all public functions)
     * @returns Promise resolving to { data, error } tuple with array of functions
     *
     * @example
     * ```typescript
     * // List all public functions
     * const { data, error } = await client.admin.functions.list()
     *
     * // List functions in a specific namespace
     * const { data, error } = await client.admin.functions.list('my-namespace')
     * if (data) {
     *   console.log('Functions:', data.map(f => f.name))
     * }
     * ```
     */
    list(namespace?: string): Promise<{
        data: EdgeFunction[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific edge function
     *
     * @param name - Function name
     * @returns Promise resolving to { data, error } tuple with function metadata
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.functions.get('my-function')
     * if (data) {
     *   console.log('Function version:', data.version)
     * }
     * ```
     */
    get(name: string): Promise<{
        data: EdgeFunction | null;
        error: Error | null;
    }>;
    /**
     * Update an existing edge function
     *
     * @param name - Function name
     * @param updates - Fields to update
     * @returns Promise resolving to { data, error } tuple with updated function metadata
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.functions.update('my-function', {
     *   enabled: false,
     *   description: 'Updated description'
     * })
     * ```
     */
    update(name: string, updates: UpdateFunctionRequest): Promise<{
        data: EdgeFunction | null;
        error: Error | null;
    }>;
    /**
     * Delete an edge function
     *
     * @param name - Function name
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.functions.delete('my-function')
     * ```
     */
    delete(name: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Get execution history for an edge function
     *
     * @param name - Function name
     * @param limit - Maximum number of executions to return (optional)
     * @returns Promise resolving to { data, error } tuple with execution records
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.functions.getExecutions('my-function', 10)
     * if (data) {
     *   data.forEach(exec => {
     *     console.log(`${exec.executed_at}: ${exec.status} (${exec.duration_ms}ms)`)
     *   })
     * }
     * ```
     */
    getExecutions(name: string, limit?: number): Promise<{
        data: EdgeFunctionExecution[] | null;
        error: Error | null;
    }>;
    /**
     * Sync multiple functions to a namespace
     *
     * Bulk create/update/delete functions in a specific namespace. This is useful for
     * deploying functions from your application to Fluxbase in Kubernetes or other
     * container environments.
     *
     * Requires service_role or admin authentication.
     *
     * @param options - Sync configuration including namespace, functions, and options
     * @returns Promise resolving to { data, error } tuple with sync results
     *
     * @example
     * ```typescript
     * // Sync functions to "payment-service" namespace
     * const { data, error } = await client.admin.functions.sync({
     *   namespace: 'payment-service',
     *   functions: [
     *     {
     *       name: 'process-payment',
     *       code: 'export default async function handler(req) { ... }',
     *       enabled: true,
     *       allow_net: true
     *     },
     *     {
     *       name: 'refund-payment',
     *       code: 'export default async function handler(req) { ... }',
     *       enabled: true
     *     }
     *   ],
     *   options: {
     *     delete_missing: true  // Remove functions not in this list
     *   }
     * })
     *
     * if (data) {
     *   console.log(`Synced: ${data.summary.created} created, ${data.summary.updated} updated`)
     * }
     *
     * // Dry run to preview changes
     * const { data, error } = await client.admin.functions.sync({
     *   namespace: 'myapp',
     *   functions: [...],
     *   options: { dry_run: true }
     * })
     * ```
     */
    sync(options: SyncFunctionsOptions): Promise<{
        data: SyncFunctionsResult | null;
        error: Error | null;
    }>;
    /**
     * Sync edge functions with automatic client-side bundling
     *
     * This is a convenience method that bundles all function code using esbuild
     * before sending to the server. Requires esbuild as a peer dependency.
     *
     * @param options - Sync options including namespace and functions array
     * @param bundleOptions - Optional bundling configuration
     * @returns Promise resolving to { data, error } tuple with sync results
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.functions.syncWithBundling({
     *   namespace: 'default',
     *   functions: [
     *     { name: 'hello', code: helloCode },
     *     { name: 'goodbye', code: goodbyeCode },
     *   ],
     *   options: { delete_missing: true }
     * })
     * ```
     */
    syncWithBundling(options: SyncFunctionsOptions, bundleOptions?: Partial<BundleOptions>): Promise<{
        data: SyncFunctionsResult | null;
        error: Error | null;
    }>;
    /**
     * Bundle function code using esbuild (client-side)
     *
     * Transforms and bundles TypeScript/JavaScript code into a single file
     * that can be executed by the Fluxbase edge functions runtime.
     *
     * Requires esbuild as a peer dependency.
     *
     * @param options - Bundle options including source code
     * @returns Promise resolving to bundled code
     * @throws Error if esbuild is not available
     *
     * @example
     * ```typescript
     * const bundled = await FluxbaseAdminFunctions.bundleCode({
     *   code: `
     *     import { helper } from './utils'
     *     export default async function handler(req) {
     *       return helper(req.body)
     *     }
     *   `,
     *   minify: true,
     * })
     *
     * // Use bundled code in sync
     * await client.admin.functions.sync({
     *   namespace: 'default',
     *   functions: [{
     *     name: 'my-function',
     *     code: bundled.code,
     *     is_pre_bundled: true,
     *   }]
     * })
     * ```
     */
    static bundleCode(options: BundleOptions): Promise<BundleResult>;
}

/**
 * Admin Migrations module for managing database migrations
 * Provides API-based migration management without filesystem coupling
 */

/**
 * Admin Migrations manager for database migration operations
 * Provides create, update, delete, apply, rollback, and smart sync operations
 *
 * @category Admin
 */
declare class FluxbaseAdminMigrations {
    private fetch;
    private localMigrations;
    constructor(fetch: FluxbaseFetch);
    /**
     * Register a migration locally for smart sync
     *
     * Call this method to register migrations in your application code.
     * When you call sync(), only new or changed migrations will be sent to the server.
     *
     * @param migration - Migration definition
     * @returns { error } tuple (always succeeds unless validation fails)
     *
     * @example
     * ```typescript
     * // In your app initialization
     * const { error: err1 } = client.admin.migrations.register({
     *   name: '001_create_users_table',
     *   namespace: 'myapp',
     *   up_sql: 'CREATE TABLE app.users (...)',
     *   down_sql: 'DROP TABLE app.users',
     *   description: 'Initial users table'
     * })
     *
     * const { error: err2 } = client.admin.migrations.register({
     *   name: '002_add_posts_table',
     *   namespace: 'myapp',
     *   up_sql: 'CREATE TABLE app.posts (...)',
     *   down_sql: 'DROP TABLE app.posts'
     * })
     *
     * // Sync all registered migrations
     * await client.admin.migrations.sync()
     * ```
     */
    register(migration: CreateMigrationRequest): {
        error: Error | null;
    };
    /**
     * Trigger schema refresh to update the REST API cache
     * Note: Server no longer restarts - cache is invalidated instantly
     *
     * @private
     */
    private triggerSchemaRefresh;
    /**
     * Smart sync all registered migrations
     *
     * Automatically determines which migrations need to be created or updated by:
     * 1. Fetching existing migrations from the server
     * 2. Comparing content hashes to detect changes
     * 3. Only sending new or changed migrations
     *
     * After successful sync, can optionally auto-apply new migrations and refresh
     * the server's schema cache.
     *
     * @param options - Sync options
     * @returns Promise resolving to { data, error } tuple with sync results
     *
     * @example
     * ```typescript
     * // Basic sync (idempotent - safe to call on every app startup)
     * const { data, error } = await client.admin.migrations.sync()
     * if (data) {
     *   console.log(`Created: ${data.summary.created}, Updated: ${data.summary.updated}`)
     * }
     *
     * // Sync with auto-apply (applies new migrations automatically)
     * const { data, error } = await client.admin.migrations.sync({
     *   auto_apply: true
     * })
     *
     * // Dry run to preview changes without applying
     * const { data, error } = await client.admin.migrations.sync({
     *   dry_run: true
     * })
     * ```
     */
    sync(options?: Partial<SyncMigrationsOptions>): Promise<{
        data: SyncMigrationsResult | null;
        error: Error | null;
    }>;
    /**
     * Create a new migration
     *
     * @param request - Migration configuration
     * @returns Promise resolving to { data, error } tuple with created migration
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.create({
     *   namespace: 'myapp',
     *   name: '001_create_users',
     *   up_sql: 'CREATE TABLE app.users (id UUID PRIMARY KEY, email TEXT)',
     *   down_sql: 'DROP TABLE app.users',
     *   description: 'Create users table'
     * })
     * ```
     */
    create(request: CreateMigrationRequest): Promise<{
        data: Migration | null;
        error: Error | null;
    }>;
    /**
     * List migrations in a namespace
     *
     * @param namespace - Migration namespace (default: 'default')
     * @param status - Filter by status: 'pending', 'applied', 'failed', 'rolled_back'
     * @returns Promise resolving to { data, error } tuple with migrations array
     *
     * @example
     * ```typescript
     * // List all migrations
     * const { data, error } = await client.admin.migrations.list('myapp')
     *
     * // List only pending migrations
     * const { data, error } = await client.admin.migrations.list('myapp', 'pending')
     * ```
     */
    list(namespace?: string, status?: "pending" | "applied" | "failed" | "rolled_back"): Promise<{
        data: Migration[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific migration
     *
     * @param name - Migration name
     * @param namespace - Migration namespace (default: 'default')
     * @returns Promise resolving to { data, error } tuple with migration details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.get('001_create_users', 'myapp')
     * ```
     */
    get(name: string, namespace?: string): Promise<{
        data: Migration | null;
        error: Error | null;
    }>;
    /**
     * Update a migration (only if status is pending)
     *
     * @param name - Migration name
     * @param updates - Fields to update
     * @param namespace - Migration namespace (default: 'default')
     * @returns Promise resolving to { data, error } tuple with updated migration
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.update(
     *   '001_create_users',
     *   { description: 'Updated description' },
     *   'myapp'
     * )
     * ```
     */
    update(name: string, updates: UpdateMigrationRequest, namespace?: string): Promise<{
        data: Migration | null;
        error: Error | null;
    }>;
    /**
     * Delete a migration (only if status is pending)
     *
     * @param name - Migration name
     * @param namespace - Migration namespace (default: 'default')
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.delete('001_create_users', 'myapp')
     * ```
     */
    delete(name: string, namespace?: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Apply a specific migration
     *
     * @param name - Migration name
     * @param namespace - Migration namespace (default: 'default')
     * @returns Promise resolving to { data, error } tuple with result message
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.apply('001_create_users', 'myapp')
     * if (data) {
     *   console.log(data.message) // "Migration applied successfully"
     * }
     * ```
     */
    apply(name: string, namespace?: string): Promise<{
        data: {
            message: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Rollback a specific migration
     *
     * @param name - Migration name
     * @param namespace - Migration namespace (default: 'default')
     * @returns Promise resolving to { data, error } tuple with result message
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.rollback('001_create_users', 'myapp')
     * ```
     */
    rollback(name: string, namespace?: string): Promise<{
        data: {
            message: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Apply all pending migrations in order
     *
     * @param namespace - Migration namespace (default: 'default')
     * @returns Promise resolving to { data, error } tuple with applied/failed counts
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.applyPending('myapp')
     * if (data) {
     *   console.log(`Applied: ${data.applied.length}, Failed: ${data.failed.length}`)
     * }
     * ```
     */
    applyPending(namespace?: string): Promise<{
        data: {
            message: string;
            applied: string[];
            failed: string[];
        } | null;
        error: Error | null;
    }>;
    /**
     * Get execution history for a migration
     *
     * @param name - Migration name
     * @param namespace - Migration namespace (default: 'default')
     * @param limit - Maximum number of executions to return (default: 50, max: 100)
     * @returns Promise resolving to { data, error } tuple with execution records
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.migrations.getExecutions(
     *   '001_create_users',
     *   'myapp',
     *   10
     * )
     * if (data) {
     *   data.forEach(exec => {
     *     console.log(`${exec.executed_at}: ${exec.action} - ${exec.status}`)
     *   })
     * }
     * ```
     */
    getExecutions(name: string, namespace?: string, limit?: number): Promise<{
        data: MigrationExecution[] | null;
        error: Error | null;
    }>;
}

/**
 * Admin Jobs module for managing job functions and executions
 * Provides administrative operations for job lifecycle management
 */

/**
 * Admin Jobs manager for managing background job functions
 * Provides create, update, delete, sync, and monitoring operations
 *
 * @category Admin
 */
declare class FluxbaseAdminJobs {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Create a new job function
     *
     * @param params - Job function configuration
     * @returns Promise resolving to { data, error } tuple with created job function
     */
    create(params: {
        name: string;
        code: string;
        enabled?: boolean;
        timeout_seconds?: number;
        namespace?: string;
    }): Promise<{
        data: JobFunction | null;
        error: Error | null;
    }>;
    /**
     * List all namespaces that have job functions
     *
     * @returns Promise resolving to { data, error } tuple with array of namespace strings
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.listNamespaces()
     * if (data) {
     *   console.log('Available namespaces:', data)
     * }
     * ```
     */
    listNamespaces(): Promise<{
        data: string[] | null;
        error: Error | null;
    }>;
    /**
     * List all job functions (admin view)
     *
     * @param namespace - Optional namespace filter
     * @returns Promise resolving to { data, error } tuple with array of job functions
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.list('default')
     * if (data) {
     *   console.log('Job functions:', data.map(f => f.name))
     * }
     * ```
     */
    list(namespace?: string): Promise<{
        data: JobFunction[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific job function
     *
     * @param namespace - Namespace
     * @param name - Job function name
     * @returns Promise resolving to { data, error } tuple with job function metadata
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.get('default', 'process-data')
     * if (data) {
     *   console.log('Job function version:', data.version)
     * }
     * ```
     */
    get(namespace: string, name: string): Promise<{
        data: JobFunction | null;
        error: Error | null;
    }>;
    /**
     * Delete a job function
     *
     * @param namespace - Namespace
     * @param name - Job function name
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.delete('default', 'process-data')
     * ```
     */
    delete(namespace: string, name: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Update an existing job function
     *
     * @param namespace - Namespace
     * @param name - Job function name
     * @param updates - Fields to update
     * @returns Promise resolving to { data, error } tuple with updated job function
     */
    update(namespace: string, name: string, updates: {
        enabled?: boolean;
        timeout_seconds?: number;
        code?: string;
    }): Promise<{
        data: JobFunction | null;
        error: Error | null;
    }>;
    /**
     * List all jobs (executions) across all namespaces (admin view)
     *
     * @param filters - Optional filters (status, namespace, limit, offset)
     * @returns Promise resolving to { data, error } tuple with array of jobs
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.listJobs({
     *   status: 'running',
     *   namespace: 'default',
     *   limit: 50
     * })
     * if (data) {
     *   data.forEach(job => {
     *     console.log(`${job.job_name}: ${job.status}`)
     *   })
     * }
     * ```
     */
    listJobs(filters?: {
        status?: string;
        namespace?: string;
        limit?: number;
        offset?: number;
        includeResult?: boolean;
    }): Promise<{
        data: Job[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific job (execution)
     *
     * @param jobId - Job ID
     * @returns Promise resolving to { data, error } tuple with job details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.getJob('550e8400-e29b-41d4-a716-446655440000')
     * if (data) {
     *   console.log(`Job ${data.job_name}: ${data.status}`)
     * }
     * ```
     */
    getJob(jobId: string): Promise<{
        data: Job | null;
        error: Error | null;
    }>;
    /**
     * Cancel a running or pending job
     *
     * @param jobId - Job ID
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.cancel('550e8400-e29b-41d4-a716-446655440000')
     * ```
     */
    cancel(jobId: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Terminate a running job immediately
     *
     * @param jobId - Job ID
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.terminate('550e8400-e29b-41d4-a716-446655440000')
     * ```
     */
    terminate(jobId: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Retry a failed job
     *
     * @param jobId - Job ID
     * @returns Promise resolving to { data, error } tuple with new job
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.retry('550e8400-e29b-41d4-a716-446655440000')
     * ```
     */
    retry(jobId: string): Promise<{
        data: Job | null;
        error: Error | null;
    }>;
    /**
     * Get job statistics
     *
     * @param namespace - Optional namespace filter
     * @returns Promise resolving to { data, error } tuple with job stats
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.getStats('default')
     * if (data) {
     *   console.log(`Pending: ${data.pending}, Running: ${data.running}`)
     * }
     * ```
     */
    getStats(namespace?: string): Promise<{
        data: JobStats | null;
        error: Error | null;
    }>;
    /**
     * List active workers
     *
     * @returns Promise resolving to { data, error } tuple with array of workers
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.listWorkers()
     * if (data) {
     *   data.forEach(worker => {
     *     console.log(`Worker ${worker.id}: ${worker.current_jobs} jobs`)
     *   })
     * }
     * ```
     */
    listWorkers(): Promise<{
        data: JobWorker[] | null;
        error: Error | null;
    }>;
    /**
     * Sync multiple job functions to a namespace
     *
     * Can sync from:
     * 1. Filesystem (if no jobs provided) - loads from configured jobs directory
     * 2. API payload (if jobs array provided) - syncs provided job specifications
     *
     * Requires service_role or admin authentication.
     *
     * @param options - Sync options including namespace and optional jobs array
     * @returns Promise resolving to { data, error } tuple with sync results
     *
     * @example
     * ```typescript
     * // Sync from filesystem
     * const { data, error } = await client.admin.jobs.sync({ namespace: 'default' })
     *
     * // Sync with pre-bundled code (client-side bundling)
     * const bundled = await FluxbaseAdminJobs.bundleCode({ code: myJobCode })
     * const { data, error } = await client.admin.jobs.sync({
     *   namespace: 'default',
     *   functions: [{
     *     name: 'my-job',
     *     code: bundled.code,
     *     is_pre_bundled: true,
     *     original_code: myJobCode,
     *   }],
     *   options: {
     *     delete_missing: true, // Remove jobs not in this sync
     *     dry_run: false,       // Preview changes without applying
     *   }
     * })
     *
     * if (data) {
     *   console.log(`Synced: ${data.summary.created} created, ${data.summary.updated} updated`)
     * }
     * ```
     */
    sync(options: SyncJobsOptions | string): Promise<{
        data: SyncJobsResult | null;
        error: Error | null;
    }>;
    /**
     * Sync job functions with automatic client-side bundling
     *
     * This is a convenience method that bundles all job code using esbuild
     * before sending to the server. Requires esbuild as a peer dependency.
     *
     * @param options - Sync options including namespace and jobs array
     * @param bundleOptions - Optional bundling configuration
     * @returns Promise resolving to { data, error } tuple with sync results
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.jobs.syncWithBundling({
     *   namespace: 'default',
     *   functions: [
     *     { name: 'process-data', code: processDataCode },
     *     { name: 'send-email', code: sendEmailCode },
     *   ],
     *   options: { delete_missing: true }
     * })
     * ```
     */
    syncWithBundling(options: SyncJobsOptions, bundleOptions?: Partial<BundleOptions>): Promise<{
        data: SyncJobsResult | null;
        error: Error | null;
    }>;
    /**
     * Bundle job code using esbuild (client-side)
     *
     * Transforms and bundles TypeScript/JavaScript code into a single file
     * that can be executed by the Fluxbase jobs runtime.
     *
     * Requires esbuild as a peer dependency.
     *
     * @param options - Bundle options including source code
     * @returns Promise resolving to bundled code
     * @throws Error if esbuild is not available
     *
     * @example
     * ```typescript
     * const bundled = await FluxbaseAdminJobs.bundleCode({
     *   code: `
     *     import { helper } from './utils'
     *     export async function handler(req) {
     *       return helper(req.payload)
     *     }
     *   `,
     *   minify: true,
     * })
     *
     * // Use bundled code in sync
     * await client.admin.jobs.sync({
     *   namespace: 'default',
     *   functions: [{
     *     name: 'my-job',
     *     code: bundled.code,
     *     is_pre_bundled: true,
     *   }]
     * })
     * ```
     */
    static bundleCode(options: BundleOptions): Promise<BundleResult>;
}

/**
 * Admin AI module for managing AI chatbots and providers
 * Provides administrative operations for chatbot lifecycle management
 */

/**
 * Admin AI manager for managing AI chatbots and providers
 * Provides create, update, delete, sync, and monitoring operations
 *
 * @category Admin
 */
declare class FluxbaseAdminAI {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all chatbots (admin view)
     *
     * @param namespace - Optional namespace filter
     * @returns Promise resolving to { data, error } tuple with array of chatbot summaries
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.listChatbots()
     * if (data) {
     *   console.log('Chatbots:', data.map(c => c.name))
     * }
     * ```
     */
    listChatbots(namespace?: string): Promise<{
        data: AIChatbotSummary[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific chatbot
     *
     * @param id - Chatbot ID
     * @returns Promise resolving to { data, error } tuple with chatbot details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.getChatbot('uuid')
     * if (data) {
     *   console.log('Chatbot:', data.name)
     * }
     * ```
     */
    getChatbot(id: string): Promise<{
        data: AIChatbot | null;
        error: Error | null;
    }>;
    /**
     * Enable or disable a chatbot
     *
     * @param id - Chatbot ID
     * @param enabled - Whether to enable or disable
     * @returns Promise resolving to { data, error } tuple with updated chatbot
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.toggleChatbot('uuid', true)
     * ```
     */
    toggleChatbot(id: string, enabled: boolean): Promise<{
        data: AIChatbot | null;
        error: Error | null;
    }>;
    /**
     * Delete a chatbot
     *
     * @param id - Chatbot ID
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.deleteChatbot('uuid')
     * ```
     */
    deleteChatbot(id: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Sync chatbots from filesystem or API payload
     *
     * Can sync from:
     * 1. Filesystem (if no chatbots provided) - loads from configured chatbots directory
     * 2. API payload (if chatbots array provided) - syncs provided chatbot specifications
     *
     * Requires service_role or admin authentication.
     *
     * @param options - Sync options including namespace and optional chatbots array
     * @returns Promise resolving to { data, error } tuple with sync results
     *
     * @example
     * ```typescript
     * // Sync from filesystem
     * const { data, error } = await client.admin.ai.sync()
     *
     * // Sync with provided chatbot code
     * const { data, error } = await client.admin.ai.sync({
     *   namespace: 'default',
     *   chatbots: [{
     *     name: 'sql-assistant',
     *     code: myChatbotCode,
     *   }],
     *   options: {
     *     delete_missing: false, // Don't remove chatbots not in this sync
     *     dry_run: false,        // Preview changes without applying
     *   }
     * })
     *
     * if (data) {
     *   console.log(`Synced: ${data.summary.created} created, ${data.summary.updated} updated`)
     * }
     * ```
     */
    sync(options?: SyncChatbotsOptions): Promise<{
        data: SyncChatbotsResult | null;
        error: Error | null;
    }>;
    /**
     * List all AI providers
     *
     * @returns Promise resolving to { data, error } tuple with array of providers
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.listProviders()
     * if (data) {
     *   console.log('Providers:', data.map(p => p.name))
     * }
     * ```
     */
    listProviders(): Promise<{
        data: AIProvider[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific AI provider
     *
     * @param id - Provider ID
     * @returns Promise resolving to { data, error } tuple with provider details
     */
    getProvider(id: string): Promise<{
        data: AIProvider | null;
        error: Error | null;
    }>;
    /**
     * Create a new AI provider
     *
     * @param params - Provider configuration including name, provider_type, and optional config
     * @returns Promise resolving to { data, error } tuple with created provider
     */
    createProvider(params: {
        name: string;
        display_name?: string;
        provider_type: string;
        is_default?: boolean;
        config?: Record<string, unknown>;
    }): Promise<{
        data: AIProvider | null;
        error: Error | null;
    }>;
    /**
     * Update an existing AI provider
     *
     * @param id - Provider ID
     * @param updates - Fields to update
     * @returns Promise resolving to { data, error } tuple with updated provider
     */
    updateProvider(id: string, updates: {
        display_name?: string;
        enabled?: boolean;
        config?: Record<string, unknown>;
        embedding_model?: string | null;
    }): Promise<{
        data: AIProvider | null;
        error: Error | null;
    }>;
    /**
     * Set a provider as the default provider
     *
     * @param id - Provider ID
     * @returns Promise resolving to { data, error } tuple with updated provider
     */
    setDefaultProvider(id: string): Promise<{
        data: AIProvider | null;
        error: Error | null;
    }>;
    /**
     * Delete an AI provider
     *
     * @param id - Provider ID
     * @returns Promise resolving to { data, error } tuple
     */
    deleteProvider(id: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Set a provider as the embedding provider
     *
     * @param id - Provider ID
     * @returns Promise resolving to { data, error } tuple with updated provider
     */
    setEmbeddingProvider(id: string): Promise<{
        data: {
            use_for_embeddings: boolean;
        } | null;
        error: Error | null;
    }>;
    /**
     * Clear the embedding provider assignment for a provider
     *
     * @param id - Provider ID
     * @returns Promise resolving to { data, error } tuple
     */
    clearEmbeddingProvider(id: string): Promise<{
        data: {
            use_for_embeddings: boolean;
        } | null;
        error: Error | null;
    }>;
    /**
     * List knowledge bases linked to a chatbot
     *
     * @param chatbotId - Chatbot ID
     * @returns Promise resolving to { data, error } tuple with linked knowledge bases
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.listChatbotKnowledgeBases('chatbot-uuid')
     * if (data) {
     *   console.log('Linked KBs:', data.map(l => l.knowledge_base_id))
     * }
     * ```
     */
    listChatbotKnowledgeBases(chatbotId: string): Promise<{
        data: ChatbotKnowledgeBaseLink[] | null;
        error: Error | null;
    }>;
    /**
     * Link a knowledge base to a chatbot
     *
     * @param chatbotId - Chatbot ID
     * @param request - Link configuration
     * @returns Promise resolving to { data, error } tuple with link details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.linkKnowledgeBase('chatbot-uuid', {
     *   knowledge_base_id: 'kb-uuid',
     *   priority: 1,
     *   max_chunks: 5,
     *   similarity_threshold: 0.7,
     * })
     * ```
     */
    linkKnowledgeBase(chatbotId: string, request: LinkKnowledgeBaseRequest): Promise<{
        data: ChatbotKnowledgeBaseLink | null;
        error: Error | null;
    }>;
    /**
     * Update a chatbot-knowledge base link
     *
     * @param chatbotId - Chatbot ID
     * @param knowledgeBaseId - Knowledge base ID
     * @param updates - Fields to update
     * @returns Promise resolving to { data, error } tuple with updated link
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.updateChatbotKnowledgeBase(
     *   'chatbot-uuid',
     *   'kb-uuid',
     *   { max_chunks: 10, enabled: true }
     * )
     * ```
     */
    updateChatbotKnowledgeBase(chatbotId: string, knowledgeBaseId: string, updates: UpdateChatbotKnowledgeBaseRequest): Promise<{
        data: ChatbotKnowledgeBaseLink | null;
        error: Error | null;
    }>;
    /**
     * Unlink a knowledge base from a chatbot
     *
     * @param chatbotId - Chatbot ID
     * @param knowledgeBaseId - Knowledge base ID
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.unlinkKnowledgeBase('chatbot-uuid', 'kb-uuid')
     * ```
     */
    unlinkKnowledgeBase(chatbotId: string, knowledgeBaseId: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * Get detailed table information including columns
     *
     * Use this to discover available columns before exporting.
     *
     * @param schema - Schema name (e.g., 'public')
     * @param table - Table name
     * @returns Promise resolving to { data, error } tuple with table details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.ai.getTableDetails('public', 'users')
     * if (data) {
     *   console.log('Columns:', data.columns.map(c => c.name))
     *   console.log('Primary key:', data.primary_key)
     * }
     * ```
     */
    getTableDetails(schema: string, table: string): Promise<{
        data: TableDetails | null;
        error: Error | null;
    }>;
}

/**
 * Admin RPC module for managing RPC procedures
 * Provides administrative operations for RPC procedure lifecycle management
 */

/**
 * Admin RPC manager for managing RPC procedures
 * Provides sync, CRUD, and execution monitoring operations
 *
 * @category Admin
 */
declare class FluxbaseAdminRPC {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Sync RPC procedures from filesystem or API payload
     *
     * Can sync from:
     * 1. Filesystem (if no procedures provided) - loads from configured procedures directory
     * 2. API payload (if procedures array provided) - syncs provided procedure specifications
     *
     * Requires service_role or admin authentication.
     *
     * @param options - Sync options including namespace and optional procedures array
     * @returns Promise resolving to { data, error } tuple with sync results
     *
     * @example
     * ```typescript
     * // Sync from filesystem
     * const { data, error } = await client.admin.rpc.sync()
     *
     * // Sync with provided procedure code
     * const { data, error } = await client.admin.rpc.sync({
     *   namespace: 'default',
     *   procedures: [{
     *     name: 'get-user-orders',
     *     code: myProcedureSQL,
     *   }],
     *   options: {
     *     delete_missing: false, // Don't remove procedures not in this sync
     *     dry_run: false,        // Preview changes without applying
     *   }
     * })
     *
     * if (data) {
     *   console.log(`Synced: ${data.summary.created} created, ${data.summary.updated} updated`)
     * }
     * ```
     */
    sync(options?: SyncRPCOptions): Promise<{
        data: SyncRPCResult | null;
        error: Error | null;
    }>;
    /**
     * List all RPC procedures (admin view)
     *
     * @param namespace - Optional namespace filter
     * @returns Promise resolving to { data, error } tuple with array of procedure summaries
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.list()
     * if (data) {
     *   console.log('Procedures:', data.map(p => p.name))
     * }
     * ```
     */
    list(namespace?: string): Promise<{
        data: RPCProcedureSummary[] | null;
        error: Error | null;
    }>;
    /**
     * List all namespaces
     *
     * @returns Promise resolving to { data, error } tuple with array of namespace names
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.listNamespaces()
     * if (data) {
     *   console.log('Namespaces:', data)
     * }
     * ```
     */
    listNamespaces(): Promise<{
        data: string[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific RPC procedure
     *
     * @param namespace - Procedure namespace
     * @param name - Procedure name
     * @returns Promise resolving to { data, error } tuple with procedure details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.get('default', 'get-user-orders')
     * if (data) {
     *   console.log('Procedure:', data.name)
     *   console.log('SQL:', data.sql_query)
     * }
     * ```
     */
    get(namespace: string, name: string): Promise<{
        data: RPCProcedure | null;
        error: Error | null;
    }>;
    /**
     * Update an RPC procedure
     *
     * @param namespace - Procedure namespace
     * @param name - Procedure name
     * @param updates - Fields to update
     * @returns Promise resolving to { data, error } tuple with updated procedure
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.update('default', 'get-user-orders', {
     *   enabled: false,
     *   max_execution_time_seconds: 60,
     * })
     * ```
     */
    update(namespace: string, name: string, updates: UpdateRPCProcedureRequest): Promise<{
        data: RPCProcedure | null;
        error: Error | null;
    }>;
    /**
     * Enable or disable an RPC procedure
     *
     * @param namespace - Procedure namespace
     * @param name - Procedure name
     * @param enabled - Whether to enable or disable
     * @returns Promise resolving to { data, error } tuple with updated procedure
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.toggle('default', 'get-user-orders', true)
     * ```
     */
    toggle(namespace: string, name: string, enabled: boolean): Promise<{
        data: RPCProcedure | null;
        error: Error | null;
    }>;
    /**
     * Delete an RPC procedure
     *
     * @param namespace - Procedure namespace
     * @param name - Procedure name
     * @returns Promise resolving to { data, error } tuple
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.delete('default', 'get-user-orders')
     * ```
     */
    delete(namespace: string, name: string): Promise<{
        data: null;
        error: Error | null;
    }>;
    /**
     * List RPC executions with optional filters
     *
     * @param filters - Optional filters for namespace, procedure, status, user
     * @returns Promise resolving to { data, error } tuple with array of executions
     *
     * @example
     * ```typescript
     * // List all executions
     * const { data, error } = await client.admin.rpc.listExecutions()
     *
     * // List failed executions for a specific procedure
     * const { data, error } = await client.admin.rpc.listExecutions({
     *   namespace: 'default',
     *   procedure: 'get-user-orders',
     *   status: 'failed',
     * })
     * ```
     */
    listExecutions(filters?: RPCExecutionFilters): Promise<{
        data: RPCExecution[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific execution
     *
     * @param executionId - Execution ID
     * @returns Promise resolving to { data, error } tuple with execution details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.getExecution('execution-uuid')
     * if (data) {
     *   console.log('Status:', data.status)
     *   console.log('Duration:', data.duration_ms, 'ms')
     * }
     * ```
     */
    getExecution(executionId: string): Promise<{
        data: RPCExecution | null;
        error: Error | null;
    }>;
    /**
     * Get execution logs for a specific execution
     *
     * @param executionId - Execution ID
     * @param afterLine - Optional line number to get logs after (for polling)
     * @returns Promise resolving to { data, error } tuple with execution logs
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.getExecutionLogs('execution-uuid')
     * if (data) {
     *   for (const log of data) {
     *     console.log(`[${log.level}] ${log.message}`)
     *   }
     * }
     * ```
     */
    getExecutionLogs(executionId: string, afterLine?: number): Promise<{
        data: RPCExecutionLog[] | null;
        error: Error | null;
    }>;
    /**
     * Cancel a running execution
     *
     * @param executionId - Execution ID
     * @returns Promise resolving to { data, error } tuple with updated execution
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.rpc.cancelExecution('execution-uuid')
     * ```
     */
    cancelExecution(executionId: string): Promise<{
        data: RPCExecution | null;
        error: Error | null;
    }>;
}

/**
 * Admin storage manager for bucket and object management
 */
declare class FluxbaseAdminStorage {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all storage buckets
     *
     * @returns List of buckets
     *
     * @example
     * ```typescript
     * const { data, error } = await admin.storage.listBuckets();
     * if (data) {
     *   console.log(`Found ${data.buckets.length} buckets`);
     * }
     * ```
     */
    listBuckets(): Promise<DataResponse<AdminListBucketsResponse>>;
    /**
     * Create a new storage bucket
     *
     * @param name - Bucket name
     * @returns Success message
     *
     * @example
     * ```typescript
     * const { error } = await admin.storage.createBucket('my-bucket');
     * if (!error) {
     *   console.log('Bucket created');
     * }
     * ```
     */
    createBucket(name: string): Promise<DataResponse<{
        message: string;
    }>>;
    /**
     * Delete a storage bucket
     *
     * @param name - Bucket name
     * @returns Success message
     *
     * @example
     * ```typescript
     * const { error } = await admin.storage.deleteBucket('my-bucket');
     * if (!error) {
     *   console.log('Bucket deleted');
     * }
     * ```
     */
    deleteBucket(name: string): Promise<DataResponse<{
        message: string;
    }>>;
    /**
     * List objects in a bucket
     *
     * @param bucket - Bucket name
     * @param prefix - Optional path prefix to filter results
     * @param delimiter - Optional delimiter for hierarchical listing (usually '/')
     * @returns List of objects and prefixes (folders)
     *
     * @example
     * ```typescript
     * // List all objects in bucket
     * const { data } = await admin.storage.listObjects('my-bucket');
     *
     * // List objects in a folder
     * const { data } = await admin.storage.listObjects('my-bucket', 'folder/', '/');
     * ```
     */
    listObjects(bucket: string, prefix?: string, delimiter?: string): Promise<DataResponse<AdminListObjectsResponse>>;
    /**
     * Get object metadata
     *
     * @param bucket - Bucket name
     * @param key - Object key (path)
     * @returns Object metadata
     *
     * @example
     * ```typescript
     * const { data } = await admin.storage.getObjectMetadata('my-bucket', 'path/to/file.txt');
     * if (data) {
     *   console.log(`File size: ${data.size} bytes`);
     * }
     * ```
     */
    getObjectMetadata(bucket: string, key: string): Promise<DataResponse<AdminStorageObject>>;
    /**
     * Download an object as a Blob
     *
     * @param bucket - Bucket name
     * @param key - Object key (path)
     * @returns Object data as Blob
     *
     * @example
     * ```typescript
     * const { data: blob } = await admin.storage.downloadObject('my-bucket', 'file.pdf');
     * if (blob) {
     *   // Use the blob
     *   const url = URL.createObjectURL(blob);
     * }
     * ```
     */
    downloadObject(bucket: string, key: string): Promise<DataResponse<Blob>>;
    /**
     * Delete an object
     *
     * @param bucket - Bucket name
     * @param key - Object key (path)
     *
     * @example
     * ```typescript
     * const { error } = await admin.storage.deleteObject('my-bucket', 'path/to/file.txt');
     * if (!error) {
     *   console.log('Object deleted');
     * }
     * ```
     */
    deleteObject(bucket: string, key: string): Promise<VoidResponse>;
    /**
     * Create a folder (empty object with directory content type)
     *
     * @param bucket - Bucket name
     * @param folderPath - Folder path (should end with /)
     *
     * @example
     * ```typescript
     * const { error } = await admin.storage.createFolder('my-bucket', 'new-folder/');
     * ```
     */
    createFolder(bucket: string, folderPath: string): Promise<VoidResponse>;
    /**
     * Generate a signed URL for a private object
     *
     * @param bucket - Bucket name
     * @param key - Object key (path)
     * @param expiresIn - URL expiration time in seconds
     * @returns Signed URL and expiration info
     *
     * @example
     * ```typescript
     * const { data } = await admin.storage.generateSignedUrl('my-bucket', 'file.pdf', 3600);
     * if (data) {
     *   window.open(data.url);
     * }
     * ```
     */
    generateSignedUrl(bucket: string, key: string, expiresIn: number): Promise<DataResponse<{
        url: string;
        expires_in: number;
    }>>;
}

/**
 * Realtime Admin Manager
 *
 * Provides methods for enabling and managing realtime subscriptions on database tables.
 * When enabled, changes to a table (INSERT, UPDATE, DELETE) are automatically broadcast
 * to WebSocket subscribers.
 *
 * @example
 * ```typescript
 * const realtime = client.admin.realtime
 *
 * // Enable realtime on a table
 * await realtime.enableRealtime('products')
 *
 * // Enable with options
 * await realtime.enableRealtime('orders', {
 *   events: ['INSERT', 'UPDATE'],
 *   exclude: ['internal_notes', 'raw_data']
 * })
 *
 * // List all realtime-enabled tables
 * const { tables } = await realtime.listTables()
 *
 * // Check status of a specific table
 * const status = await realtime.getStatus('public', 'products')
 *
 * // Disable realtime
 * await realtime.disableRealtime('public', 'products')
 * ```
 */
declare class FluxbaseAdminRealtime {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Enable realtime on a table
     *
     * Creates the necessary database triggers to broadcast changes to WebSocket subscribers.
     * Also sets REPLICA IDENTITY FULL to include old values in UPDATE/DELETE events.
     *
     * @param table - Table name to enable realtime on
     * @param options - Optional configuration
     * @returns Promise resolving to EnableRealtimeResponse
     *
     * @example
     * ```typescript
     * // Enable realtime on products table (all events)
     * await client.admin.realtime.enableRealtime('products')
     *
     * // Enable on a specific schema
     * await client.admin.realtime.enableRealtime('orders', {
     *   schema: 'sales'
     * })
     *
     * // Enable specific events only
     * await client.admin.realtime.enableRealtime('audit_log', {
     *   events: ['INSERT'] // Only broadcast inserts
     * })
     *
     * // Exclude large columns from notifications
     * await client.admin.realtime.enableRealtime('posts', {
     *   exclude: ['content', 'raw_html'] // Skip these in payload
     * })
     * ```
     */
    enableRealtime(table: string, options?: {
        schema?: string;
        events?: ("INSERT" | "UPDATE" | "DELETE")[];
        exclude?: string[];
    }): Promise<EnableRealtimeResponse>;
    /**
     * Disable realtime on a table
     *
     * Removes the realtime trigger from a table. Existing subscribers will stop
     * receiving updates for this table.
     *
     * @param schema - Schema name
     * @param table - Table name
     * @returns Promise resolving to success message
     *
     * @example
     * ```typescript
     * await client.admin.realtime.disableRealtime('public', 'products')
     * console.log('Realtime disabled')
     * ```
     */
    disableRealtime(schema: string, table: string): Promise<{
        success: boolean;
        message: string;
    }>;
    /**
     * List all realtime-enabled tables
     *
     * Returns a list of all tables that have realtime enabled, along with their
     * configuration (events, excluded columns, etc.).
     *
     * @param options - Optional filter options
     * @returns Promise resolving to ListRealtimeTablesResponse
     *
     * @example
     * ```typescript
     * // List all enabled tables
     * const { tables, count } = await client.admin.realtime.listTables()
     * console.log(`${count} tables have realtime enabled`)
     *
     * tables.forEach(t => {
     *   console.log(`${t.schema}.${t.table}: ${t.events.join(', ')}`)
     * })
     *
     * // Include disabled tables
     * const all = await client.admin.realtime.listTables({ includeDisabled: true })
     * ```
     */
    listTables(options?: {
        includeDisabled?: boolean;
    }): Promise<ListRealtimeTablesResponse>;
    /**
     * Get realtime status for a specific table
     *
     * Returns the realtime configuration for a table, including whether it's enabled,
     * which events are tracked, and which columns are excluded.
     *
     * @param schema - Schema name
     * @param table - Table name
     * @returns Promise resolving to RealtimeTableStatus
     *
     * @example
     * ```typescript
     * const status = await client.admin.realtime.getStatus('public', 'products')
     *
     * if (status.realtime_enabled) {
     *   console.log('Events:', status.events.join(', '))
     *   console.log('Excluded:', status.excluded_columns?.join(', ') || 'none')
     * } else {
     *   console.log('Realtime not enabled')
     * }
     * ```
     */
    getStatus(schema: string, table: string): Promise<RealtimeTableStatus>;
    /**
     * Update realtime configuration for a table
     *
     * Modifies the events or excluded columns for a realtime-enabled table
     * without recreating the trigger.
     *
     * @param schema - Schema name
     * @param table - Table name
     * @param config - New configuration
     * @returns Promise resolving to success message
     *
     * @example
     * ```typescript
     * // Change which events are tracked
     * await client.admin.realtime.updateConfig('public', 'products', {
     *   events: ['INSERT', 'UPDATE'] // Stop tracking deletes
     * })
     *
     * // Update excluded columns
     * await client.admin.realtime.updateConfig('public', 'posts', {
     *   exclude: ['raw_content', 'search_vector']
     * })
     *
     * // Clear excluded columns
     * await client.admin.realtime.updateConfig('public', 'posts', {
     *   exclude: [] // Include all columns again
     * })
     * ```
     */
    updateConfig(schema: string, table: string, config: UpdateRealtimeConfigRequest): Promise<{
        success: boolean;
        message: string;
    }>;
}

/**
 * Service Keys Manager
 *
 * Manages service keys (anon and service) for tenant databases.
 * Each tenant has their own auth.service_keys table.
 *
 * @example
 * ```typescript
 * // List all service keys
 * const { data, error } = await client.admin.serviceKeys.list()
 *
 * // Create a new service key
 * const { data, error } = await client.admin.serviceKeys.create({
 *   name: 'Production API Key',
 *   key_type: 'service',
 *   scopes: ['*']
 * })
 *
 * // Rotate a key
 * const { data, error } = await client.admin.serviceKeys.rotate('key-id')
 * ```
 *
 * @category Admin
 */
declare class ServiceKeysManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all service keys
     *
     * @returns List of service keys
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.serviceKeys.list()
     * ```
     */
    list(): Promise<{
        data: ServiceKey[] | null;
        error: Error | null;
    }>;
    /**
     * Get a service key by ID
     *
     * @param id - Service key ID
     * @returns Service key details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.serviceKeys.get('key-id')
     * ```
     */
    get(id: string): Promise<{
        data: ServiceKey | null;
        error: Error | null;
    }>;
    /**
     * Create a new service key
     *
     * The full key value is only returned once - store it securely!
     *
     * @param request - Key creation options
     * @returns Created key with full key value
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.serviceKeys.create({
     *   name: 'Production API Key',
     *   key_type: 'service',
     *   scopes: ['*'],
     *   rate_limit_per_minute: 1000
     * })
     *
     * if (data) {
     *   // Store data.key securely - it won't be shown again!
     *   console.log('Key created:', data.key)
     * }
     * ```
     */
    create(request: CreateServiceKeyRequest): Promise<{
        data: ServiceKeyWithKey | null;
        error: Error | null;
    }>;
    /**
     * Update a service key
     *
     * @param id - Service key ID
     * @param request - Update options
     * @returns Updated key
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.serviceKeys.update('key-id', {
     *   name: 'New Name',
     *   rate_limit_per_minute: 2000
     * })
     * ```
     */
    update(id: string, request: UpdateServiceKeyRequest): Promise<{
        data: ServiceKey | null;
        error: Error | null;
    }>;
    /**
     * Delete a service key permanently
     *
     * @param id - Service key ID
     * @returns Success or error
     *
     * @example
     * ```typescript
     * const { error } = await client.admin.serviceKeys.delete('key-id')
     * ```
     */
    delete(id: string): Promise<{
        error: Error | null;
    }>;
    /**
     * Disable a service key (temporarily)
     *
     * @param id - Service key ID
     * @returns Success or error
     *
     * @example
     * ```typescript
     * const { error } = await client.admin.serviceKeys.disable('key-id')
     * ```
     */
    disable(id: string): Promise<{
        error: Error | null;
    }>;
    /**
     * Enable a disabled service key
     *
     * @param id - Service key ID
     * @returns Success or error
     *
     * @example
     * ```typescript
     * const { error } = await client.admin.serviceKeys.enable('key-id')
     * ```
     */
    enable(id: string): Promise<{
        error: Error | null;
    }>;
    /**
     * Revoke a service key permanently (emergency)
     *
     * Use for immediate revocation when a key is compromised.
     *
     * @param id - Service key ID
     * @param request - Revocation options
     * @returns Success or error
     *
     * @example
     * ```typescript
     * const { error } = await client.admin.serviceKeys.revoke('key-id', {
     *   reason: 'Key was compromised'
     * })
     * ```
     */
    revoke(id: string, request?: RevokeServiceKeyRequest): Promise<{
        error: Error | null;
    }>;
    /**
     * Deprecate a service key (graceful rotation)
     *
     * Marks the key for removal but keeps it active during grace period.
     *
     * @param id - Service key ID
     * @param request - Deprecation options
     * @returns Deprecation details
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.serviceKeys.deprecate('key-id', {
     *   reason: 'Rotating to new key',
     *   grace_period_hours: 48
     * })
     * ```
     */
    deprecate(id: string, request?: DeprecateServiceKeyRequest): Promise<{
        data: {
            deprecated_at: string;
            grace_period_ends_at: string;
        } | null;
        error: Error | null;
    }>;
    /**
     * Rotate a service key (create replacement)
     *
     * Creates a new key with the same settings and deprecates the old one.
     * The new key is returned with its full value.
     *
     * @param id - Service key ID to rotate
     * @returns New key with full key value
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.serviceKeys.rotate('old-key-id')
     *
     * if (data) {
     *   console.log('New key:', data.key)
     *   console.log('Old key deprecated at:', data.deprecated_at)
     * }
     * ```
     */
    rotate(id: string): Promise<{
        data: ServiceKeyWithKey | null;
        error: Error | null;
    }>;
    /**
     * Get revocation history for a service key
     *
     * @param id - Service key ID
     * @returns Revocation history
     *
     * @example
     * ```typescript
     * const { data, error } = await client.admin.serviceKeys.getRevocationHistory('key-id')
     * ```
     */
    getRevocationHistory(id: string): Promise<{
        data: {
            id: string;
            name: string;
            revoked_at: string;
            revoked_by: string;
            revocation_reason: string;
        } | null;
        error: Error | null;
    }>;
}

/**
 * Admin client for managing Fluxbase instance
 */
declare class FluxbaseAdmin {
    private fetch;
    private adminToken;
    /**
     * Settings manager for system and application settings
     */
    settings: FluxbaseSettings;
    /**
     * DDL manager for database schema and table operations
     */
    ddl: DDLManager;
    /**
     * OAuth configuration manager for provider and auth settings
     */
    oauth: FluxbaseOAuth;
    /**
     * Impersonation manager for user impersonation and audit trail
     */
    impersonation: ImpersonationManager;
    /**
     * Management namespace for client keys, webhooks, and invitations
     */
    management: FluxbaseManagement;
    /**
     * Email template manager for customizing authentication and notification emails
     */
    emailTemplates: EmailTemplateManager;
    /**
     * Functions manager for edge function management (create, update, delete, sync)
     */
    functions: FluxbaseAdminFunctions;
    /**
     * Jobs manager for background job management (create, update, delete, sync, monitoring)
     */
    jobs: FluxbaseAdminJobs;
    /**
     * Migrations manager for database migration operations (create, apply, rollback, sync)
     */
    migrations: FluxbaseAdminMigrations;
    /**
     * AI manager for chatbot and provider management (create, update, delete, sync)
     */
    ai: FluxbaseAdminAI;
    /**
     * RPC manager for procedure management (create, update, delete, sync, execution monitoring)
     */
    rpc: FluxbaseAdminRPC;
    /**
     * Storage manager for bucket and object management (list, create, delete, signed URLs)
     */
    storage: FluxbaseAdminStorage;
    /**
     * Realtime manager for enabling/disabling realtime on tables
     */
    realtime: FluxbaseAdminRealtime;
    /**
     * Service keys manager for API key management (list, create, rotate, revoke)
     */
    serviceKeys: ServiceKeysManager;
    constructor(fetch: FluxbaseFetch);
    /**
     * Set admin authentication token
     */
    setToken(token: string): void;
    /**
     * Get current admin token
     */
    getToken(): string | null;
    /**
     * Clear admin token
     */
    clearToken(): void;
    /**
     * Get system health status
     *
     * @returns Health status including database and realtime service status
     *
     * @example
     * ```typescript
     * const { data, error } = await admin.getHealth();
     * if (data) {
     *   console.log('Status:', data.status);
     *   console.log('Database:', data.services.database);
     *   console.log('Realtime:', data.services.realtime);
     * }
     * ```
     */
    getHealth(): Promise<DataResponse<HealthResponse>>;
    /**
     * Check if initial admin setup is needed
     *
     * @returns Setup status indicating if initial setup is required
     *
     * @example
     * ```typescript
     * const status = await admin.getSetupStatus();
     * if (status.needs_setup) {
     *   console.log('Initial setup required');
     * }
     * ```
     */
    getSetupStatus(): Promise<DataResponse<AdminSetupStatusResponse>>;
    /**
     * Perform initial admin setup
     *
     * Creates the first admin user and completes initial setup.
     * This endpoint can only be called once.
     *
     * @param request - Setup request containing email, password, and name
     * @returns Authentication response with tokens
     *
     * @example
     * ```typescript
     * const response = await admin.setup({
     *   email: 'admin@example.com',
     *   password: 'SecurePassword123!',
     *   name: 'Admin User'
     * });
     *
     * // Store tokens
     * localStorage.setItem('admin_token', response.access_token);
     * ```
     */
    setup(request: AdminSetupRequest): Promise<DataResponse<AdminAuthResponse>>;
    /**
     * Admin login
     *
     * Authenticate as an admin user
     *
     * @param request - Login request containing email and password
     * @returns Authentication response with tokens
     *
     * @example
     * ```typescript
     * const response = await admin.login({
     *   email: 'admin@example.com',
     *   password: 'password123'
     * });
     *
     * // Token is automatically set in the client
     * console.log('Logged in as:', response.user.email);
     * ```
     */
    login(request: AdminLoginRequest): Promise<DataResponse<AdminAuthResponse>>;
    /**
     * Refresh admin access token
     *
     * @param request - Refresh request containing the refresh token
     * @returns New access and refresh tokens
     *
     * @example
     * ```typescript
     * const refreshToken = localStorage.getItem('admin_refresh_token');
     * const response = await admin.refreshToken({ refresh_token: refreshToken });
     *
     * // Update stored tokens
     * localStorage.setItem('admin_token', response.access_token);
     * localStorage.setItem('admin_refresh_token', response.refresh_token);
     * ```
     */
    refreshToken(request: AdminRefreshRequest): Promise<DataResponse<AdminRefreshResponse>>;
    /**
     * Admin logout
     *
     * Invalidates the current admin session
     *
     * @example
     * ```typescript
     * await admin.logout();
     * localStorage.removeItem('admin_token');
     * ```
     */
    logout(): Promise<VoidResponse>;
    /**
     * Get current admin user information
     *
     * @returns Current admin user details
     *
     * @example
     * ```typescript
     * const { user } = await admin.me();
     * console.log('Logged in as:', user.email);
     * console.log('Role:', user.role);
     * ```
     */
    me(): Promise<DataResponse<AdminMeResponse>>;
    /**
     * List all users
     *
     * @param options - Filter and pagination options
     * @returns List of users with metadata
     *
     * @example
     * ```typescript
     * // List all users
     * const { users, total } = await admin.listUsers();
     *
     * // List with filters
     * const result = await admin.listUsers({
     *   exclude_admins: true,
     *   search: 'john',
     *   limit: 50,
     *   type: 'app'
     * });
     * ```
     */
    listUsers(options?: ListUsersOptions): Promise<DataResponse<ListUsersResponse>>;
    /**
     * Get a user by ID
     *
     * Fetch a single user's details by their user ID
     *
     * @param userId - User ID to fetch
     * @param type - User type ('app' or 'dashboard')
     * @returns User details with metadata
     *
     * @example
     * ```typescript
     * // Get an app user
     * const user = await admin.getUserById('user-123');
     *
     * // Get a dashboard user
     * const dashboardUser = await admin.getUserById('admin-456', 'dashboard');
     * console.log('User email:', dashboardUser.email);
     * console.log('Last login:', dashboardUser.last_login_at);
     * ```
     */
    getUserById(userId: string, type?: "app" | "dashboard"): Promise<DataResponse<EnrichedUser>>;
    /**
     * Invite a new user
     *
     * Creates a new user and optionally sends an invitation email
     *
     * @param request - User invitation details
     * @param type - User type ('app' or 'dashboard')
     * @returns Created user and invitation details
     *
     * @example
     * ```typescript
     * const response = await admin.inviteUser({
     *   email: 'newuser@example.com',
     *   role: 'user',
     *   send_email: true
     * });
     *
     * console.log('User invited:', response.user.email);
     * console.log('Invitation link:', response.invitation_link);
     * ```
     */
    inviteUser(request: InviteUserRequest, type?: "app" | "dashboard"): Promise<DataResponse<InviteUserResponse>>;
    /**
     * Delete a user
     *
     * Permanently deletes a user and all associated data
     *
     * @param userId - User ID to delete
     * @param type - User type ('app' or 'dashboard')
     * @returns Deletion confirmation
     *
     * @example
     * ```typescript
     * await admin.deleteUser('user-uuid');
     * console.log('User deleted');
     * ```
     */
    deleteUser(userId: string, type?: "app" | "dashboard"): Promise<DataResponse<DeleteUserResponse>>;
    /**
     * Update user role
     *
     * Changes a user's role
     *
     * @param userId - User ID
     * @param role - New role
     * @param type - User type ('app' or 'dashboard')
     * @returns Updated user
     *
     * @example
     * ```typescript
     * const user = await admin.updateUserRole('user-uuid', 'admin');
     * console.log('User role updated:', user.role);
     * ```
     */
    updateUserRole(userId: string, role: string, type?: "app" | "dashboard"): Promise<DataResponse<EnrichedUser>>;
    /**
     * Reset user password
     *
     * Generates a new password for the user and optionally sends it via email
     *
     * @param userId - User ID
     * @param type - User type ('app' or 'dashboard')
     * @returns Reset confirmation message
     *
     * @example
     * ```typescript
     * const response = await admin.resetUserPassword('user-uuid');
     * console.log(response.message);
     * ```
     */
    resetUserPassword(userId: string, type?: "app" | "dashboard"): Promise<DataResponse<ResetUserPasswordResponse>>;
}

/**
 * Secrets Management module for Fluxbase SDK
 *
 * Provides methods for managing secrets that are injected into edge functions
 * and background jobs at runtime. Secrets are encrypted at rest and scoped
 * to either global or namespace level.
 *
 * @example
 * ```typescript
 * // Create a secret
 * const secret = await client.secrets.create({
 *   name: 'API_KEY',
 *   value: 'sk-your-api-key',
 *   scope: 'global'
 * })
 *
 * // Get secret by name
 * const secret = await client.secrets.get('API_KEY')
 *
 * // Update secret by name
 * await client.secrets.update('API_KEY', { value: 'new-value' })
 *
 * // List all secrets
 * const secrets = await client.secrets.list()
 * ```
 *
 * @category Secrets
 */

/**
 * Represents a stored secret (metadata only, never includes value)
 */
interface Secret {
    id: string;
    name: string;
    scope: 'global' | 'namespace';
    namespace?: string;
    description?: string;
    version: number;
    expires_at?: string;
    created_at: string;
    updated_at: string;
    created_by?: string;
    updated_by?: string;
}
/**
 * Summary of a secret for list responses
 */
interface SecretSummary {
    id: string;
    name: string;
    scope: 'global' | 'namespace';
    namespace?: string;
    description?: string;
    version: number;
    expires_at?: string;
    is_expired: boolean;
    created_at: string;
    updated_at: string;
    created_by?: string;
    updated_by?: string;
}
/**
 * Represents a historical version of a secret
 */
interface SecretVersion {
    id: string;
    secret_id: string;
    version: number;
    created_at: string;
    created_by?: string;
}
/**
 * Statistics about secrets
 */
interface SecretStats {
    total: number;
    expiring_soon: number;
    expired: number;
}
/**
 * Request to create a new secret
 */
interface CreateSecretRequest {
    name: string;
    value: string;
    scope?: 'global' | 'namespace';
    namespace?: string;
    description?: string;
    expires_at?: string;
}
/**
 * Request to update an existing secret
 */
interface UpdateSecretRequest {
    value?: string;
    description?: string;
    expires_at?: string;
}
/**
 * Options for listing secrets
 */
interface ListSecretsOptions {
    scope?: 'global' | 'namespace';
    namespace?: string;
}
/**
 * Options for name-based secret operations
 */
interface SecretByNameOptions {
    namespace?: string;
}
/**
 * Secrets Manager for managing edge function and job secrets
 *
 * Provides both name-based (recommended) and UUID-based operations.
 * Name-based operations are more convenient for most use cases.
 *
 * @example
 * ```typescript
 * const client = createClient({ url: 'http://localhost:8080' })
 * await client.auth.login({ email: 'user@example.com', password: 'password' })
 *
 * // Create a global secret
 * const secret = await client.secrets.create({
 *   name: 'STRIPE_KEY',
 *   value: 'sk_live_xxx',
 *   description: 'Stripe production API key'
 * })
 *
 * // Create a namespace-scoped secret
 * await client.secrets.create({
 *   name: 'DATABASE_URL',
 *   value: 'postgres://...',
 *   scope: 'namespace',
 *   namespace: 'production'
 * })
 *
 * // Get secret by name
 * const secret = await client.secrets.get('STRIPE_KEY')
 *
 * // Get namespace-scoped secret
 * const secret = await client.secrets.get('DATABASE_URL', { namespace: 'production' })
 *
 * // Update secret
 * await client.secrets.update('STRIPE_KEY', { value: 'sk_live_new_key' })
 *
 * // List all secrets
 * const secrets = await client.secrets.list()
 *
 * // Get version history
 * const versions = await client.secrets.getVersions('STRIPE_KEY')
 *
 * // Rollback to previous version
 * await client.secrets.rollback('STRIPE_KEY', 1)
 *
 * // Delete secret
 * await client.secrets.delete('STRIPE_KEY')
 * ```
 *
 * @category Secrets
 */
declare class SecretsManager {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Create a new secret
     *
     * Creates a new secret with the specified name, value, and scope.
     * The value is encrypted at rest and never returned by the API.
     *
     * @param request - Secret creation request
     * @returns Promise resolving to the created secret (metadata only)
     *
     * @example
     * ```typescript
     * // Create a global secret
     * const secret = await client.secrets.create({
     *   name: 'SENDGRID_API_KEY',
     *   value: 'SG.xxx',
     *   description: 'SendGrid API key for transactional emails'
     * })
     *
     * // Create a namespace-scoped secret
     * const secret = await client.secrets.create({
     *   name: 'DATABASE_URL',
     *   value: 'postgres://user:pass@host:5432/db',
     *   scope: 'namespace',
     *   namespace: 'production',
     *   description: 'Production database URL'
     * })
     *
     * // Create a secret with expiration
     * const secret = await client.secrets.create({
     *   name: 'TEMP_TOKEN',
     *   value: 'xyz123',
     *   expires_at: '2025-12-31T23:59:59Z'
     * })
     * ```
     */
    create(request: CreateSecretRequest): Promise<Secret>;
    /**
     * Get a secret by name (metadata only, never includes value)
     *
     * @param name - Secret name
     * @param options - Optional namespace for namespace-scoped secrets
     * @returns Promise resolving to the secret
     *
     * @example
     * ```typescript
     * // Get a global secret
     * const secret = await client.secrets.get('API_KEY')
     *
     * // Get a namespace-scoped secret
     * const secret = await client.secrets.get('DATABASE_URL', { namespace: 'production' })
     * ```
     */
    get(name: string, options?: SecretByNameOptions): Promise<Secret>;
    /**
     * Update a secret by name
     *
     * Updates the secret's value, description, or expiration.
     * Only provided fields will be updated.
     *
     * @param name - Secret name
     * @param request - Update request
     * @param options - Optional namespace for namespace-scoped secrets
     * @returns Promise resolving to the updated secret
     *
     * @example
     * ```typescript
     * // Update secret value
     * const secret = await client.secrets.update('API_KEY', { value: 'new-value' })
     *
     * // Update description
     * const secret = await client.secrets.update('API_KEY', { description: 'Updated description' })
     *
     * // Update namespace-scoped secret
     * const secret = await client.secrets.update('DATABASE_URL',
     *   { value: 'postgres://new-host:5432/db' },
     *   { namespace: 'production' }
     * )
     * ```
     */
    update(name: string, request: UpdateSecretRequest, options?: SecretByNameOptions): Promise<Secret>;
    /**
     * Delete a secret by name
     *
     * Permanently deletes the secret and all its versions.
     *
     * @param name - Secret name
     * @param options - Optional namespace for namespace-scoped secrets
     * @returns Promise resolving when deletion is complete
     *
     * @example
     * ```typescript
     * // Delete a global secret
     * await client.secrets.delete('OLD_API_KEY')
     *
     * // Delete a namespace-scoped secret
     * await client.secrets.delete('DATABASE_URL', { namespace: 'staging' })
     * ```
     */
    delete(name: string, options?: SecretByNameOptions): Promise<void>;
    /**
     * Get version history for a secret by name
     *
     * Returns all historical versions of the secret (values are never included).
     *
     * @param name - Secret name
     * @param options - Optional namespace for namespace-scoped secrets
     * @returns Promise resolving to array of secret versions
     *
     * @example
     * ```typescript
     * const versions = await client.secrets.getVersions('API_KEY')
     *
     * versions.forEach(v => {
     *   console.log(`Version ${v.version} created at ${v.created_at}`)
     * })
     * ```
     */
    getVersions(name: string, options?: SecretByNameOptions): Promise<SecretVersion[]>;
    /**
     * Rollback a secret to a previous version by name
     *
     * Restores the secret to a previous version's value.
     * This creates a new version with the old value.
     *
     * @param name - Secret name
     * @param version - Version number to rollback to
     * @param options - Optional namespace for namespace-scoped secrets
     * @returns Promise resolving to the updated secret
     *
     * @example
     * ```typescript
     * // Rollback to version 2
     * const secret = await client.secrets.rollback('API_KEY', 2)
     * console.log(`Secret now at version ${secret.version}`)
     * ```
     */
    rollback(name: string, version: number, options?: SecretByNameOptions): Promise<Secret>;
    /**
     * List all secrets (metadata only, never includes values)
     *
     * @param options - Filter options for scope and namespace
     * @returns Promise resolving to array of secret summaries
     *
     * @example
     * ```typescript
     * // List all secrets
     * const secrets = await client.secrets.list()
     *
     * // List only global secrets
     * const secrets = await client.secrets.list({ scope: 'global' })
     *
     * // List secrets for a specific namespace
     * const secrets = await client.secrets.list({ namespace: 'production' })
     *
     * secrets.forEach(s => {
     *   console.log(`${s.name}: version ${s.version}, expired: ${s.is_expired}`)
     * })
     * ```
     */
    list(options?: ListSecretsOptions): Promise<SecretSummary[]>;
    /**
     * Get statistics about secrets
     *
     * @returns Promise resolving to secret statistics
     *
     * @example
     * ```typescript
     * const stats = await client.secrets.stats()
     * console.log(`Total: ${stats.total}, Expiring soon: ${stats.expiring_soon}, Expired: ${stats.expired}`)
     * ```
     */
    stats(): Promise<SecretStats>;
    /**
     * Get a secret by ID (metadata only)
     *
     * @param id - Secret UUID
     * @returns Promise resolving to the secret
     *
     * @example
     * ```typescript
     * const secret = await client.secrets.getById('550e8400-e29b-41d4-a716-446655440000')
     * ```
     */
    getById(id: string): Promise<Secret>;
    /**
     * Update a secret by ID
     *
     * @param id - Secret UUID
     * @param request - Update request
     * @returns Promise resolving to the updated secret
     *
     * @example
     * ```typescript
     * const secret = await client.secrets.updateById('550e8400-e29b-41d4-a716-446655440000', {
     *   value: 'new-value'
     * })
     * ```
     */
    updateById(id: string, request: UpdateSecretRequest): Promise<Secret>;
    /**
     * Delete a secret by ID
     *
     * @param id - Secret UUID
     * @returns Promise resolving when deletion is complete
     *
     * @example
     * ```typescript
     * await client.secrets.deleteById('550e8400-e29b-41d4-a716-446655440000')
     * ```
     */
    deleteById(id: string): Promise<void>;
    /**
     * Get version history for a secret by ID
     *
     * @param id - Secret UUID
     * @returns Promise resolving to array of secret versions
     *
     * @example
     * ```typescript
     * const versions = await client.secrets.getVersionsById('550e8400-e29b-41d4-a716-446655440000')
     * ```
     */
    getVersionsById(id: string): Promise<SecretVersion[]>;
    /**
     * Rollback a secret to a previous version by ID
     *
     * @param id - Secret UUID
     * @param version - Version number to rollback to
     * @returns Promise resolving to the updated secret
     *
     * @example
     * ```typescript
     * const secret = await client.secrets.rollbackById('550e8400-e29b-41d4-a716-446655440000', 2)
     * ```
     */
    rollbackById(id: string, version: number): Promise<Secret>;
}

/**
 * AI Chat module for interacting with AI chatbots
 * Provides WebSocket-based chat functionality with streaming support
 */

/**
 * Event types for chat callbacks
 */
type AIChatEventType = "connected" | "chat_started" | "progress" | "content" | "query_result" | "tool_result" | "done" | "error" | "cancelled" | "disconnected";
/**
 * Chat event data
 */
interface AIChatEvent {
    type: AIChatEventType;
    conversationId?: string;
    chatbot?: string;
    step?: string;
    message?: string;
    delta?: string;
    query?: string;
    summary?: string;
    rowCount?: number;
    data?: Record<string, any>[];
    usage?: AIUsageStats;
    error?: string;
    code?: string;
}
/**
 * Chat connection options
 */
interface AIChatOptions {
    /** WebSocket URL (defaults to ws://host/ai/ws) */
    wsUrl?: string;
    /** JWT token for authentication */
    token?: string;
    /** Callback for all events */
    onEvent?: (event: AIChatEvent) => void;
    /** Callback for content chunks (streaming) */
    onContent?: (delta: string, conversationId: string) => void;
    /** Callback for progress updates */
    onProgress?: (step: string, message: string, conversationId: string) => void;
    /** Callback for query results */
    onQueryResult?: (query: string, summary: string, rowCount: number, data: Record<string, any>[], conversationId: string) => void;
    /** Callback when message is complete */
    onDone?: (usage: AIUsageStats | undefined, conversationId: string, 
    /**
     * Turn metadata (Ask 2/4/5). Optional third argument — old callbacks
     * that only declare two params keep working unchanged.
     */
    extras?: {
        matched_intent_rules?: AIMatchedIntentRule[];
        daily_quota?: AIDailyQuotaSnapshot;
    }) => void;
    /** Callback for errors */
    onError?: (error: string, code: string | undefined, conversationId: string | undefined) => void;
    /** Reconnect attempts (0 = no reconnect) */
    reconnectAttempts?: number;
    /** Reconnect delay in ms */
    reconnectDelay?: number;
    /** @internal Lookup function for smart namespace resolution */
    _lookupChatbot?: (name: string) => Promise<{
        data: AIChatbotLookupResponse | null;
        error: Error | null;
    }>;
}
/**
 * AI Chat client for WebSocket-based chat with AI chatbots
 *
 * @example
 * ```typescript
 * const chat = new FluxbaseAIChat({
 *   wsUrl: 'ws://localhost:8080/ai/ws',
 *   token: 'my-jwt-token',
 *   onContent: (delta, convId) => {
 *     process.stdout.write(delta)
 *   },
 *   onProgress: (step, message) => {
 *     console.log(`[${step}] ${message}`)
 *   },
 *   onQueryResult: (query, summary, rowCount, data) => {
 *     console.log(`Query: ${query}`)
 *     console.log(`Result: ${summary} (${rowCount} rows)`)
 *   },
 *   onDone: (usage) => {
 *     console.log(`\nTokens: ${usage?.total_tokens}`)
 *   },
 *   onError: (error, code) => {
 *     console.error(`Error: ${error} (${code})`)
 *   },
 * })
 *
 * await chat.connect()
 * const convId = await chat.startChat('sql-assistant')
 * await chat.sendMessage(convId, 'Show me the top 10 users by order count')
 * ```
 */
declare class FluxbaseAIChat {
    private ws;
    private options;
    private reconnectCount;
    private pendingStartResolve;
    private pendingStartReject;
    private accumulatedContent;
    constructor(options: AIChatOptions);
    /**
     * Connect to the AI chat WebSocket
     *
     * @returns Promise that resolves when connected
     */
    connect(): Promise<void>;
    /**
     * Disconnect from the AI chat WebSocket
     */
    disconnect(): void;
    /**
     * Check if connected
     */
    isConnected(): boolean;
    /**
     * Start a new chat session with a chatbot
     *
     * @param chatbot - Chatbot name
     * @param namespace - Optional namespace. If not provided and a lookup function is available,
     *                    performs smart resolution:
     *                    - If exactly one chatbot with this name exists, uses it
     *                    - If multiple exist, tries "default" namespace
     *                    - If ambiguous and not in default, throws error with available namespaces
     *                    If no lookup function, falls back to "default" namespace.
     * @param conversationId - Optional conversation ID to resume
     * @param impersonateUserId - Optional user ID to impersonate (admin only)
     * @returns Promise resolving to conversation ID
     */
    startChat(chatbot: string, namespace?: string, conversationId?: string, impersonateUserId?: string): Promise<string>;
    /**
     * Send a message in a conversation
     *
     * @param conversationId - Conversation ID
     * @param content - Message content
     */
    sendMessage(conversationId: string, content: string): void;
    /**
     * Cancel an ongoing message generation
     *
     * @param conversationId - Conversation ID
     */
    cancel(conversationId: string): void;
    /**
     * Get the full accumulated response content for a conversation
     *
     * @param conversationId - Conversation ID
     * @returns Accumulated content string
     */
    getAccumulatedContent(conversationId: string): string;
    private buildWsUrl;
    private handleMessage;
    private serverMessageToEvent;
    private emitEvent;
    private handleClose;
}
/**
 * Fluxbase AI client for listing chatbots and managing conversations
 *
 * @example
 * ```typescript
 * const ai = new FluxbaseAI(fetchClient, 'ws://localhost:8080')
 *
 * // List available chatbots
 * const { data, error } = await ai.listChatbots()
 *
 * // Create a chat connection
 * const chat = ai.createChat({
 *   token: 'my-jwt-token',
 *   onContent: (delta) => process.stdout.write(delta),
 * })
 *
 * await chat.connect()
 * const convId = await chat.startChat('sql-assistant')
 * chat.sendMessage(convId, 'Show me recent orders')
 * ```
 */
declare class FluxbaseAI {
    private fetch;
    private wsBaseUrl;
    constructor(fetch: {
        get: <T>(path: string) => Promise<T>;
        patch: <T>(path: string, body?: unknown) => Promise<T>;
        delete: (path: string) => Promise<void>;
    }, wsBaseUrl: string);
    /**
     * List available chatbots (public, enabled)
     *
     * @returns Promise resolving to { data, error } tuple with array of chatbot summaries
     */
    listChatbots(namespace?: string): Promise<{
        data: AIChatbotSummary[] | null;
        error: Error | null;
    }>;
    /**
     * Get details of a specific chatbot
     *
     * @param id - Chatbot ID
     * @returns Promise resolving to { data, error } tuple with chatbot details
     */
    getChatbot(id: string): Promise<{
        data: AIChatbotSummary | null;
        error: Error | null;
    }>;
    /**
     * Lookup a chatbot by name with smart namespace resolution
     *
     * Resolution logic:
     * 1. If exactly one chatbot with this name exists -> returns it
     * 2. If multiple exist -> tries "default" namespace first
     * 3. If multiple exist and none in "default" -> returns ambiguous=true with namespaces list
     *
     * @param name - Chatbot name
     * @returns Promise resolving to { data, error } tuple with lookup result
     *
     * @example
     * ```typescript
     * // Lookup chatbot by name
     * const { data, error } = await ai.lookupChatbot('sql-assistant')
     * if (data?.chatbot) {
     *   console.log(`Found in namespace: ${data.chatbot.namespace}`)
     * } else if (data?.ambiguous) {
     *   console.log(`Chatbot exists in: ${data.namespaces?.join(', ')}`)
     * }
     * ```
     */
    lookupChatbot(name: string): Promise<{
        data: AIChatbotLookupResponse | null;
        error: Error | null;
    }>;
    /**
     * Create a new AI chat connection
     *
     * @param options - Chat connection options
     * @returns FluxbaseAIChat instance
     */
    createChat(options: Omit<AIChatOptions, "wsUrl" | "_lookupChatbot">): FluxbaseAIChat;
    /**
     * List the authenticated user's conversations
     *
     * @param options - Optional filters and pagination
     * @returns Promise resolving to { data, error } tuple with conversations
     *
     * @example
     * ```typescript
     * // List all conversations
     * const { data, error } = await ai.listConversations()
     *
     * // Filter by chatbot
     * const { data, error } = await ai.listConversations({ chatbot: 'sql-assistant' })
     *
     * // With pagination
     * const { data, error } = await ai.listConversations({ limit: 20, offset: 0 })
     * ```
     */
    listConversations(options?: ListConversationsOptions): Promise<{
        data: ListConversationsResult | null;
        error: Error | null;
    }>;
    /**
     * Get a single conversation with all messages
     *
     * @param id - Conversation ID
     * @returns Promise resolving to { data, error } tuple with conversation detail
     *
     * @example
     * ```typescript
     * const { data, error } = await ai.getConversation('conv-uuid-123')
     * if (data) {
     *   console.log(`Title: ${data.title}`)
     *   console.log(`Messages: ${data.messages.length}`)
     * }
     * ```
     */
    getConversation(id: string): Promise<{
        data: AIUserConversationDetail | null;
        error: Error | null;
    }>;
    /**
     * Delete a conversation
     *
     * @param id - Conversation ID
     * @returns Promise resolving to { error } (null on success)
     *
     * @example
     * ```typescript
     * const { error } = await ai.deleteConversation('conv-uuid-123')
     * if (!error) {
     *   console.log('Conversation deleted')
     * }
     * ```
     */
    deleteConversation(id: string): Promise<{
        error: Error | null;
    }>;
    /**
     * Update a conversation (currently supports title update only)
     *
     * @param id - Conversation ID
     * @param updates - Fields to update
     * @returns Promise resolving to { data, error } tuple with updated conversation
     *
     * @example
     * ```typescript
     * const { data, error } = await ai.updateConversation('conv-uuid-123', {
     *   title: 'My custom conversation title'
     * })
     * ```
     */
    updateConversation(id: string, updates: UpdateConversationOptions): Promise<{
        data: AIUserConversationDetail | null;
        error: Error | null;
    }>;
    /**
     * Get the current user's daily quota for a chatbot (Ask 2).
     *
     * Returns requests used/limit and tokens used/limit, plus the RFC3339
     * timestamp of when the counters reset. Best-effort: counters are in-memory
     * and reset on server restart; per-instance in multi-replica deployments.
     *
     * For per-turn updates without an extra round-trip, read `daily_quota` from
     * the `onDone` callback's third argument.
     *
     * @param chatbotId - Chatbot ID
     * @returns Promise resolving to { data, error } with the quota snapshot
     *
     * @example
     * ```typescript
     * const { data, error } = await ai.getUsage('chatbot-uuid')
     * if (data) {
     *   console.log(`${data.requests.limit - data.requests.used} requests left today`)
     *   console.log(`${data.tokens.limit - data.tokens.used} tokens left today`)
     * }
     * ```
     */
    getUsage(chatbotId: string): Promise<{
        data: AIDailyQuotaSnapshot | null;
        error: Error | null;
    }>;
}

/**
 * Vector search module for Fluxbase SDK
 * Provides convenience methods for vector similarity search using pgvector
 */

/**
 * FluxbaseVector provides vector search functionality using pgvector
 *
 * @example
 * ```typescript
 * // Embed text and search
 * const { data: results } = await client.vector.search({
 *   table: 'documents',
 *   column: 'embedding',
 *   query: 'How to use TypeScript?',
 *   match_count: 10
 * })
 *
 * // Embed text directly
 * const { data: embedding } = await client.vector.embed({ text: 'Hello world' })
 * ```
 */
declare class FluxbaseVector {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * Generate embeddings for text
     *
     * @example
     * ```typescript
     * // Single text
     * const { data } = await client.vector.embed({
     *   text: 'Hello world'
     * })
     * console.log(data.embeddings[0]) // [0.1, 0.2, ...]
     *
     * // Multiple texts
     * const { data } = await client.vector.embed({
     *   texts: ['Hello', 'World'],
     *   model: 'text-embedding-3-small'
     * })
     * ```
     */
    embed(request: EmbedRequest): Promise<FluxbaseResponse<EmbedResponse>>;
    /**
     * Search for similar vectors with automatic text embedding
     *
     * This is a convenience method that:
     * 1. Embeds the query text automatically (if `query` is provided)
     * 2. Performs vector similarity search
     * 3. Returns results with distance scores
     *
     * @example
     * ```typescript
     * // Search with text query (auto-embedded)
     * const { data } = await client.vector.search({
     *   table: 'documents',
     *   column: 'embedding',
     *   query: 'How to use TypeScript?',
     *   match_count: 10,
     *   match_threshold: 0.8
     * })
     *
     * // Search with pre-computed vector
     * const { data } = await client.vector.search({
     *   table: 'documents',
     *   column: 'embedding',
     *   vector: [0.1, 0.2, ...],
     *   metric: 'cosine',
     *   match_count: 10
     * })
     *
     * // With additional filters
     * const { data } = await client.vector.search({
     *   table: 'documents',
     *   column: 'embedding',
     *   query: 'TypeScript tutorial',
     *   filters: [
     *     { column: 'status', operator: 'eq', value: 'published' }
     *   ],
     *   match_count: 10
     * })
     * ```
     */
    search<T = Record<string, unknown>>(options: VectorSearchOptions): Promise<FluxbaseResponse<VectorSearchResult<T>>>;
}

/**
 * Knowledge Base module for Fluxbase SDK
 * Provides RAG document management, semantic search, and knowledge graph operations
 */

/**
 * FluxbaseKnowledgeBase provides knowledge base management for RAG applications
 *
 * @example
 * ```typescript
 * // List knowledge bases
 * const { data: kbs } = await client.knowledgeBase.list()
 *
 * // Create a knowledge base
 * const { data: kb } = await client.knowledgeBase.create({
 *   name: 'Product Docs',
 *   description: 'Product documentation for RAG'
 * })
 *
 * // Add a document
 * const { data } = await client.knowledgeBase.addDocument(kb.id, {
 *   title: 'Getting Started',
 *   content: 'Welcome to our product...'
 * })
 *
 * // Search the knowledge base
 * const { data: results } = await client.knowledgeBase.search(kb.id, {
 *   query: 'How to get started?'
 * })
 * ```
 *
 * @category AI
 */
declare class FluxbaseKnowledgeBase {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all knowledge bases the user has access to
     *
     * @example
     * ```typescript
     * const { data, error } = await client.knowledgeBase.list()
     * ```
     */
    list(): Promise<FluxbaseResponse<KnowledgeBaseSummary[]>>;
    /**
     * Get a knowledge base by ID
     *
     * @param id - Knowledge base ID
     */
    get(id: string): Promise<FluxbaseResponse<KnowledgeBase>>;
    /**
     * Create a new knowledge base
     *
     * @param request - Knowledge base configuration
     * @example
     * ```typescript
     * const { data, error } = await client.knowledgeBase.create({
     *   name: 'Product Docs',
     *   description: 'Product documentation',
     *   embedding_model: 'text-embedding-3-small',
     *   chunk_size: 1000,
     *   chunk_overlap: 200
     * })
     * ```
     */
    create(request: CreateKnowledgeBaseRequest): Promise<FluxbaseResponse<KnowledgeBase>>;
    /**
     * Update a knowledge base
     *
     * @param id - Knowledge base ID
     * @param updates - Fields to update
     */
    update(id: string, updates: UpdateKnowledgeBaseRequest): Promise<FluxbaseResponse<KnowledgeBase>>;
    /**
     * Delete a knowledge base
     *
     * @param id - Knowledge base ID
     */
    delete(id: string): Promise<{
        data: boolean;
        error: Error | null;
    }>;
    /**
     * List documents in a knowledge base
     *
     * @param kbId - Knowledge base ID
     */
    listDocuments(kbId: string): Promise<FluxbaseResponse<KnowledgeBaseDocument[]>>;
    /**
     * Get a single document
     *
     * @param kbId - Knowledge base ID
     * @param docId - Document ID
     */
    getDocument(kbId: string, docId: string): Promise<FluxbaseResponse<KnowledgeBaseDocument>>;
    /**
     * Add a document with text content
     *
     * @param kbId - Knowledge base ID
     * @param request - Document content and metadata
     * @example
     * ```typescript
     * const { data } = await client.knowledgeBase.addDocument(kbId, {
     *   title: 'API Reference',
     *   content: 'The API supports REST and GraphQL...',
     *   metadata: { category: 'reference' },
     *   tags: ['api', 'reference']
     * })
     * ```
     */
    addDocument(kbId: string, request: AddDocumentRequest): Promise<FluxbaseResponse<AddDocumentResponse>>;
    /**
     * Upload a file as a document
     *
     * Supports: PDF, TXT, MD, HTML, CSV, DOCX, XLSX, RTF, EPUB, JSON (max 50MB)
     *
     * @param kbId - Knowledge base ID
     * @param file - File to upload (File, Blob, or ArrayBuffer)
     * @param filename - Name of the file
     * @param metadata - Optional metadata
     * @example
     * ```typescript
     * const file = new File(['content'], 'guide.pdf', { type: 'application/pdf' })
     * const { data } = await client.knowledgeBase.uploadDocument(kbId, file, 'guide.pdf')
     * ```
     */
    uploadDocument(kbId: string, file: File | Blob | ArrayBuffer, filename: string, metadata?: Record<string, string>): Promise<FluxbaseResponse<UploadDocumentResponse>>;
    /**
     * Update a document's metadata
     *
     * @param kbId - Knowledge base ID
     * @param docId - Document ID
     * @param updates - Fields to update
     */
    updateDocument(kbId: string, docId: string, updates: UpdateDocumentRequest): Promise<FluxbaseResponse<KnowledgeBaseDocument>>;
    /**
     * Delete a document
     *
     * @param kbId - Knowledge base ID
     * @param docId - Document ID
     */
    deleteDocument(kbId: string, docId: string): Promise<{
        data: boolean;
        error: Error | null;
    }>;
    /**
     * Delete documents matching a filter (bulk operation)
     *
     * @param kbId - Knowledge base ID
     * @param filter - Filter criteria (by tags and/or metadata)
     */
    deleteDocumentsByFilter(kbId: string, filter: DeleteDocumentsByFilterRequest): Promise<FluxbaseResponse<DeleteDocumentsByFilterResponse>>;
    /**
     * Search a knowledge base using semantic similarity
     *
     * Automatically embeds the query text and returns matching chunks.
     *
     * @param kbId - Knowledge base ID
     * @param request - Search parameters
     * @example
     * ```typescript
     * const { data, error } = await client.knowledgeBase.search(kbId, {
     *   query: 'How to configure authentication?',
     *   max_chunks: 5,
     *   threshold: 0.8
     * })
     *
     * data.results.forEach(result => {
     *   console.log(result.document_title, result.similarity)
     *   console.log(result.content)
     * })
     * ```
     */
    search(kbId: string, request: SearchKnowledgeBaseRequest): Promise<FluxbaseResponse<SearchKnowledgeBaseResponse>>;
    /**
     * List entities in a knowledge base
     *
     * @param kbId - Knowledge base ID
     * @param type - Optional entity type filter
     */
    listEntities(kbId: string, type?: EntityType): Promise<FluxbaseResponse<Entity[]>>;
    /**
     * Search entities by name
     *
     * @param kbId - Knowledge base ID
     * @param query - Search query
     */
    searchEntities(kbId: string, query: string): Promise<FluxbaseResponse<Entity[]>>;
    /**
     * Get relationships for an entity
     *
     * @param kbId - Knowledge base ID
     * @param entityId - Entity ID
     */
    getEntityRelationships(kbId: string, entityId: string): Promise<FluxbaseResponse<EntityRelationship[]>>;
    /**
     * Get the full knowledge graph for a knowledge base
     *
     * Returns all entities and relationships for visualization.
     *
     * @param kbId - Knowledge base ID
     */
    getKnowledgeGraph(kbId: string): Promise<FluxbaseResponse<KnowledgeGraphData>>;
}

/**
 * GraphQL client for Fluxbase
 *
 * Provides a type-safe interface for executing GraphQL queries and mutations
 * against the auto-generated GraphQL schema from your database tables.
 *
 * @example
 * ```typescript
 * import { createClient } from '@nimbleflux/fluxbase-sdk'
 *
 * const client = createClient({ url: 'http://localhost:8080' })
 *
 * // Execute a query
 * const { data, errors } = await client.graphql.query(`
 *   query GetUsers($limit: Int) {
 *     users(limit: $limit) {
 *       id
 *       email
 *       posts {
 *         title
 *       }
 *     }
 *   }
 * `, { limit: 10 })
 *
 * // Execute a mutation
 * const { data, errors } = await client.graphql.mutation(`
 *   mutation CreateUser($data: UserInput!) {
 *     insertUser(data: $data) {
 *       id
 *       email
 *     }
 *   }
 * `, { data: { email: 'user@example.com' } })
 * ```
 *
 * @category GraphQL
 */

/**
 * GraphQL error location in the query
 */
interface GraphQLErrorLocation {
    line: number;
    column: number;
}
/**
 * GraphQL error returned from the server
 */
interface GraphQLError {
    message: string;
    locations?: GraphQLErrorLocation[];
    path?: (string | number)[];
    extensions?: Record<string, unknown>;
}
/**
 * GraphQL response from the server
 */
interface GraphQLResponse<T = unknown> {
    data?: T;
    errors?: GraphQLError[];
}
/**
 * Options for GraphQL requests
 */
interface GraphQLRequestOptions {
    /**
     * Custom headers to include in the request
     */
    headers?: Record<string, string>;
    /**
     * Request timeout in milliseconds
     */
    timeout?: number;
}
/**
 * GraphQL client class for executing queries and mutations
 *
 * @category GraphQL
 */
declare class FluxbaseGraphQL {
    private fetch;
    /**
     * Create a new GraphQL client
     * @param fetch - The HTTP client to use for requests
     */
    constructor(fetch: FluxbaseFetch);
    /**
     * Execute a GraphQL query
     *
     * @typeParam T - The expected response data type
     * @param query - The GraphQL query string
     * @param variables - Variables to pass to the query
     * @param options - Additional request options
     * @returns Promise resolving to the GraphQL response
     *
     * @example
     * ```typescript
     * interface UsersQuery {
     *   users: Array<{ id: string; email: string }>
     * }
     *
     * const { data, errors } = await client.graphql.query<UsersQuery>(`
     *   query {
     *     users { id email }
     *   }
     * `)
     *
     * if (data) {
     *   console.log(data.users)
     * }
     * ```
     */
    query<T = unknown>(query: string, variables?: Record<string, unknown>, options?: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;
    /**
     * Execute a GraphQL mutation
     *
     * @typeParam T - The expected response data type
     * @param mutation - The GraphQL mutation string
     * @param variables - Variables to pass to the mutation
     * @param options - Additional request options
     * @returns Promise resolving to the GraphQL response
     *
     * @example
     * ```typescript
     * interface CreateUserMutation {
     *   insertUser: { id: string; email: string }
     * }
     *
     * const { data, errors } = await client.graphql.mutation<CreateUserMutation>(`
     *   mutation CreateUser($data: UserInput!) {
     *     insertUser(data: $data) {
     *       id
     *       email
     *     }
     *   }
     * `, { data: { email: 'user@example.com' } })
     * ```
     */
    mutation<T = unknown>(mutation: string, variables?: Record<string, unknown>, options?: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;
    /**
     * Execute a GraphQL request with an operation name
     *
     * Use this when your query document contains multiple operations
     * and you need to specify which one to execute.
     *
     * @typeParam T - The expected response data type
     * @param query - The GraphQL document containing one or more operations
     * @param variables - Variables to pass to the operation
     * @param operationName - The name of the operation to execute
     * @param options - Additional request options
     * @returns Promise resolving to the GraphQL response
     *
     * @example
     * ```typescript
     * const { data } = await client.graphql.execute(`
     *   query GetUser($id: ID!) {
     *     user(id: $id) { id email }
     *   }
     *   query ListUsers {
     *     users { id email }
     *   }
     * `, { id: '123' }, 'GetUser')
     * ```
     */
    execute<T = unknown>(query: string, variables?: Record<string, unknown>, operationName?: string, options?: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;
    /**
     * Fetch the GraphQL schema via introspection
     *
     * Returns the full schema information including types, fields, and directives.
     * Useful for tooling and documentation.
     *
     * @param options - Additional request options
     * @returns Promise resolving to the introspection result
     *
     * @example
     * ```typescript
     * const { data, errors } = await client.graphql.introspect()
     *
     * if (data) {
     *   console.log('Types:', data.__schema.types.length)
     * }
     * ```
     */
    introspect(options?: GraphQLRequestOptions): Promise<GraphQLResponse<{
        __schema: IntrospectionSchema;
    }>>;
}
/**
 * GraphQL introspection schema type
 */
interface IntrospectionSchema {
    queryType: {
        name: string;
    };
    mutationType?: {
        name: string;
    };
    subscriptionType?: {
        name: string;
    };
    types: IntrospectionType[];
    directives: IntrospectionDirective[];
}
/**
 * GraphQL introspection type
 */
interface IntrospectionType {
    kind: string;
    name: string;
    description?: string;
    fields?: IntrospectionField[];
    inputFields?: IntrospectionInputValue[];
    interfaces?: IntrospectionTypeRef[];
    enumValues?: IntrospectionEnumValue[];
    possibleTypes?: IntrospectionTypeRef[];
}
/**
 * GraphQL introspection field
 */
interface IntrospectionField {
    name: string;
    description?: string;
    args: IntrospectionInputValue[];
    type: IntrospectionTypeRef;
    isDeprecated: boolean;
    deprecationReason?: string;
}
/**
 * GraphQL introspection input value
 */
interface IntrospectionInputValue {
    name: string;
    description?: string;
    type: IntrospectionTypeRef;
    defaultValue?: string;
}
/**
 * GraphQL introspection type reference
 */
interface IntrospectionTypeRef {
    kind: string;
    name?: string;
    ofType?: IntrospectionTypeRef;
}
/**
 * GraphQL introspection enum value
 */
interface IntrospectionEnumValue {
    name: string;
    description?: string;
    isDeprecated: boolean;
    deprecationReason?: string;
}
/**
 * GraphQL introspection directive
 */
interface IntrospectionDirective {
    name: string;
    description?: string;
    locations: string[];
    args: IntrospectionInputValue[];
}

/**
 * Branching module for Fluxbase SDK
 * Provides database branching capabilities for development workflows
 *
 * @example
 * ```typescript
 * // List all branches
 * const { data, error } = await client.branching.list()
 *
 * // Create a new branch for feature development
 * const { data: branch } = await client.branching.create('feature/add-auth', {
 *   dataCloneMode: 'schema_only',
 *   expiresIn: '7d'
 * })
 *
 * // Get branch details
 * const { data: details } = await client.branching.get('feature/add-auth')
 *
 * // Reset branch to parent state
 * await client.branching.reset('feature/add-auth')
 *
 * // Delete branch when done
 * await client.branching.delete('feature/add-auth')
 * ```
 */

/**
 * Branching client for database branch management
 *
 * Database branches allow you to create isolated copies of your database
 * for development, testing, and preview environments.
 *
 * @category Branching
 */
declare class FluxbaseBranching {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all database branches
     *
     * @param options - Filter and pagination options
     * @returns Promise resolving to { data, error } tuple with branches list
     *
     * @example
     * ```typescript
     * // List all branches
     * const { data, error } = await client.branching.list()
     *
     * // Filter by status
     * const { data } = await client.branching.list({ status: 'ready' })
     *
     * // Filter by type
     * const { data } = await client.branching.list({ type: 'preview' })
     *
     * // Only show my branches
     * const { data } = await client.branching.list({ mine: true })
     *
     * // Pagination
     * const { data } = await client.branching.list({ limit: 10, offset: 20 })
     * ```
     */
    list(options?: ListBranchesOptions): Promise<{
        data: ListBranchesResponse | null;
        error: Error | null;
    }>;
    /**
     * Get a specific branch by ID or slug
     *
     * @param idOrSlug - Branch ID (UUID) or slug
     * @returns Promise resolving to { data, error } tuple with branch details
     *
     * @example
     * ```typescript
     * // Get by slug
     * const { data, error } = await client.branching.get('feature/add-auth')
     *
     * // Get by ID
     * const { data } = await client.branching.get('123e4567-e89b-12d3-a456-426614174000')
     * ```
     */
    get(idOrSlug: string): Promise<{
        data: Branch | null;
        error: Error | null;
    }>;
    /**
     * Create a new database branch
     *
     * @param name - Branch name (will be converted to a slug)
     * @param options - Branch creation options
     * @returns Promise resolving to { data, error } tuple with created branch
     *
     * @example
     * ```typescript
     * // Create a simple branch
     * const { data, error } = await client.branching.create('feature/add-auth')
     *
     * // Create with options
     * const { data } = await client.branching.create('feature/add-auth', {
     *   dataCloneMode: 'schema_only',  // Don't clone data
     *   expiresIn: '7d',               // Auto-delete after 7 days
     *   type: 'persistent'             // Won't auto-delete on PR merge
     * })
     *
     * // Create a PR preview branch
     * const { data } = await client.branching.create('pr-123', {
     *   type: 'preview',
     *   githubPRNumber: 123,
     *   githubRepo: 'owner/repo',
     *   expiresIn: '7d'
     * })
     *
     * // Clone with full data (for debugging)
     * const { data } = await client.branching.create('debug-issue-456', {
     *   dataCloneMode: 'full_clone'
     * })
     * ```
     */
    create(name: string, options?: CreateBranchOptions): Promise<{
        data: Branch | null;
        error: Error | null;
    }>;
    /**
     * Delete a database branch
     *
     * This permanently deletes the branch database and all its data.
     * Cannot delete the main branch.
     *
     * @param idOrSlug - Branch ID (UUID) or slug
     * @returns Promise resolving to { error } (null on success)
     *
     * @example
     * ```typescript
     * // Delete a branch
     * const { error } = await client.branching.delete('feature/add-auth')
     *
     * if (error) {
     *   console.error('Failed to delete branch:', error.message)
     * }
     * ```
     */
    delete(idOrSlug: string): Promise<{
        error: Error | null;
    }>;
    /**
     * Reset a branch to its parent state
     *
     * This drops and recreates the branch database, resetting all data
     * to match the parent branch. Cannot reset the main branch.
     *
     * @param idOrSlug - Branch ID (UUID) or slug
     * @returns Promise resolving to { data, error } tuple with reset branch
     *
     * @example
     * ```typescript
     * // Reset a branch
     * const { data, error } = await client.branching.reset('feature/add-auth')
     *
     * if (data) {
     *   console.log('Branch reset, status:', data.status)
     * }
     * ```
     */
    reset(idOrSlug: string): Promise<{
        data: Branch | null;
        error: Error | null;
    }>;
    /**
     * Get activity log for a branch
     *
     * @param idOrSlug - Branch ID (UUID) or slug
     * @param limit - Maximum number of entries to return (default: 50, max: 100)
     * @returns Promise resolving to { data, error } tuple with activity entries
     *
     * @example
     * ```typescript
     * // Get recent activity
     * const { data, error } = await client.branching.getActivity('feature/add-auth')
     *
     * if (data) {
     *   for (const entry of data) {
     *     console.log(`${entry.action}: ${entry.status}`)
     *   }
     * }
     *
     * // Get more entries
     * const { data } = await client.branching.getActivity('feature/add-auth', 100)
     * ```
     */
    getActivity(idOrSlug: string, limit?: number): Promise<{
        data: BranchActivity[] | null;
        error: Error | null;
    }>;
    /**
     * Get connection pool statistics for all branches
     *
     * This is useful for monitoring and debugging branch connections.
     *
     * @returns Promise resolving to { data, error } tuple with pool stats
     *
     * @example
     * ```typescript
     * const { data, error } = await client.branching.getPoolStats()
     *
     * if (data) {
     *   for (const pool of data) {
     *     console.log(`${pool.slug}: ${pool.active_connections} active`)
     *   }
     * }
     * ```
     */
    getPoolStats(): Promise<{
        data: BranchPoolStats[] | null;
        error: Error | null;
    }>;
    /**
     * Check if a branch exists
     *
     * @param idOrSlug - Branch ID (UUID) or slug
     * @returns Promise resolving to true if branch exists, false otherwise
     *
     * @example
     * ```typescript
     * const exists = await client.branching.exists('feature/add-auth')
     *
     * if (!exists) {
     *   await client.branching.create('feature/add-auth')
     * }
     * ```
     */
    exists(idOrSlug: string): Promise<boolean>;
    /**
     * Wait for a branch to be ready
     *
     * Polls the branch status until it reaches 'ready' or an error state.
     *
     * @param idOrSlug - Branch ID (UUID) or slug
     * @param options - Polling options
     * @returns Promise resolving to { data, error } tuple with ready branch
     *
     * @example
     * ```typescript
     * // Create branch and wait for it to be ready
     * const { data: branch } = await client.branching.create('feature/add-auth')
     *
     * const { data: ready, error } = await client.branching.waitForReady(branch!.slug, {
     *   timeout: 60000,     // 60 seconds
     *   pollInterval: 1000  // Check every second
     * })
     *
     * if (ready) {
     *   console.log('Branch is ready!')
     * }
     * ```
     */
    waitForReady(idOrSlug: string, options?: {
        /** Timeout in milliseconds (default: 30000) */
        timeout?: number;
        /** Poll interval in milliseconds (default: 1000) */
        pollInterval?: number;
    }): Promise<{
        data: Branch | null;
        error: Error | null;
    }>;
}

/**
 * FluxbaseTenant - Multi-tenant management module
 *
 * Provides methods for managing tenants and admin assignments.
 * With database-per-tenant architecture, each tenant has its own isolated database.
 */

/**
 * FluxbaseTenant provides multi-tenant management functionality
 *
 * @example
 * ```typescript
 * // List tenants I have access to
 * const { data } = await client.tenant.listMine()
 *
 * // Get tenant details
 * const { data } = await client.tenant.get('tenant-id')
 *
 * // Create a tenant (instance admin only)
 * const { data } = await client.tenant.create({
 *   slug: 'acme-corp',
 *   name: 'Acme Corporation'
 * })
 *
 * // Assign admin to tenant (tenant admin only)
 * await client.tenant.assignAdmin('tenant-id', {
 *   user_id: 'user-id'
 * })
 * ```
 *
 * @category Multi-Tenancy
 */
declare class FluxbaseTenant {
    private fetch;
    constructor(fetch: FluxbaseFetch);
    /**
     * List all tenants (instance admin only)
     *
     * @returns Promise with tenants list or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.list()
     * ```
     */
    list(): Promise<FluxbaseResponse<Tenant[]>>;
    /**
     * List tenants the current user has access to
     *
     * @returns Promise with tenants and user's role in each
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.listMine()
     * // data: [{ id: '...', slug: 'acme', name: 'Acme', my_role: 'tenant_admin', status: 'active' }]
     * ```
     */
    listMine(): Promise<FluxbaseResponse<TenantWithRole[]>>;
    /**
     * Get a tenant by ID
     *
     * @param id - Tenant ID
     * @returns Promise with tenant details or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.get('tenant-id')
     * ```
     */
    get(id: string): Promise<FluxbaseResponse<Tenant>>;
    /**
     * Create a new tenant (instance admin only)
     *
     * This creates a new isolated database for the tenant.
     *
     * @param options - Tenant creation options
     * @returns Promise with created tenant or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.create({
     *   slug: 'acme-corp',
     *   name: 'Acme Corporation',
     *   metadata: { plan: 'enterprise' }
     * })
     * ```
     */
    create(options: CreateTenantOptions): Promise<FluxbaseResponse<Tenant>>;
    /**
     * Update a tenant (tenant admin only)
     *
     * @param id - Tenant ID
     * @param options - Update options
     * @returns Promise with updated tenant or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.update('tenant-id', {
     *   name: 'New Name'
     * })
     * ```
     */
    update(id: string, options: UpdateTenantOptions): Promise<FluxbaseResponse<Tenant>>;
    /**
     * Delete a tenant (instance admin only)
     *
     * This permanently deletes the tenant's database and all its data.
     * Cannot delete the default tenant.
     *
     * @param id - Tenant ID
     * @returns Promise that resolves when deleted
     *
     * @example
     * ```typescript
     * const { error } = await client.tenant.delete('tenant-id')
     * ```
     */
    delete(id: string): Promise<FluxbaseResponse<void>>;
    /**
     * Migrate a tenant database to the latest schema (instance admin only)
     *
     * @param id - Tenant ID
     * @returns Promise with migration status or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.migrate('tenant-id')
     * // data: { status: 'migrated' }
     * ```
     */
    migrate(id: string): Promise<FluxbaseResponse<{
        status: string;
    }>>;
    /**
     * List admins of a tenant
     *
     * @param tenantId - Tenant ID
     * @returns Promise with admin list or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.listAdmins('tenant-id')
     * // data: [{ id: '...', tenant_id: '...', user_id: '...', email: 'admin@example.com' }]
     * ```
     */
    listAdmins(tenantId: string): Promise<FluxbaseResponse<TenantAdminAssignment[]>>;
    /**
     * Assign an admin to a tenant (tenant admin only)
     *
     * @param tenantId - Tenant ID
     * @param options - Admin assignment options
     * @returns Promise with created assignment or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.tenant.assignAdmin('tenant-id', {
     *   user_id: 'user-id'
     * })
     * ```
     */
    assignAdmin(tenantId: string, options: AssignAdminOptions): Promise<FluxbaseResponse<TenantAdminAssignment>>;
    /**
     * Remove an admin from a tenant (tenant admin only)
     *
     * @param tenantId - Tenant ID
     * @param userId - User ID
     * @returns Promise that resolves when removed
     *
     * @example
     * ```typescript
     * const { error } = await client.tenant.removeAdmin('tenant-id', 'user-id')
     * ```
     */
    removeAdmin(tenantId: string, userId: string): Promise<FluxbaseResponse<void>>;
}

/**
 * PostgreSQL query builder for Fluxbase SDK
 * Inspired by Supabase's PostgREST client
 */

declare class QueryBuilder<T = unknown> implements PromiseLike<PostgrestResponse<T>> {
    private fetch;
    private table;
    private schema?;
    private selectQuery;
    private filters;
    private orFilters;
    private andFilters;
    private betweenFilters;
    private orderBys;
    private limitValue?;
    private offsetValue?;
    private singleRow;
    private maybeSingleRow;
    private groupByColumns?;
    private operationType;
    private countType?;
    private headOnly;
    private isCountAggregation;
    private insertData?;
    private updateData?;
    private truncateValue?;
    constructor(fetch: FluxbaseFetch, table: string, schema?: string);
    /**
     * Build the API path for this table, including schema if specified
     */
    private buildTablePath;
    /**
     * Select columns to return
     * @example select('*')
     * @example select('id, name, email')
     * @example select('id, name, posts(title, content)')
     * @example select('*', { count: 'exact' }) // Get exact count
     * @example select('*', { count: 'exact', head: true }) // Get count only (no data)
     */
    select(columns?: string, options?: SelectOptions): this;
    /**
     * Insert a single row or multiple rows
     */
    insert(data: Partial<T> | Array<Partial<T>>): this;
    /**
     * Upsert (insert or update) rows (Supabase-compatible)
     * @param data - Row(s) to upsert
     * @param options - Upsert options (onConflict, ignoreDuplicates, defaultToNull)
     */
    upsert(data: Partial<T> | Array<Partial<T>>, options?: UpsertOptions): Promise<PostgrestResponse<T>>;
    /**
     * Update rows matching the filters
     */
    update(data: Partial<T>): this;
    /**
     * Delete rows matching the filters
     */
    delete(): this;
    /**
     * Equal to
     */
    eq(column: string, value: unknown): this;
    /**
     * Not equal to
     */
    neq(column: string, value: unknown): this;
    /**
     * Greater than
     */
    gt(column: string, value: unknown): this;
    /**
     * Greater than or equal to
     */
    gte(column: string, value: unknown): this;
    /**
     * Less than
     */
    lt(column: string, value: unknown): this;
    /**
     * Less than or equal to
     */
    lte(column: string, value: unknown): this;
    /**
     * Pattern matching (case-sensitive)
     */
    like(column: string, pattern: string): this;
    /**
     * Pattern matching (case-insensitive)
     */
    ilike(column: string, pattern: string): this;
    /**
     * Check if value is null or not null
     */
    is(column: string, value: null | boolean): this;
    /**
     * Check if value is in array
     */
    in(column: string, values: unknown[]): this;
    /**
     * Contains (for arrays and JSONB)
     */
    contains(column: string, value: unknown): this;
    /**
     * Full-text search
     */
    textSearch(column: string, query: string): this;
    /**
     * Negate a filter condition (Supabase-compatible)
     * @example not('status', 'eq', 'deleted')
     * @example not('completed_at', 'is', null)
     */
    not(column: string, operator: FilterOperator, value: unknown): this;
    /**
     * Apply OR logic to filters (Supabase-compatible)
     * @example or('status.eq.active,status.eq.pending')
     * @example or('id.eq.2,name.eq.Han')
     */
    or(filters: string): this;
    /**
     * Apply AND logic to filters (Supabase-compatible)
     * Groups multiple conditions that must all be true
     * @example and('status.eq.active,verified.eq.true')
     * @example and('age.gte.18,age.lte.65')
     */
    and(filters: string): this;
    /**
     * Match multiple columns with exact values (Supabase-compatible)
     * Shorthand for multiple .eq() calls
     * @example match({ id: 1, status: 'active', role: 'admin' })
     */
    match(conditions: Record<string, unknown>): this;
    /**
     * Generic filter method using PostgREST syntax (Supabase-compatible)
     * @example filter('name', 'in', '("Han","Yoda")')
     * @example filter('age', 'gte', '18')
     * @example filter('recorded_at', 'between', ['2024-01-01', '2024-01-10'])
     * @example filter('recorded_at', 'not.between', ['2024-01-01', '2024-01-10'])
     */
    filter(column: string, operator: FilterOperator, value: unknown): this;
    /**
     * Check if column is contained by value (Supabase-compatible)
     * For arrays and JSONB
     * @example containedBy('tags', '["news","update"]')
     */
    containedBy(column: string, value: unknown): this;
    /**
     * Check if arrays have common elements (Supabase-compatible)
     * @example overlaps('tags', '["news","sports"]')
     */
    overlaps(column: string, value: unknown): this;
    /**
     * Filter column value within an inclusive range (BETWEEN)
     * Generates: AND (column >= min AND column <= max)
     *
     * @param column - Column name to filter
     * @param min - Minimum value (inclusive)
     * @param max - Maximum value (inclusive)
     * @example between('recorded_at', '2024-01-01', '2024-01-10')
     * @example between('price', 10, 100)
     */
    between(column: string, min: unknown, max: unknown): this;
    /**
     * Filter column value outside an inclusive range (NOT BETWEEN)
     * Generates: OR (column < min OR column > max)
     * Multiple notBetween calls on the same column AND together
     *
     * @param column - Column name to filter
     * @param min - Minimum value of excluded range
     * @param max - Maximum value of excluded range
     * @example notBetween('recorded_at', '2024-01-01', '2024-01-10')
     * @example notBetween('price', 0, 10) // Excludes items priced 0-10
     */
    notBetween(column: string, min: unknown, max: unknown): this;
    /**
     * Check if geometries intersect (PostGIS ST_Intersects)
     * @param column - Column containing geometry/geography data
     * @param geojson - GeoJSON object to test intersection with
     * @example intersects('location', { type: 'Point', coordinates: [-122.4, 37.8] })
     */
    intersects(column: string, geojson: unknown): this;
    /**
     * Check if geometry A contains geometry B (PostGIS ST_Contains)
     * @param column - Column containing geometry/geography data
     * @param geojson - GeoJSON object to test containment
     * @example contains('region', { type: 'Point', coordinates: [-122.4, 37.8] })
     */
    stContains(column: string, geojson: unknown): this;
    /**
     * Check if geometry A is within geometry B (PostGIS ST_Within)
     * @param column - Column containing geometry/geography data
     * @param geojson - GeoJSON object to test containment within
     * @example within('point', { type: 'Polygon', coordinates: [[...]] })
     */
    within(column: string, geojson: unknown): this;
    /**
     * Check if geometries touch (PostGIS ST_Touches)
     * @param column - Column containing geometry/geography data
     * @param geojson - GeoJSON object to test touching
     * @example touches('boundary', { type: 'LineString', coordinates: [[...]] })
     */
    touches(column: string, geojson: unknown): this;
    /**
     * Check if geometries cross (PostGIS ST_Crosses)
     * @param column - Column containing geometry/geography data
     * @param geojson - GeoJSON object to test crossing
     * @example crosses('road', { type: 'LineString', coordinates: [[...]] })
     */
    crosses(column: string, geojson: unknown): this;
    /**
     * Check if geometries spatially overlap (PostGIS ST_Overlaps)
     * @param column - Column containing geometry/geography data
     * @param geojson - GeoJSON object to test overlap
     * @example stOverlaps('area', { type: 'Polygon', coordinates: [[...]] })
     */
    stOverlaps(column: string, geojson: unknown): this;
    /**
     * Order results
     */
    order(column: string, options?: {
        ascending?: boolean;
        nullsFirst?: boolean;
    }): this;
    /**
     * Order results by vector similarity (pgvector)
     * Results are ordered by distance (ascending = closest first)
     *
     * @example
     * ```typescript
     * // Order by cosine similarity (closest matches first)
     * const { data } = await client
     *   .from('documents')
     *   .select('id, title, content')
     *   .orderByVector('embedding', queryVector, 'cosine')
     *   .limit(10)
     * ```
     *
     * @param column - The vector column to order by
     * @param vector - The query vector to compare against
     * @param metric - Distance metric: 'l2' (euclidean), 'cosine', or 'inner_product'
     * @param options - Optional: { ascending?: boolean } - defaults to true (closest first)
     */
    orderByVector(column: string, vector: number[], metric?: VectorMetric, options?: {
        ascending?: boolean;
    }): this;
    /**
     * Filter by vector similarity (pgvector)
     * This is a convenience method that adds a vector filter using the specified distance metric.
     * Typically used with orderByVector() for similarity search.
     *
     * @example
     * ```typescript
     * // Find the 10 most similar documents
     * const { data } = await client
     *   .from('documents')
     *   .select('id, title, content')
     *   .vectorSearch('embedding', queryVector, 'cosine')
     *   .limit(10)
     *
     * // Combine with other filters
     * const { data } = await client
     *   .from('documents')
     *   .select('id, title, content')
     *   .eq('status', 'published')
     *   .vectorSearch('embedding', queryVector)
     *   .limit(10)
     * ```
     *
     * @param column - The vector column to search
     * @param vector - The query vector
     * @param metric - Distance metric: 'l2' (euclidean), 'cosine', or 'inner_product'
     */
    vectorSearch(column: string, vector: number[], metric?: VectorMetric): this;
    /**
     * Limit number of rows returned
     */
    limit(count: number): this;
    /**
     * Skip rows
     */
    offset(count: number): this;
    /**
     * Truncate text columns to specified length
     * Useful for browsing tables with large text fields
     * @example truncate(500) // Truncate text columns to 500 characters
     */
    truncate(length: number): this;
    /**
     * Return a single row (adds limit(1))
     * Errors if no rows found
     */
    single(): this;
    /**
     * Return a single row or null (adds limit(1))
     * Does not error if no rows found (Supabase-compatible)
     * @example
     * ```typescript
     * // Returns null instead of erroring when no row exists
     * const { data, error } = await client
     *   .from('users')
     *   .select('*')
     *   .eq('id', 999)
     *   .maybeSingle()
     * // data will be null if no row found
     * ```
     */
    maybeSingle(): this;
    /**
     * Range selection (pagination)
     */
    range(from: number, to: number): this;
    /**
     * Group results by one or more columns (for use with aggregations)
     *
     * @param columns - Column name(s) to group by
     * @returns Query builder for chaining
     *
     * @example
     * ```typescript
     * // Group by single column
     * const { data } = await client.from('orders')
     *   .count('*')
     *   .groupBy('status')
     *   .execute()
     *
     * // Group by multiple columns
     * const { data } = await client.from('sales')
     *   .sum('amount')
     *   .groupBy(['region', 'product_category'])
     *   .execute()
     * ```
     *
     * @category Aggregation
     */
    groupBy(columns: string | string[]): this;
    /**
     * Count rows or a specific column
     *
     * @param column - Column to count (default: '*' for row count)
     * @returns Query builder for chaining
     *
     * @example
     * ```typescript
     * // Count all rows
     * const { data } = await client.from('users').count().execute()
     * // Returns: { count: 150 }
     *
     * // Count non-null values in a column
     * const { data } = await client.from('orders').count('completed_at').execute()
     *
     * // Count with grouping
     * const { data } = await client.from('products')
     *   .count('*')
     *   .groupBy('category')
     *   .execute()
     * // Returns: [{ category: 'electronics', count: 45 }, { category: 'books', count: 23 }]
     * ```
     *
     * @category Aggregation
     */
    count(column?: string): this;
    /**
     * Calculate the sum of a numeric column
     *
     * @param column - Column to sum
     * @returns Query builder for chaining
     *
     * @example
     * ```typescript
     * // Sum all prices
     * const { data } = await client.from('products').sum('price').execute()
     * // Returns: { sum_price: 15420.50 }
     *
     * // Sum by category
     * const { data } = await client.from('orders')
     *   .sum('total')
     *   .groupBy('status')
     *   .execute()
     * // Returns: [{ status: 'completed', sum_total: 12500 }, { status: 'pending', sum_total: 3200 }]
     * ```
     *
     * @category Aggregation
     */
    sum(column: string): this;
    /**
     * Calculate the average of a numeric column
     *
     * @param column - Column to average
     * @returns Query builder for chaining
     *
     * @example
     * ```typescript
     * // Average price
     * const { data } = await client.from('products').avg('price').execute()
     * // Returns: { avg_price: 129.99 }
     *
     * // Average by category
     * const { data } = await client.from('products')
     *   .avg('price')
     *   .groupBy('category')
     *   .execute()
     * ```
     *
     * @category Aggregation
     */
    avg(column: string): this;
    /**
     * Find the minimum value in a column
     *
     * @param column - Column to find minimum value
     * @returns Query builder for chaining
     *
     * @example
     * ```typescript
     * // Find lowest price
     * const { data } = await client.from('products').min('price').execute()
     * // Returns: { min_price: 9.99 }
     *
     * // Find earliest date
     * const { data } = await client.from('orders').min('created_at').execute()
     * ```
     *
     * @category Aggregation
     */
    min(column: string): this;
    /**
     * Find the maximum value in a column
     *
     * @param column - Column to find maximum value
     * @returns Query builder for chaining
     *
     * @example
     * ```typescript
     * // Find highest price
     * const { data } = await client.from('products').max('price').execute()
     * // Returns: { max_price: 1999.99 }
     *
     * // Find most recent order
     * const { data } = await client.from('orders').max('created_at').execute()
     * ```
     *
     * @category Aggregation
     */
    max(column: string): this;
    /**
     * Insert multiple rows in a single request (batch insert)
     *
     * This is a convenience method that explicitly shows intent for batch operations.
     * Internally calls `insert()` with an array.
     *
     * @param rows - Array of row objects to insert
     * @returns Promise with the inserted rows
     *
     * @example
     * ```typescript
     * // Insert multiple users at once
     * const { data } = await client.from('users').insertMany([
     *   { name: 'Alice', email: 'alice@example.com' },
     *   { name: 'Bob', email: 'bob@example.com' },
     *   { name: 'Charlie', email: 'charlie@example.com' }
     * ])
     * ```
     *
     * @category Batch Operations
     */
    insertMany(rows: Array<Partial<T>>): Promise<PostgrestResponse<T>>;
    /**
     * Update multiple rows matching the filters (batch update)
     *
     * Updates all rows that match the current query filters.
     * This is a convenience method that explicitly shows intent for batch operations.
     *
     * @param data - Data to update matching rows with
     * @returns Promise with the updated rows
     *
     * @example
     * ```typescript
     * // Apply discount to all electronics
     * const { data } = await client.from('products')
     *   .eq('category', 'electronics')
     *   .updateMany({ discount: 10, updated_at: new Date() })
     *
     * // Mark all pending orders as processing
     * const { data } = await client.from('orders')
     *   .eq('status', 'pending')
     *   .updateMany({ status: 'processing' })
     * ```
     *
     * @category Batch Operations
     */
    updateMany(data: Partial<T>): Promise<PostgrestResponse<T>>;
    /**
     * Delete multiple rows matching the filters (batch delete)
     *
     * Deletes all rows that match the current query filters.
     * This is a convenience method that explicitly shows intent for batch operations.
     *
     * @returns Promise confirming deletion
     *
     * @example
     * ```typescript
     * // Delete all inactive users
     * await client.from('users')
     *   .eq('active', false)
     *   .deleteMany()
     *
     * // Delete old logs
     * await client.from('logs')
     *   .lt('created_at', '2024-01-01')
     *   .deleteMany()
     * ```
     *
     * @category Batch Operations
     */
    deleteMany(): Promise<PostgrestResponse<null>>;
    /**
     * Execute the query and return results
     */
    execute(): Promise<PostgrestResponse<T>>;
    /**
     * Execute the query and throw an error if one occurs (Supabase-compatible)
     * Returns the data directly instead of { data, error } wrapper
     *
     * @throws {Error} If the query fails or returns an error
     * @example
     * ```typescript
     * // Throws error instead of returning { data, error }
     * try {
     *   const user = await client
     *     .from('users')
     *     .select('*')
     *     .eq('id', 1)
     *     .single()
     *     .throwOnError()
     * } catch (error) {
     *   console.error('Query failed:', error)
     * }
     * ```
     */
    throwOnError(): Promise<T>;
    /**
     * Make QueryBuilder awaitable (implements PromiseLike)
     * This allows using `await client.from('table').select()` without calling `.execute()`
     *
     * @example
     * ```typescript
     * // Without .execute() (new way)
     * const { data } = await client.from('users').select('*')
     *
     * // With .execute() (old way, still supported)
     * const { data } = await client.from('users').select('*').execute()
     * ```
     */
    then<TResult1 = PostgrestResponse<T>, TResult2 = never>(onfulfilled?: ((value: PostgrestResponse<T>) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null): PromiseLike<TResult1 | TResult2>;
    /**
     * Build the query string from filters, ordering, etc.
     */
    private buildQueryString;
    /**
     * Format a value for the query string
     */
    private formatValue;
    /**
     * Validate between filter value - must be array of exactly 2 elements
     * @throws Error if value is invalid
     */
    private validateBetweenValue;
    /**
     * Parse the Content-Range header to extract the total count
     * Header format: "0-999/50000" or "* /50000" (when no rows returned)
     */
    private parseContentRangeCount;
    /**
     * Check if the query should use POST-based query endpoint
     * Returns true if the query string would exceed the URL length threshold
     */
    private shouldUsePostQuery;
    /**
     * Execute a SELECT query using the POST /query endpoint
     * Used when query parameters would exceed URL length limits
     */
    private executePostQuery;
    /**
     * Build the request body for POST-based queries
     * Used when query parameters would exceed URL length limits
     */
    private buildQueryBody;
}

/**
 * Schema-scoped query builder for accessing tables in non-public schemas.
 *
 * @example
 * ```typescript
 * // Query the logging.entries table
 * const { data } = await client
 *   .schema('logging')
 *   .from('entries')
 *   .select('*')
 *   .execute();
 * ```
 */

declare class SchemaQueryBuilder {
    private fetch;
    private schemaName;
    constructor(fetch: FluxbaseFetch, schemaName: string);
    /**
     * Create a query builder for a table in this schema
     *
     * @param table - The table name (without schema prefix)
     * @returns A query builder instance for constructing and executing queries
     */
    from<T = unknown>(table: string): QueryBuilder<T>;
}

/**
 * Callable RPC type - can be called directly (Supabase-compatible) or access methods
 * @category RPC
 */
type CallableRPC = {
    /**
     * Call a PostgreSQL function (RPC) - Supabase compatible
     * Uses 'default' namespace
     *
     * @param fn - Function name
     * @param params - Function parameters
     * @returns Promise with data or error
     *
     * @example
     * ```typescript
     * const { data, error } = await client.rpc('get_user_orders', { user_id: '123' })
     * ```
     */
    <T = unknown>(fn: string, params?: Record<string, unknown>): Promise<{
        data: T | null;
        error: Error | null;
    }>;
} & FluxbaseRPC;
/**
 * Main Fluxbase client class
 * @category Client
 */
declare class FluxbaseClient<Database = unknown, _SchemaName extends string & keyof Database = string & keyof Database> {
    protected fluxbaseUrl: string;
    protected fluxbaseKey: string;
    /** Internal HTTP client for making requests */
    private fetch;
    /** Client options */
    private options?;
    /** Authentication module for user management */
    auth: FluxbaseAuth;
    /** Realtime module for WebSocket subscriptions */
    realtime: FluxbaseRealtime;
    /** Storage module for file operations */
    storage: FluxbaseStorage;
    /** Functions module for invoking and managing edge functions */
    functions: FluxbaseFunctions;
    /** Jobs module for submitting and monitoring background jobs */
    jobs: FluxbaseJobs;
    /** Admin module for instance management (requires admin authentication) */
    admin: FluxbaseAdmin;
    /** Management module for client keys, webhooks, and invitations */
    management: FluxbaseManagement;
    /** Settings module for reading public application settings (respects RLS policies) */
    settings: SettingsClient;
    /** Secrets module for managing edge function and job secrets */
    secrets: SecretsManager;
    /** AI module for chatbots and conversation history */
    ai: FluxbaseAI;
    /** Knowledge Base module for RAG document management and search */
    knowledgeBase: FluxbaseKnowledgeBase;
    /**
     * Vector search module for pgvector similarity search
     *
     * Provides convenience methods for vector similarity search:
     * - `embed()` - Generate embeddings from text
     * - `search()` - Search for similar vectors with auto-embedding
     *
     * @example
     * ```typescript
     * // Search with automatic embedding
     * const { data } = await client.vector.search({
     *   table: 'documents',
     *   column: 'embedding',
     *   query: 'How to use TypeScript?',
     *   match_count: 10
     * })
     *
     * // Generate embeddings
     * const { data } = await client.vector.embed({ text: 'Hello world' })
     * ```
     *
     * Note: For more control, use the QueryBuilder methods:
     * - `vectorSearch()` - Filter and order by vector similarity
     * - `orderByVector()` - Order results by vector distance
     *
     * @category Vector Search
     */
    vector: FluxbaseVector;
    /**
     * GraphQL module for executing queries and mutations
     *
     * Provides a type-safe interface for the auto-generated GraphQL schema
     * from your database tables.
     *
     * @example
     * ```typescript
     * // Execute a query
     * const { data, errors } = await client.graphql.query(`
     *   query GetUsers($limit: Int) {
     *     users(limit: $limit) {
     *       id
     *       email
     *     }
     *   }
     * `, { limit: 10 })
     *
     * // Execute a mutation
     * const { data, errors } = await client.graphql.mutation(`
     *   mutation CreateUser($data: UserInput!) {
     *     insertUser(data: $data) {
     *       id
     *       email
     *     }
     *   }
     * `, { data: { email: 'user@example.com' } })
     * ```
     *
     * @category GraphQL
     */
    graphql: FluxbaseGraphQL;
    /**
     * Branching module for database branch management
     *
     * Database branches allow you to create isolated copies of your database
     * for development, testing, and preview environments.
     *
     * @example
     * ```typescript
     * // List all branches
     * const { data } = await client.branching.list()
     *
     * // Create a feature branch
     * const { data: branch } = await client.branching.create('feature/add-auth', {
     *   dataCloneMode: 'schema_only',
     *   expiresIn: '7d'
     * })
     *
     * // Reset branch to parent state
     * await client.branching.reset('feature/add-auth')
     *
     * // Delete when done
     * await client.branching.delete('feature/add-auth')
     * ```
     *
     * @category Branching
     */
    branching: FluxbaseBranching;
    /**
     * RPC module for calling PostgreSQL functions - Supabase compatible
     *
     * Can be called directly (Supabase-style) or access methods like invoke(), list(), getStatus()
     *
     * @example
     * ```typescript
     * // Supabase-style direct call (uses 'default' namespace)
     * const { data, error } = await client.rpc('get_user_orders', { user_id: '123' })
     *
     * // With full options
     * const { data, error } = await client.rpc.invoke('get_user_orders', { user_id: '123' }, {
     *   namespace: 'custom',
     *   async: true
     * })
     *
     * // List available procedures
     * const { data: procedures } = await client.rpc.list()
     * ```
     *
     * @category RPC
     */
    rpc: CallableRPC;
    /**
     * Tenant management module for multi-tenant operations
     *
     * @example
     * ```typescript
     * // List tenants I have access to
     * const { data } = await client.tenant.listMine()
     *
     * // Create a new tenant (instance admin only)
     * const { data } = await client.tenant.create({
     *   slug: 'acme-corp',
     *   name: 'Acme Corporation'
     * })
     *
     * // Get tenant details
     * const { data } = await client.tenant.get('tenant-id')
     *
     * // Add a member to a tenant (tenant admin only)
     * await client.tenant.addMember('tenant-id', {
     *   user_id: 'user-id',
     *   role: 'tenant_member'
     * })
     * ```
     *
     * @category Multi-Tenancy
     */
    tenant: FluxbaseTenant;
    /** Current tenant ID (from X-FB-Tenant header or JWT claim) */
    private _tenantId?;
    /**
     * Create a new Fluxbase client instance
     *
     * @param fluxbaseUrl - The URL of your Fluxbase instance
     * @param fluxbaseKey - The anon key (JWT token with "anon" role). Generate using scripts/generate-keys.sh
     * @param options - Additional client configuration options
     *
     * @example
     * ```typescript
     * const client = new FluxbaseClient(
     *   'http://localhost:8080',
     *   'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',  // Anon JWT token
     *   { timeout: 30000 }
     * )
     * ```
     */
    constructor(fluxbaseUrl: string, fluxbaseKey: string, options?: FluxbaseClientOptions);
    /**
     * Create a query builder for a database table
     *
     * @param table - The table name (can include schema, e.g., 'public.users')
     * @returns A query builder instance for constructing and executing queries
     *
     * @example
     * ```typescript
     * // Simple select
     * const { data } = await client.from('users').select('*').execute()
     *
     * // With filters
     * const { data } = await client.from('products')
     *   .select('id, name, price')
     *   .gt('price', 100)
     *   .eq('category', 'electronics')
     *   .execute()
     *
     * // Insert
     * await client.from('users').insert({ name: 'John', email: 'john@example.com' }).execute()
     * ```
     *
     * @category Database
     */
    from<T = unknown>(table: string): QueryBuilder<T>;
    /**
     * Access a specific database schema
     *
     * Use this to query tables in non-public schemas.
     *
     * @param schemaName - The schema name (e.g., 'jobs', 'analytics')
     * @returns A schema query builder for constructing queries on that schema
     *
     * @example
     * ```typescript
     * // Query the logging.entries table
     * const { data } = await client
     *   .schema('logging')
     *   .from('entries')
     *   .select('*')
     *   .eq('execution_id', executionId)
     *   .execute()
     *
     * // Insert into a custom schema table
     * await client
     *   .schema('analytics')
     *   .from('events')
     *   .insert({ event_type: 'click', data: {} })
     *   .execute()
     * ```
     *
     * @category Database
     */
    schema(schemaName: string): SchemaQueryBuilder;
    /**
     * Sync auth state with realtime connections
     * @internal
     */
    private setupAuthSync;
    /**
     * Get the current authentication token
     *
     * @returns The current JWT access token, or null if not authenticated
     *
     * @category Authentication
     */
    getAuthToken(): string | null;
    /**
     * Set a new authentication token
     *
     * This updates both the HTTP client and realtime connection with the new token.
     *
     * @param token - The JWT access token to set, or null to clear authentication
     *
     * @category Authentication
     */
    setAuthToken(token: string | null): void;
    /**
     * Get the current tenant ID
     *
     * Returns the tenant ID from X-FB-Tenant header or JWT claim, or default tenant.
     *
     * @returns The current tenant ID, or undefined if not set
     *
     * @category Multi-Tenancy
     */
    getTenantId(): string | undefined;
    /**
     * Set the tenant context for all subsequent requests
     *
     * This adds the X-FB-Tenant header to all HTTP requests and updates
     * the realtime connection to filter by tenant.
     *
     * @param tenantId - The tenant ID to use for scoping
     *
     * @example
     * ```typescript
     * // Switch to a specific tenant
     * client.setTenant('tenant-uuid-here')
     *
     * // All subsequent requests will be scoped to this tenant
     * const { data } = await client.from('users').select('*').execute()
     * ```
     *
     * @category Multi-Tenancy
     */
    setTenant(tenantId: string | undefined): void;
    /**
     * Register a callback that is called before every request.
     * The callback receives the headers object and can modify it in place.
     * This is useful for dynamically injecting headers at request time
     * (e.g., reading tenant context from an external store).
     *
     * The callback runs after static headers are merged, so it can override them.
     *
     * @param callback - A function that receives the headers object, or null to remove
     *
     * @category Advanced
     */
    setBeforeRequestCallback(callback: ((headers: Record<string, string>) => void) | null): void;
    /**
     * Create a new client scoped to a specific tenant
     *
     * This returns a new client instance with the tenant context set.
     * The original client is not modified.
     *
     * @param tenantId - The tenant ID to scope to
     * @returns A new FluxbaseClient instance scoped to the tenant
     *
     * @example
     * ```typescript
     * // Create a tenant-scoped client
     * const tenantClient = client.forTenant('tenant-uuid')
     *
     * // Use the scoped client for tenant-specific operations
     * const { data } = await tenantClient.from('users').select('*').execute()
     * ```
     *
     * @category Multi-Tenancy
     */
    forTenant(tenantId: string): FluxbaseClient<Database, _SchemaName>;
    /**
     * Create or get a realtime channel (Supabase-compatible)
     *
     * @param name - Channel name
     * @param config - Optional channel configuration
     * @returns RealtimeChannel instance
     *
     * @example
     * ```typescript
     * const channel = client.channel('room-1', {
     *   broadcast: { self: true },
     *   presence: { key: 'user-123' }
     * })
     *   .on('broadcast', { event: 'message' }, (payload) => {
     *     console.log('Message:', payload)
     *   })
     *   .subscribe()
     * ```
     *
     * @category Realtime
     */
    channel(name: string, config?: RealtimeChannelConfig): RealtimeChannel;
    /**
     * Remove a realtime channel (Supabase-compatible)
     *
     * @param channel - The channel to remove
     * @returns Promise resolving to status
     *
     * @example
     * ```typescript
     * const channel = client.channel('room-1')
     * await client.removeChannel(channel)
     * ```
     *
     * @category Realtime
     */
    removeChannel(channel: RealtimeChannel): Promise<"error" | "ok">;
    /**
     * Get the internal HTTP client
     *
     * Use this for advanced scenarios like making custom API calls or admin operations.
     *
     * @returns The internal FluxbaseFetch instance
     *
     * @example
     * ```typescript
     * // Make a custom API call
     * const data = await client.http.get('/api/custom-endpoint')
     * ```
     *
     * @category Advanced
     */
    get http(): FluxbaseFetch;
}
/**
 * Create a new Fluxbase client instance (Supabase-compatible)
 *
 * This function signature is identical to Supabase's createClient, making migration seamless.
 *
 * When called without arguments (or with undefined values), the function will attempt to
 * read from environment variables:
 * - `FLUXBASE_URL` - The URL of your Fluxbase instance
 * - `FLUXBASE_ANON_KEY` or `FLUXBASE_JOB_TOKEN` or `FLUXBASE_SERVICE_TOKEN` - The API key/token
 *
 * This is useful in:
 * - Server-side environments where env vars are set
 * - Fluxbase job functions where tokens are automatically provided
 * - Edge functions with configured environment
 *
 * @param fluxbaseUrl - The URL of your Fluxbase instance (optional if FLUXBASE_URL env var is set)
 * @param fluxbaseKey - The anon key or JWT token (optional if env var is set)
 * @param options - Optional client configuration
 * @returns A configured Fluxbase client instance with full TypeScript support
 *
 * @example
 * ```typescript
 * import { createClient } from '@nimbleflux/fluxbase-sdk'
 *
 * // Initialize with anon key (identical to Supabase)
 * const client = createClient(
 *   'http://localhost:8080',
 *   'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'  // Anon JWT token
 * )
 *
 * // With additional options
 * const client = createClient(
 *   'http://localhost:8080',
 *   'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
 *   { timeout: 30000, debug: true }
 * )
 *
 * // In a Fluxbase job function (reads from env vars automatically)
 * const client = createClient()
 *
 * // With TypeScript database types
 * const client = createClient<Database>(
 *   'http://localhost:8080',
 *   'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
 * )
 * ```
 *
 * @category Client
 */
declare function createClient<Database = unknown, SchemaName extends string & keyof Database = string & keyof Database>(fluxbaseUrl?: string, fluxbaseKey?: string, options?: FluxbaseClientOptions): FluxbaseClient<Database, SchemaName>;

/**
 * Type guard utilities for Fluxbase SDK
 * Provides runtime type checking and type narrowing for response types
 */

/**
 * Type guard to check if a FluxbaseResponse is an error response
 *
 * @param response - The response to check
 * @returns true if the response is an error (data is null, error is not null)
 *
 * @example
 * ```typescript
 * const result = await client.auth.signIn(credentials)
 *
 * if (isFluxbaseError(result)) {
 *   // TypeScript knows: result.error is Error, result.data is null
 *   console.error('Sign in failed:', result.error.message)
 *   return
 * }
 *
 * // TypeScript knows: result.data is T, result.error is null
 * console.log('Signed in as:', result.data.user.email)
 * ```
 */
declare function isFluxbaseError<T>(response: FluxbaseResponse<T>): response is {
    data: null;
    error: Error;
};
/**
 * Type guard to check if a FluxbaseResponse is a success response
 *
 * @param response - The response to check
 * @returns true if the response is successful (data is not null, error is null)
 *
 * @example
 * ```typescript
 * const result = await client.from('users').select('*').execute()
 *
 * if (isFluxbaseSuccess(result)) {
 *   // TypeScript knows: result.data is T, result.error is null
 *   result.data.forEach(user => console.log(user.name))
 * }
 * ```
 */
declare function isFluxbaseSuccess<T>(response: FluxbaseResponse<T>): response is {
    data: T;
    error: null;
};
/**
 * Type guard to check if an auth response is an error
 *
 * @param response - The auth response to check
 * @returns true if the auth operation failed
 *
 * @example
 * ```typescript
 * const result = await client.auth.signUp(credentials)
 *
 * if (isAuthError(result)) {
 *   console.error('Sign up failed:', result.error.message)
 *   return
 * }
 *
 * // TypeScript knows result.data contains user and session
 * console.log('Welcome,', result.data.user.email)
 * ```
 */
declare function isAuthError(response: FluxbaseAuthResponse): response is {
    data: null;
    error: Error;
};
/**
 * Type guard to check if an auth response is successful
 *
 * @param response - The auth response to check
 * @returns true if the auth operation succeeded
 */
declare function isAuthSuccess(response: FluxbaseAuthResponse): response is {
    data: AuthResponseData;
    error: null;
};
/**
 * Type guard to check if a PostgrestResponse has an error
 *
 * @param response - The Postgrest response to check
 * @returns true if the response contains an error
 *
 * @example
 * ```typescript
 * const response = await client.from('products').select('*').execute()
 *
 * if (hasPostgrestError(response)) {
 *   // TypeScript knows: response.error is PostgrestError
 *   console.error('Query failed:', response.error.message)
 *   if (response.error.hint) {
 *     console.log('Hint:', response.error.hint)
 *   }
 *   return
 * }
 *
 * // TypeScript knows: response.data is T (not null)
 * console.log('Found', response.data.length, 'products')
 * ```
 */
declare function hasPostgrestError<T>(response: PostgrestResponse<T>): response is PostgrestResponse<T> & {
    error: PostgrestError;
    data: null;
};
/**
 * Type guard to check if a PostgrestResponse is successful (has data)
 *
 * @param response - The Postgrest response to check
 * @returns true if the response has data and no error
 */
declare function isPostgrestSuccess<T>(response: PostgrestResponse<T>): response is PostgrestResponse<T> & {
    data: T;
    error: null;
};
/**
 * Type guard to check if a value is a non-null object
 * Useful for narrowing unknown types from API responses
 *
 * @param value - The value to check
 * @returns true if value is a non-null object
 */
declare function isObject(value: unknown): value is Record<string, unknown>;
/**
 * Type guard to check if a value is an array
 * Useful for narrowing unknown types from API responses
 *
 * @param value - The value to check
 * @returns true if value is an array
 */
declare function isArray(value: unknown): value is unknown[];
/**
 * Type guard to check if a value is a string
 *
 * @param value - The value to check
 * @returns true if value is a string
 */
declare function isString(value: unknown): value is string;
/**
 * Type guard to check if a value is a number
 *
 * @param value - The value to check
 * @returns true if value is a number (excludes NaN)
 */
declare function isNumber(value: unknown): value is number;
/**
 * Type guard to check if a value is a boolean
 *
 * @param value - The value to check
 * @returns true if value is a boolean
 */
declare function isBoolean(value: unknown): value is boolean;
/**
 * Assert that a value is of type T, throwing if validation fails
 *
 * @param value - The value to assert
 * @param validator - A type guard function to validate the value
 * @param errorMessage - Optional custom error message
 * @throws Error if validation fails
 *
 * @example
 * ```typescript
 * const response = await client.functions.invoke('get-user')
 * assertType(response.data, isObject, 'Expected user object')
 * // Now response.data is typed as Record<string, unknown>
 * ```
 */
declare function assertType<T>(value: unknown, validator: (v: unknown) => v is T, errorMessage?: string): asserts value is T;

export { type AIChatClientMessage, type AIChatEvent, type AIChatEventType, type AIChatMessageRole, type AIChatOptions, type AIChatServerMessage, type AIChatbot, type AIChatbotLookupResponse, type AIChatbotSummary, type AIConversation, type AIConversationMessage, type AIDailyQuotaSnapshot, type Entity as AIEntity, type EntityRelationship as AIEntityRelationship, type EntityType as AIEntityType, type AIMatchedIntentRule, type AIProvider, type AIProviderType, type AIQuota, type AIUsageStats, type AIUserConversationDetail, type AIUserConversationSummary, type AIUserMessage, type AIUserQueryResult, type AIUserUsageStats, type APIKey, APIKeysManager, type AcceptInvitationRequest, type AcceptInvitationResponse, type AddDocumentRequest, type AddDocumentResponse, type AdminAuthResponse, type AdminBucket, type AdminListBucketsResponse, type AdminListObjectsResponse, type AdminLoginRequest, type AdminMeResponse, type AdminRefreshRequest, type AdminRefreshResponse, type AdminSetupRequest, type AdminSetupStatusResponse, type AdminStorageObject, type AdminUser, type AppSettings, AppSettingsManager, type ApplyMigrationRequest, type ApplyPendingRequest, type AssignAdminOptions, type AuthConfig, type AuthResponse, type AuthResponseData, type AuthSession, type AuthSettings, AuthSettingsManager, type AuthenticationSettings, type BroadcastCallback, type BroadcastMessage, type BundleOptions, type BundleResult, type CaptchaConfig, type CaptchaProvider, type ChatbotKnowledgeBaseLink, type ChatbotSpec, type ChunkedUploadSession, type ClientKey, ClientKeysManager, type Column, type CreateAIProviderRequest, type CreateAPIKeyRequest, type CreateAPIKeyResponse, type CreateClientKeyRequest, type CreateClientKeyResponse, type CreateColumnRequest, type CreateFunctionRequest, type CreateInvitationRequest, type CreateInvitationResponse, type CreateKnowledgeBaseRequest, type CreateMigrationRequest, type CreateOAuthProviderRequest, type CreateOAuthProviderResponse, type CreateSchemaRequest, type CreateSchemaResponse, type CreateSecretRequest, type CreateServiceKeyRequest, type CreateTableRequest, type CreateTableResponse, type CreateTenantOptions, type CreateUserSettingRequest, type CreateWebhookRequest, DDLManager, type DataResponse, type DeleteAPIKeyResponse, type DeleteClientKeyResponse, type DeleteDocumentsByFilterRequest, type DeleteDocumentsByFilterResponse, type DeleteOAuthProviderResponse, type DeleteTableResponse, type DeleteUserResponse, type DeleteWebhookResponse, type DeprecateServiceKeyRequest, type DocumentStatus, type DownloadOptions, type DownloadProgress, type EdgeFunction, type EdgeFunctionExecution, type EmailProviderSettings, type EmailSettingOverride, type EmailSettings, EmailSettingsManager, type EmailTemplate, EmailTemplateManager, type EmailTemplateType, type EmbedRequest, type EmbedResponse, type EnableRealtimeRequest, type EnableRealtimeResponse, type EnrichedUser, type ExecutionLog, type ExecutionLogCallback, type ExecutionLogConfig, type ExecutionLogEvent, type ExecutionLogLevel, ExecutionLogsChannel, type ExecutionType, type FeatureSettings, type FileObject, type FilterOperator, FluxbaseAI, FluxbaseAIChat, FluxbaseAdmin, FluxbaseAdminAI, FluxbaseAdminFunctions, FluxbaseAdminJobs, FluxbaseAdminMigrations, FluxbaseAdminRPC, FluxbaseAdminRealtime, FluxbaseAdminStorage, FluxbaseAuth, type FluxbaseAuthResponse, FluxbaseBranching, FluxbaseClient, type FluxbaseClientOptions, type FluxbaseError, FluxbaseFetch, FluxbaseFunctions, FluxbaseGraphQL, FluxbaseJobs, FluxbaseKnowledgeBase, FluxbaseManagement, FluxbaseOAuth, FluxbaseRPC, FluxbaseRealtime, type FluxbaseResponse, FluxbaseSettings, FluxbaseStorage, FluxbaseTenant, FluxbaseVector, type FunctionInvokeOptions, type FunctionSpec, type GetImpersonationResponse, type GraphQLError, type GraphQLErrorLocation, type GraphQLRequestOptions, type GraphQLResponse, type HealthResponse, type HttpMethod, type ImageFitMode, type ImageFormat, type ImpersonateAnonRequest, type ImpersonateServiceRequest, type ImpersonateUserRequest, ImpersonationManager, type ImpersonationSession, type ImpersonationTargetUser, type ImpersonationType, type IntrospectionDirective, type IntrospectionEnumValue, type IntrospectionField, type IntrospectionInputValue, type IntrospectionSchema, type IntrospectionType, type IntrospectionTypeRef, type Invitation, InvitationsManager, type InviteUserRequest, type InviteUserResponse, type KnowledgeBase, type KnowledgeBaseDocument, type KnowledgeBaseSearchResult, type KnowledgeBaseSummary, type KnowledgeGraphData, type LinkKnowledgeBaseRequest, type ListAPIKeysResponse, type ListClientKeysResponse, type ListConversationsOptions, type ListConversationsResult, type ListEmailTemplatesResponse, type ListImpersonationSessionsOptions, type ListImpersonationSessionsResponse, type ListInvitationsOptions, type ListInvitationsResponse, type ListOAuthProvidersResponse, type ListOptions, type ListRealtimeTablesResponse, type ListSchemasResponse, type ListSecretsOptions, type ListSystemSettingsResponse, type ListTablesResponse, type ListUsersOptions, type ListUsersResponse, type ListWebhookDeliveriesResponse, type ListWebhooksResponse, type MailgunSettings, type Migration, type MigrationExecution, type OAuthLogoutOptions, type OAuthLogoutResponse, type OAuthProvider, type OAuthProviderInfo, OAuthProviderManager, type OAuthProviderPublic, type OrderBy, type OrderDirection, type PostgresChangesConfig, type PostgrestError, type PostgrestResponse, type PresenceCallback, type PresenceState, type ProviderTokenNotFoundError, type ProviderTokenResponse, QueryBuilder, type QueryFilter, type RPCExecution, type RPCExecutionFilters, type RPCExecutionLog, type RPCExecutionStatus, type RPCInvokeResponse, type RPCProcedure, type RPCProcedureSpec, type RPCProcedureSummary, type RealtimeBroadcastPayload, type RealtimeCallback, type RealtimeChangePayload, RealtimeChannel, type RealtimeChannelConfig, type RealtimeMessage, type RealtimePostgresChangesPayload, type RealtimePresencePayload, type RealtimeTableStatus, type RequestOptions, type ResetUserPasswordResponse, type ResumableDownloadData, type ResumableDownloadOptions, type ResumableUploadOptions, type ResumableUploadProgress, type RevokeAPIKeyResponse, type RevokeClientKeyResponse, type RevokeInvitationResponse, type RevokeServiceKeyRequest, type RollbackMigrationRequest, type SAMLLoginOptions, type SAMLLoginResponse, type SAMLProvider, type SAMLProvidersResponse, type SAMLSession, type SESSettings, type SMTPSettings, type Schema, SchemaQueryBuilder, type SearchKnowledgeBaseRequest, type SearchKnowledgeBaseResponse, type Secret, type SecretByNameOptions, type SecretStats, type SecretSummary, type SecretVersion, SecretsManager, type SecuritySettings, type SendGridSettings, type ServiceKey, type ServiceKeyWithKey, ServiceKeysManager, type SessionResponse, SettingsClient, type SignInCredentials, type SignInWith2FAResponse, type SignUpCredentials, type SignedUrlOptions, type StartImpersonationResponse, type StopImpersonationResponse, StorageBucket, type StorageObject, type StreamDownloadData, type StreamUploadOptions, type SyncChatbotsOptions, type SyncChatbotsResult, type SyncError, type SyncFunctionsOptions, type SyncFunctionsResult, type SyncMigrationsOptions, type SyncMigrationsResult, type SyncRPCOptions, type SyncRPCResult, type SystemSetting, SystemSettingsManager, type Table, type TableColumn, type TableDetails, type TableForeignKey, type TableIndex, type Tenant, type TenantAdminAssignment, type TenantAdminWithUser, type TenantEmailProviderSettings, type TenantStatus, type TenantWithRole, type TestEmailSettingsResponse, type TestEmailTemplateRequest, type TestWebhookResponse, type TransformOptions, type TwoFactorEnableResponse, type TwoFactorSetupResponse, type TwoFactorStatusResponse, type TwoFactorVerifyRequest, type UpdateAIProviderRequest, type UpdateAPIKeyRequest, type UpdateAppSettingsRequest, type UpdateAuthSettingsRequest, type UpdateAuthSettingsResponse, type UpdateChatbotKnowledgeBaseRequest, type UpdateClientKeyRequest, type UpdateConversationOptions, type UpdateDocumentRequest, type UpdateEmailProviderSettingsRequest, type UpdateEmailTemplateRequest, type UpdateFunctionRequest, type UpdateKnowledgeBaseRequest, type UpdateMigrationRequest, type UpdateOAuthProviderRequest, type UpdateOAuthProviderResponse, type UpdateRPCProcedureRequest, type UpdateRealtimeConfigRequest, type UpdateSecretRequest, type UpdateServiceKeyRequest, type UpdateSystemSettingRequest, type UpdateTenantOptions, type UpdateUserAttributes, type UpdateUserRoleRequest, type UpdateWebhookRequest, type UploadDocumentResponse, type UploadOptions, type UploadProgress, type UpsertOptions, type User, type UserResponse, type UserSetting, type UserSettingWithSource, type ValidateInvitationResponse, type VectorMetric, type VectorOrderOptions, type VectorSearchOptions, type VectorSearchResult, type VoidResponse, type WeakPassword, type Webhook, type WebhookDelivery, WebhooksManager, assertType, bundleCode, createClient, denoExternalPlugin, hasPostgrestError, isArray, isAuthError, isAuthSuccess, isBoolean, isFluxbaseError, isFluxbaseSuccess, isNumber, isObject, isPostgrestSuccess, isString, loadImportMap };
