UNPKG

@fluxbase/sdk

Version:

Official TypeScript SDK for Fluxbase - Backend as a Service

1,893 lines (1,882 loc) 94.8 kB
/** * Core types for the Fluxbase SDK */ interface FluxbaseClientOptions { /** * Base URL of your Fluxbase instance * @example 'https://api.myapp.com' * @example 'http://localhost:8080' */ url: string; /** * 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; }; /** * 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; } interface SignUpCredentials { email: string; password: string; metadata?: Record<string, unknown>; } interface AuthResponse { user: User; access_token: string; refresh_token: string; expires_in: number; } interface TwoFactorSetupResponse { secret: string; qr_code_url: string; message: string; } interface TwoFactorEnableResponse { success: boolean; backup_codes: string[]; message: string; } interface TwoFactorStatusResponse { totp_enabled: boolean; } 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; } type FilterOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'like' | 'ilike' | 'is' | 'in' | 'cs' | 'cd' | 'ov' | 'sl' | 'sr' | 'nxr' | 'nxl' | 'fts' | 'plfts' | 'wfts'; interface QueryFilter { column: string; operator: FilterOperator; value: unknown; } type OrderDirection = 'asc' | 'desc'; interface OrderBy { column: string; direction: OrderDirection; nulls?: 'first' | 'last'; } interface RealtimeMessage { type: 'subscribe' | 'unsubscribe' | 'heartbeat' | 'broadcast' | 'ack' | 'error'; channel?: string; payload?: unknown; error?: string; } interface RealtimeChangePayload { type: 'INSERT' | 'UPDATE' | 'DELETE'; schema: string; table: string; new_record?: Record<string, unknown>; old_record?: Record<string, unknown>; timestamp: string; } type RealtimeCallback = (payload: RealtimeChangePayload) => void; interface StorageObject { key: string; bucket: string; size: number; content_type: string; last_modified: string; etag?: string; metadata?: Record<string, string>; } interface UploadOptions { contentType?: string; metadata?: Record<string, string>; cacheControl?: string; upsert?: boolean; } interface ListOptions { prefix?: string; limit?: number; offset?: number; } interface SignedUrlOptions { expiresIn?: number; } interface PasswordResetResponse { message: string; } interface VerifyResetTokenResponse { valid: boolean; message: string; } interface ResetPasswordResponse { message: string; } interface MagicLinkOptions { redirect_to?: string; } interface MagicLinkResponse { message: string; } interface OAuthProvidersResponse { providers: OAuthProvider[]; } interface OAuthOptions { redirect_to?: string; scopes?: string[]; } interface OAuthUrlResponse { url: string; provider: string; } interface AdminSetupStatusResponse { needs_setup: boolean; has_admin: boolean; } interface AdminSetupRequest { email: string; password: string; name: 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, any>; } 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 APIKey { 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 CreateAPIKeyRequest { name: string; description?: string; scopes: string[]; rate_limit_per_minute: number; expires_at?: string; } interface CreateAPIKeyResponse { api_key: APIKey; key: string; } interface ListAPIKeysResponse { api_keys: APIKey[]; total: number; } interface UpdateAPIKeyRequest { name?: string; description?: string; scopes?: string[]; rate_limit_per_minute?: number; } interface RevokeAPIKeyResponse { message: string; } interface DeleteAPIKeyResponse { message: string; } 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, any>; 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: 'dashboard_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; } /** * System setting with key-value storage */ interface SystemSetting { id: string; key: string; value: Record<string, unknown>; description?: 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[]; } /** * Authentication settings for the application */ interface AuthenticationSettings { enable_signup: boolean; enable_magic_link: boolean; password_min_length: number; require_email_verification: boolean; } /** * Feature flags for the application */ interface FeatureSettings { enable_realtime: boolean; enable_storage: boolean; enable_functions: boolean; } /** * Email configuration settings */ interface EmailSettings { enabled: boolean; provider: string; } /** * Security settings for the application */ interface SecuritySettings { enable_global_rate_limit: boolean; } /** * Complete application settings structure */ interface AppSettings { authentication: AuthenticationSettings; features: FeatureSettings; email: EmailSettings; security: SecuritySettings; } /** * 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>; } interface OAuthProvider { id: string; name: string; enabled: boolean; authorize_url?: 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; } /** * 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; } /** * 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[]; } /** * Table column information */ interface Column { name: string; type: string; nullable: boolean; default_value?: string; is_primary_key?: boolean; } /** * 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; } /** * HTTP client for making requests to the Fluxbase API */ interface FetchOptions { method: HttpMethod; headers?: Record<string, string>; body?: unknown; timeout?: number; } declare class FluxbaseFetch { private baseUrl; private defaultHeaders; private timeout; private debug; constructor(baseUrl: string, options?: { headers?: Record<string, string>; timeout?: number; debug?: boolean; }); /** * Update the authorization header */ setAuthToken(token: string | null): void; /** * Make an HTTP request */ request<T = unknown>(path: string, options: FetchOptions): Promise<T>; /** * GET request */ get<T = unknown>(path: string, options?: Omit<FetchOptions, 'method'>): Promise<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>; } /** * Authentication module for Fluxbase SDK */ declare class FluxbaseAuth { private fetch; private session; private persist; private autoRefresh; private refreshTimer; constructor(fetch: FluxbaseFetch, autoRefresh?: boolean, persist?: boolean); /** * Get the current session */ getSession(): AuthSession | null; /** * Get the current user */ getUser(): User | null; /** * Get the current access token */ getAccessToken(): string | null; /** * Sign in with email and password * Returns AuthSession if successful, or SignInWith2FAResponse if 2FA is required */ signIn(credentials: SignInCredentials): Promise<AuthSession | SignInWith2FAResponse>; /** * Sign up with email and password */ signUp(credentials: SignUpCredentials): Promise<AuthSession>; /** * Sign out the current user */ signOut(): Promise<void>; /** * Refresh the access token */ refreshToken(): Promise<AuthSession>; /** * Get the current user from the server */ getCurrentUser(): Promise<User>; /** * Update the current user */ updateUser(data: Partial<Pick<User, 'email' | 'metadata'>>): Promise<User>; /** * Set the auth token manually */ setToken(token: string): void; /** * Setup 2FA for the current user * Returns TOTP secret and QR code URL */ setup2FA(): Promise<TwoFactorSetupResponse>; /** * Enable 2FA after verifying the TOTP code * Returns backup codes that should be saved by the user */ enable2FA(code: string): Promise<TwoFactorEnableResponse>; /** * Disable 2FA for the current user * Requires password confirmation */ disable2FA(password: string): Promise<{ success: boolean; message: string; }>; /** * Check 2FA status for the current user */ get2FAStatus(): Promise<TwoFactorStatusResponse>; /** * Verify 2FA code during login * Call this after signIn returns requires_2fa: true */ verify2FA(request: TwoFactorVerifyRequest): Promise<AuthSession>; /** * Send password reset email * Sends a password reset link to the provided email address * @param email - Email address to send reset link to */ sendPasswordReset(email: string): Promise<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<VerifyResetTokenResponse>; /** * Reset password with token * Complete the password reset process with a valid token * @param token - Password reset token * @param newPassword - New password to set */ resetPassword(token: string, newPassword: string): Promise<ResetPasswordResponse>; /** * Send magic link for passwordless authentication * @param email - Email address to send magic link to * @param options - Optional configuration for magic link */ sendMagicLink(email: string, options?: MagicLinkOptions): Promise<MagicLinkResponse>; /** * Verify magic link token and sign in * @param token - Magic link token from email */ verifyMagicLink(token: string): Promise<AuthSession>; /** * Sign in anonymously * Creates a temporary anonymous user session */ signInAnonymously(): Promise<AuthSession>; /** * Get list of enabled OAuth providers */ getOAuthProviders(): Promise<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<OAuthUrlResponse>; /** * Exchange OAuth authorization code for session * This is typically called in your OAuth callback handler * @param code - Authorization code from OAuth callback */ exchangeCodeForSession(code: string): Promise<AuthSession>; /** * 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<void>; /** * Internal: Set the session and persist it */ private setSession; /** * Internal: Clear the session */ private clearSession; /** * Internal: Save session to storage */ private saveSession; /** * Internal: Schedule automatic token refresh */ private scheduleTokenRefresh; } /** * Realtime subscriptions using WebSockets */ declare class RealtimeChannel { private ws; private url; private token; private channelName; private callbacks; private reconnectAttempts; private maxReconnectAttempts; private reconnectDelay; private heartbeatInterval; constructor(url: string, channelName: string, token?: string | null); /** * Listen to a specific event type * @param event - The event type (INSERT, UPDATE, DELETE, or '*' for all) * @param callback - The callback function */ on(event: 'INSERT' | 'UPDATE' | 'DELETE' | '*', callback: RealtimeCallback): this; /** * Remove a callback */ off(event: 'INSERT' | 'UPDATE' | 'DELETE' | '*', callback: RealtimeCallback): this; /** * Subscribe to the channel */ subscribe(): this; /** * Unsubscribe from the channel */ unsubscribe(): void; /** * Internal: Connect to WebSocket */ private connect; /** * Internal: Disconnect WebSocket */ private disconnect; /** * Internal: Send a message */ private send; /** * Internal: Handle incoming message */ private handleMessage; /** * Internal: Handle broadcast message */ private handleBroadcast; /** * Internal: Start heartbeat interval */ private startHeartbeat; /** * Internal: Stop heartbeat interval */ private stopHeartbeat; /** * Internal: Attempt to reconnect */ private attemptReconnect; } declare class FluxbaseRealtime { private url; private token; private channels; constructor(url: string, token?: string | null); /** * Create or get a channel * @param channelName - Channel name (e.g., 'table:public.products') */ channel(channelName: string): RealtimeChannel; /** * Remove all channels */ removeAllChannels(): void; /** * Update auth token for all channels */ setToken(token: string | null): void; } /** * 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, or ArrayBuffer) * @param options - Upload options */ upload(path: string, file: File | Blob | ArrayBuffer, options?: UploadOptions): Promise<{ data: StorageObject | null; error: Error | null; }>; /** * Download a file from the bucket * @param path - The path/key of the file */ download(path: string): Promise<{ data: Blob | null; error: Error | null; }>; /** * List files in the bucket * @param options - List options (prefix, limit, offset) */ list(options?: ListOptions): Promise<{ data: StorageObject[] | null; error: Error | null; }>; /** * Remove files from the bucket * @param paths - Array of file paths to remove */ remove(paths: string[]): Promise<{ data: null; error: Error | null; }>; /** * Get a public URL for a file * @param path - The file path */ getPublicUrl(path: string): { data: { publicUrl: string; }; }; /** * Create a signed URL for temporary access to a file * @param path - The file path * @param options - Signed URL options */ createSignedUrl(path: string, options?: SignedUrlOptions): Promise<{ data: { signedUrl: string; } | null; error: Error | null; }>; /** * Move a file to a new location * @param fromPath - Current file path * @param toPath - New file path */ move(fromPath: string, toPath: string): Promise<{ data: StorageObject | null; error: Error | null; }>; /** * Copy a file to a new location * @param fromPath - Source file path * @param toPath - Destination file path */ copy(fromPath: string, toPath: string): Promise<{ data: StorageObject | 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: null; error: Error | null; }>; /** * Delete a bucket * @param bucketName - The name of the bucket to delete */ deleteBucket(bucketName: string): Promise<{ data: null; error: Error | null; }>; /** * Empty a bucket (delete all files) * @param bucketName - The name of the bucket to empty */ emptyBucket(bucketName: string): Promise<{ data: 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 * } * }) * * // Reset to defaults * await settings.reset() * ``` */ 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>; /** * Reset all application settings to defaults * * This will delete all custom settings and return to default values. * * @returns Promise resolving to AppSettings - Default settings * * @example * ```typescript * const defaults = await client.admin.settings.app.reset() * console.log('Settings reset to defaults:', defaults) * ``` */ reset(): 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>; } /** * Settings Manager * * Provides access to both system-level and application-level settings. * * @example * ```typescript * const settings = client.admin.settings * * // Access system settings * const systemSettings = await settings.system.list() * * // Access app settings * const appSettings = await settings.app.get() * ``` */ declare class FluxbaseSettings { system: SystemSettingsManager; app: AppSettingsManager; constructor(fetch: FluxbaseFetch); } /** * 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'], * 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 = a