UNPKG

@smartsamurai/krapi-sdk

Version:

KRAPI TypeScript SDK - Easy-to-use client SDK for connecting to self-hosted KRAPI servers (like Appwrite SDK)

1,782 lines (1,777 loc) 164 kB
import { AxiosInstance } from 'axios'; /** * Core SDK Types and Interfaces * * Shared types and interfaces used across the SDK for both * database operations and HTTP client operations. * * @module core */ /** * Database Connection Interface * * Defines the interface for database connections used by the SDK. * * @interface DatabaseConnection * @property {Function} query - Execute SQL query with parameters * @property {Function} [connect] - Connect to database (optional) * @property {Function} [end] - Close database connection (optional) */ interface DatabaseConnection$2 { query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[]; rowCount: number; }>; connect?: () => Promise<void>; end?: () => Promise<void>; } /** * Logger Interface * * Defines the interface for loggers used by the SDK. * * @interface Logger * @property {Function} info - Log info messages * @property {Function} warn - Log warning messages * @property {Function} error - Log error messages * @property {Function} debug - Log debug messages */ interface Logger { info: (message: string, ...args: unknown[]) => void; warn: (message: string, ...args: unknown[]) => void; error: (message: string, ...args: unknown[]) => void; debug: (message: string, ...args: unknown[]) => void; } /** * SDK Configuration for Database Operations * * Configuration for SDK when using database mode (server-side). * * @interface DatabaseSDKConfig * @property {DatabaseConnection} databaseConnection - Database connection (required) * @property {Logger} [logger] - Logger instance * @property {boolean} [enableAutoFix] - Enable automatic schema fixes * @property {boolean} [enableHealthChecks] - Enable health checks * @property {number} [maxRetries] - Maximum retry attempts */ interface DatabaseSDKConfig { databaseConnection: DatabaseConnection$2; logger?: Logger; enableAutoFix?: boolean; enableHealthChecks?: boolean; maxRetries?: number; } /** * SDK Configuration for HTTP Client Operations * * Configuration for SDK when using HTTP client mode (client-side). * * @interface HttpSDKConfig * @property {string} baseUrl - Base URL for API requests * @property {string} [apiKey] - API key for authentication * @property {string} [sessionToken] - Session token for authentication * @property {number} [timeout] - Request timeout in milliseconds * @property {Logger} [logger] - Logger instance */ interface HttpSDKConfig { baseUrl: string; apiKey?: string; sessionToken?: string; timeout?: number; logger?: Logger; } /** * Common API Response Type * * Standard response format for all API operations. * * @interface ApiResponse * @template T - Response data type * @property {boolean} success - Whether the operation succeeded * @property {T} [data] - Response data (if successful) * @property {string} [error] - Error message (if failed) * @property {string} [message] - Additional message * @property {string} [timestamp] - Response timestamp */ interface ApiResponse$1<T = unknown> { success: boolean; data?: T; error?: string; message?: string; timestamp?: string; } /** * Paginated API Response Type * * Response format for paginated API operations. * * @interface PaginatedResponse * @template T - Response data item type * @extends {ApiResponse<T[]>} * @property {Object} [pagination] - Pagination information * @property {number} pagination.page - Current page number * @property {number} pagination.limit - Items per page * @property {number} pagination.total - Total number of items * @property {number} pagination.totalPages - Total number of pages * @property {boolean} pagination.hasNext - Whether there is a next page * @property {boolean} pagination.hasPrev - Whether there is a previous page */ interface PaginatedResponse$1<T = unknown> extends ApiResponse$1<T[]> { pagination?: { page: number; limit: number; total: number; totalPages: number; hasNext: boolean; hasPrev: boolean; }; } /** * Common Query Options * * Options for querying data with pagination, search, sorting, and filtering. * * @interface QueryOptions * @property {number} [limit] - Maximum number of items to return * @property {number} [offset] - Number of items to skip * @property {string} [search] - Search term * @property {string} [sortBy] - Field to sort by * @property {"asc" | "desc"} [sortOrder] - Sort order * @property {Record<string, unknown>} [filters] - Additional filters */ interface QueryOptions$1 { limit?: number; offset?: number; search?: string; sortBy?: string; sortOrder?: "asc" | "desc"; filters?: Record<string, unknown>; } /** * Base Client Interface * * Base interface for both database and HTTP client operations. * * @interface BaseClient * @property {Function} [close] - Close the client connection (optional) */ interface BaseClient { close?: () => Promise<void>; } /** * SDK Error Type * * Extended error type for SDK-specific errors. * * @interface SDKError * @extends {Error} * @property {string} [code] - Error code * @property {number} [status] - HTTP status code (if applicable) * @property {boolean} [isApiError] - Whether this is an API error * @property {boolean} [isNetworkError] - Whether this is a network error * @property {boolean} [isConfigError] - Whether this is a configuration error * @property {Error} [originalError] - Original error (if wrapped) */ interface SDKError extends Error { code?: string; status?: number; isApiError?: boolean; isNetworkError?: boolean; isConfigError?: boolean; originalError?: Error; } /** * Environment Type * * Application environment type. * * @typedef {"development" | "staging" | "production"} Environment */ type Environment = "development" | "staging" | "production"; /** * Field Type Enum * * Supported field types for collection fields. * * @enum {string} FieldType */ declare enum FieldType { string = "string", text = "text", number = "number", integer = "integer", float = "float", boolean = "boolean", date = "date", datetime = "datetime", time = "time", timestamp = "timestamp", email = "email", url = "url", phone = "phone", uuid = "uuid", uniqueID = "uniqueID", json = "json", array = "array", object = "object", file = "file", image = "image", video = "video", audio = "audio", reference = "reference", relation = "relation", enum = "enum", password = "password", encrypted = "encrypted", varchar = "varchar", decimal = "decimal" } /** * KRAPI Universal Type Definitions * * This file is the SINGLE SOURCE OF TRUTH for all types across: * - SDK (client and server modes) * - Frontend API routes * - Backend implementations * - Database schemas * - Test suites * * ALL other files must import types from here. * NO types should be defined elsewhere. * * @module types */ interface ApiResponse<T = unknown> { success: boolean; data?: T; error?: string; message?: string; timestamp?: string; } interface PaginatedResponse<T = unknown> { data: T[]; pagination: { page: number; per_page: number; total: number; total_pages: number; has_next: boolean; has_prev: boolean; }; } interface PaginationOptions { limit?: number; offset?: number; page?: number; perPage?: number; } interface SearchOptions { search?: string; query?: string; filter?: Record<string, unknown>; } interface SortOptions { orderBy?: string; order?: "asc" | "desc"; sortBy?: string; sortOrder?: "asc" | "desc"; } type QueryOptions = PaginationOptions & SearchOptions & SortOptions; interface SessionToken { token: string; user_id: string; expires_at: string; created_at: string; last_used_at?: string; } interface Session$1 { id: string; user_id: string; token: string; expires_at: string; created_at: string; last_used_at?: string; ip_address?: string; user_agent?: string; is_active: boolean; type?: SessionType; project_id?: string; scopes?: Scope[]; metadata?: Record<string, unknown>; consumed?: boolean; user_type?: "admin" | "project"; } interface SessionValidation { valid: boolean; user?: User; expires_at?: string; session_token?: string; } interface RefreshResponse { success: boolean; session_token: string; expires_at: string; } interface ProjectLoginRequest { projectId: string; username: string; password: string; email?: string; } interface User { id: string; username: string; email: string; role: UserRole; status: UserStatus; created_at: string; updated_at: string; last_login_at?: string; profile?: UserProfile; project_id?: string; permissions?: string[]; phone?: string; is_verified?: boolean; scopes?: Scope[]; } interface ProjectUser$1 { id: string; project_id: string; username: string; email: string; role: UserRole; status: UserStatus; created_at: string; updated_at: string; last_login?: string; phone?: string; is_verified?: boolean; scopes?: string[]; password?: string; permissions?: string[]; } interface AdminUser$1 { id: string; username: string; email: string; role: AdminRole; access_level: AccessLevel; permissions: string[]; active: boolean; created_at: string; updated_at: string; last_login?: string; login_count?: number; api_key?: string; password_hash?: string; } type CollectionField = FieldDefinition; type CollectionIndex = IndexDefinition; interface UserProfile { first_name?: string; last_name?: string; display_name?: string; avatar_url?: string; bio?: string; metadata?: Record<string, unknown>; } type UserRole = "admin" | "user" | "viewer" | "editor" | "owner" | "member"; type UserStatus = "active" | "inactive" | "suspended" | "pending"; declare enum AdminRole { SUPER_ADMIN = "super_admin", ADMIN = "admin", MODERATOR = "moderator", DEVELOPER = "developer", MASTER_ADMIN = "master_admin", PROJECT_ADMIN = "project_admin", LIMITED_ADMIN = "limited_admin" } declare enum AccessLevel { READ = "read", WRITE = "write", DELETE = "delete", ADMIN = "admin", READ_ONLY = "read_only", READ_WRITE = "read_write", FULL = "full" } declare enum Scope { READ = "read", WRITE = "write", DELETE = "delete", ADMIN = "admin", MASTER = "master", ADMIN_READ = "admin:read", ADMIN_WRITE = "admin:write", ADMIN_DELETE = "admin:delete", PROJECTS_READ = "projects:read", PROJECTS_WRITE = "projects:write", PROJECTS_DELETE = "projects:delete", COLLECTIONS_READ = "collections:read", COLLECTIONS_WRITE = "collections:write", COLLECTIONS_DELETE = "collections:delete", DOCUMENTS_READ = "documents:read", DOCUMENTS_WRITE = "documents:write", DOCUMENTS_DELETE = "documents:delete", STORAGE_READ = "storage:read", STORAGE_WRITE = "storage:write", STORAGE_DELETE = "storage:delete", EMAIL_SEND = "email:send", EMAIL_READ = "email:read", FUNCTIONS_EXECUTE = "functions:execute", FUNCTIONS_WRITE = "functions:write", FUNCTIONS_DELETE = "functions:delete", USERS_READ = "users:read", USERS_WRITE = "users:write", USERS_DELETE = "users:delete", DATA_READ = "data:read", DATA_WRITE = "data:write", DATA_DELETE = "data:delete", FILES_READ = "files:read", FILES_WRITE = "files:write", FILES_DELETE = "files:delete" } /** * Project-specific scopes for users within a project * * NOTE: These scopes are ONLY for managing resources within a SINGLE project. * Global scopes like "projects:read" are reserved for main KRAPI app admin users, * not for project users. Projects are isolated - they cannot see or manage other projects. */ declare enum ProjectScope { USERS_READ = "users:read", USERS_WRITE = "users:write", USERS_DELETE = "users:delete", DATA_READ = "data:read", DATA_WRITE = "data:write", DATA_DELETE = "data:delete", FILES_READ = "files:read", FILES_WRITE = "files:write", FILES_DELETE = "files:delete", FUNCTIONS_EXECUTE = "functions:execute", EMAIL_SEND = "email:send", COLLECTIONS_READ = "collections:read", COLLECTIONS_WRITE = "collections:write", COLLECTIONS_DELETE = "collections:delete", DOCUMENTS_READ = "documents:read", DOCUMENTS_WRITE = "documents:write", DOCUMENTS_DELETE = "documents:delete" } interface UserListOptions extends QueryOptions { role?: UserRole; status?: UserStatus; } interface ApiKey { id: string; name: string; key: string; scopes: ApiKeyScope[]; project_id?: string; user_id: string; status: ApiKeyStatus; expires_at?: string; created_at: string; last_used_at?: string; usage_count: number; rate_limit?: number; metadata?: Record<string, unknown>; project_ids?: string[]; } type ApiKeyScope = "read" | "write" | "delete" | "projects:read" | "projects:write" | "projects:delete" | "collections:read" | "collections:write" | "collections:delete" | "documents:read" | "documents:write" | "documents:delete" | "files:read" | "files:write" | "files:delete" | "users:read" | "users:write" | "users:delete" | "admin" | "*"; type ApiKeyStatus = "active" | "inactive" | "revoked" | "expired"; interface CreateApiKeyRequest { name: string; scopes: ApiKeyScope[]; project_id?: string; expires_at?: string; rate_limit?: number; metadata?: Record<string, unknown>; } interface ApiKeyListOptions extends QueryOptions { type?: "admin" | "project"; status?: ApiKeyStatus; project_id?: string; } interface CreateSessionRequest { api_key: string; } interface Project { id: string; name: string; description?: string; status: ProjectStatus; owner_id: string; created_at: string; updated_at: string; settings: ProjectSettings; metadata?: Record<string, unknown>; stats?: ProjectStats; storage_used?: number; allowed_origins?: string[]; total_api_calls?: number; last_api_call?: string; project_url?: string; active?: boolean; created_by?: string; rate_limit?: number; rate_limit_window?: number; } type ProjectStatus = "active" | "inactive" | "suspended" | "archived"; interface ProjectSettings { public: boolean; allow_registration: boolean; require_email_verification: boolean; max_users?: number; max_collections?: number; max_documents_per_collection?: number; max_file_size?: number; allowed_file_types?: string[]; cors_origins?: string[]; webhook_urls?: string[]; rate_limits?: { requests_per_minute?: number; requests_per_hour?: number; requests_per_day?: number; }; custom_domain?: string; timezone?: string; locale?: string; email_config?: { smtp_host: string; smtp_port: number; smtp_secure: boolean; smtp_username: string; smtp_password: string; from_email: string; from_name: string; }; authentication_required?: boolean; cors_enabled?: boolean; rate_limiting_enabled?: boolean; logging_enabled?: boolean; encryption_enabled?: boolean; backup_enabled?: boolean; backup_automation?: { enabled: boolean; frequency: "hourly" | "daily" | "weekly" | "monthly"; time?: string; day_of_week?: number; day_of_month?: number; retention_days?: number; max_backups?: number; include_files?: boolean; description_template?: string; }; custom_headers?: Record<string, string>; environment?: "development" | "staging" | "production"; } interface ProjectStats { total_users: number; total_collections: number; total_documents: number; total_files: number; storage_used: number; api_requests_today: number; api_requests_month: number; api_calls_count?: number; last_api_call?: string; collections_count?: number; documents_count?: number; users_count?: number; } interface CreateProjectRequest { name: string; description?: string; settings?: Partial<ProjectSettings>; metadata?: Record<string, unknown>; } interface UpdateProjectRequest { name?: string; description?: string; status?: ProjectStatus; settings?: Partial<ProjectSettings>; metadata?: Record<string, unknown>; } interface ProjectListOptions extends QueryOptions { status?: ProjectStatus; owner_id?: string; page?: number; } interface Collection$1 { id: string; name: string; display_name?: string; description?: string; project_id: string; schema: CollectionSchema; settings: CollectionSettings; created_at: string; updated_at: string; metadata?: Record<string, unknown>; stats?: CollectionStats; fields?: FieldDefinition[]; indexes?: IndexDefinition[]; collection_id?: string; } interface CollectionSchema { fields: FieldDefinition[]; indexes?: IndexDefinition[]; validations?: ValidationRule[]; relationships?: RelationshipDefinition[]; } interface FieldDefinition { name: string; type: FieldType; display_name?: string; description?: string; required: boolean; unique: boolean; default_value?: unknown; validation?: FieldValidation; options?: FieldOptions; metadata?: Record<string, unknown>; indexed?: boolean; default?: unknown; relation?: Record<string, unknown>; length?: number; precision?: number; scale?: number; nullable?: boolean; primary?: boolean; } interface FieldValidation { min_length?: number; max_length?: number; min_value?: number; max_value?: number; pattern?: string; allowed_values?: unknown[]; custom_validator?: string; minLength?: number; maxLength?: number; minItems?: number; maxItems?: number; min?: number; max?: number; } interface FieldOptions { enum_values?: string[]; reference_collection?: string; reference_field?: string; file_types?: string[]; max_file_size?: number; multiple?: boolean; placeholder?: string; help_text?: string; } interface IndexDefinition { name: string; fields: string[]; unique?: boolean; type?: "btree" | "hash" | "gin" | "gist"; } interface ValidationRule { name: string; type: "required" | "unique" | "custom"; fields: string[]; message?: string; validator?: string; } interface RelationshipDefinition { name: string; type: "one_to_one" | "one_to_many" | "many_to_many"; target_collection: string; foreign_key?: string; reference_key?: string; cascade_delete?: boolean; } type RelationConfig = RelationshipDefinition; interface CollectionSettings { read_permissions: Permission[]; write_permissions: Permission[]; delete_permissions: Permission[]; enable_audit_log: boolean; enable_soft_delete: boolean; enable_versioning: boolean; cache_ttl?: number; max_documents?: number; } interface Permission { role: UserRole; conditions?: Record<string, unknown>; } interface CollectionStats { total_documents: number; total_size: number; last_updated: string; avg_document_size: number; } interface CreateCollectionRequest { name: string; display_name?: string; description?: string; schema: Partial<CollectionSchema>; settings?: Partial<CollectionSettings>; metadata?: Record<string, unknown>; } interface UpdateCollectionRequest { name?: string; display_name?: string; description?: string; schema?: Partial<CollectionSchema>; settings?: Partial<CollectionSettings>; metadata?: Record<string, unknown>; } interface CollectionListOptions extends QueryOptions { project_id?: string; } interface Document$1 { id: string; collection_id: string; project_id: string; data: Record<string, unknown>; version: number; is_deleted: boolean; created_at: string; updated_at: string; created_by: string; updated_by: string; metadata?: Record<string, unknown>; } type DocumentStatus = "draft" | "published" | "archived" | "deleted"; interface DocumentListOptions extends QueryOptions { status?: DocumentStatus; created_by?: string; date_from?: string; date_to?: string; } interface DocumentSearchRequest { text?: string; filters?: Record<string, unknown>; collections?: string[]; limit?: number; offset?: number; } interface BulkDocumentRequest { operation: "create" | "update" | "delete"; documents: Record<string, unknown>[]; } interface BulkDocumentResponse { success: boolean; created: number; updated: number; deleted: number; errors: Array<{ index: number; error: string; }>; } interface AggregationRequest { aggregations: Array<{ type: "count" | "sum" | "avg" | "min" | "max" | "group"; field?: string; group_by?: string; filters?: Record<string, unknown>; }>; } interface AggregationResponse { results: Array<{ type: string; field?: string; value: unknown; group?: string; }>; } interface FileInfo { id: string; name: string; original_name: string; filename: string; path: string; url: string; mime_type: string; size: number; project_id: string; uploaded_by?: string; created_at: string; updated_at: string; metadata?: FileMetadata; public: boolean; folder?: string; relations?: Array<{ id: string; type: string; target_id: string; target_type: string; metadata?: Record<string, unknown>; }>; } interface FileMetadata { width?: number; height?: number; duration?: number; thumbnail_url?: string; alt_text?: string; caption?: string; tags?: string[]; custom?: Record<string, unknown>; } interface UploadFileOptions { folder?: string; filename?: string; public?: boolean; metadata?: Partial<FileMetadata>; } interface FileListOptions extends QueryOptions { folder?: string; mime_type?: string; public?: boolean; uploaded_by?: string; } interface EmailTemplate$1 { id: string; name: string; subject: string; body: string; type: EmailTemplateType; project_id: string; variables?: string[]; created_at: string; updated_at: string; metadata?: Record<string, unknown>; } interface EmailConfig$1 { smtp_host: string; smtp_port: number; smtp_user: string; smtp_password: string; smtp_secure: boolean; from_email: string; from_name: string; reply_to?: string; rate_limit?: number; enabled: boolean; } type EmailTemplateType = "welcome" | "verification" | "reset_password" | "notification" | "custom"; interface CreateEmailTemplateRequest { name: string; subject: string; body: string; type: EmailTemplateType; variables?: string[]; metadata?: Record<string, unknown>; } interface SendEmailRequest { to: string | string[]; subject: string; body?: string; template_id?: string; variables?: Record<string, unknown>; from?: string; reply_to?: string; attachments?: Array<{ filename: string; content: string | Buffer; content_type?: string; }>; } interface EmailResponse { success: boolean; message_id?: string; error?: string; } interface EmailListOptions extends QueryOptions { type?: EmailTemplateType; } interface ActivityLog { id: string; user_id?: string; project_id?: string; action: string; resource_type: string; resource_id?: string; details: Record<string, unknown>; ip_address?: string; user_agent?: string; timestamp: Date; severity: "info" | "warning" | "error" | "critical"; metadata?: Record<string, unknown>; } interface HealthStatus { healthy: boolean; timestamp: string; version: string; environment: string; uptime: number; database: DatabaseHealth$1; storage: StorageHealth; cache?: CacheHealth; external_services?: ExternalServiceHealth[]; } interface DatabaseIssue { type: string; description: string; severity: "info" | "warning" | "error" | "low" | "medium" | "high" | "critical"; table?: string; field?: string; } interface DatabaseHealth$1 { connected: boolean; response_time?: number; total_tables?: number; total_records?: number; last_backup?: string; issues?: DatabaseIssue[]; checkDuration?: number; isHealthy?: boolean; warnings?: DatabaseIssue[]; } type DatabaseHealthStatus$1 = DatabaseHealth$1; interface SchemaValidationResult$1 { valid: boolean; isValid?: boolean; errors: string[]; warnings: string[]; missing_tables: string[]; extra_tables: string[]; field_mismatches: FieldMismatch[]; mismatches?: SchemaMismatch[]; missingTables?: string[]; extraTables?: string[]; fieldMismatches?: FieldMismatch[]; timestamp?: string; } interface MigrationResult$1 { success: boolean; migrations_applied: number; migrationsApplied?: number; errors: string[]; duration: number; details?: string; appliedMigrations?: number; } interface SchemaMismatch { table: string; type: "missing" | "extra" | "field_mismatch" | "missing_field" | "missing_index" | "missing_constraint"; details: string; field?: string; } interface FieldMismatch { table: string; field: string; expected_type: string; actual_type: string; nullable_mismatch?: boolean; expected: FieldDefinition; } interface StorageHealth { available: boolean; free_space?: number; total_space?: number; used_space?: number; issues?: string[]; } interface CacheHealth { connected: boolean; hit_rate?: number; memory_usage?: number; issues?: string[]; } interface ExternalServiceHealth { name: string; status: "up" | "down" | "degraded"; response_time?: number; last_check: string; } interface AutoFixResult$1 { success: boolean; message?: string; actions?: { repairs: string[]; migrations: string[]; optimizations: string[]; }; fixesApplied?: number; appliedFixes?: string[]; duration: number; details?: string; } type RouteParams<T = Record<string, string>> = Promise<T>; interface RouteContext<T = Record<string, string>> { params: RouteParams<T>; } interface ProjectRouteParams { projectId: string; } interface CollectionRouteParams extends ProjectRouteParams { collectionName: string; } interface DocumentRouteParams extends CollectionRouteParams { documentId: string; } interface UserRouteParams extends ProjectRouteParams { userId: string; } interface FileRouteParams extends ProjectRouteParams { fileId: string; } type RouteHandler = (request: Request, context: RouteContext) => Promise<Response>; type ProjectRouteHandler = (request: Request, context: RouteContext<ProjectRouteParams>) => Promise<Response>; type CollectionRouteHandler = (request: Request, context: RouteContext<CollectionRouteParams>) => Promise<Response>; type DocumentRouteHandler = (request: Request, context: RouteContext<DocumentRouteParams>) => Promise<Response>; interface DatabaseConnection$1 { host: string; port: number; database: string; username: string; password: string; ssl?: boolean; pool?: { min?: number; max?: number; idleTimeoutMillis?: number; }; } interface HttpConnection { endpoint: string; apiKey?: string; timeout?: number; retries?: number; headers?: Record<string, string>; } type KrapiConnection = DatabaseConnection$1 | HttpConnection; type DeepPartial<T> = { [P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]; }; interface CollectionTypeDefinition { id: string; name: string; description?: string; version: string; schema: CollectionTypeSchema; validation_rules: CollectionTypeValidationRule[]; auto_fix_rules: CollectionTypeAutoFixRule[]; created_at: string; updated_at: string; created_by: string; project_id: string; fields: CollectionTypeField[]; indexes: CollectionTypeIndex[]; constraints: CollectionTypeConstraint[]; relations: CollectionTypeRelation[]; metadata?: Record<string, unknown>; } interface CollectionTypeSchema { fields: CollectionTypeField[]; indexes: CollectionTypeIndex[]; constraints: CollectionTypeConstraint[]; relations: CollectionTypeRelation[]; } interface CollectionTypeField { name: string; type: FieldType; required: boolean; unique: boolean; indexed: boolean; default?: unknown; description?: string; validation?: FieldValidation; length?: number; precision?: number; scale?: number; nullable?: boolean; primary?: boolean; sqlite_type?: string; typescript_type?: string; relation?: Record<string, unknown>; } interface CollectionTypeIndex { name: string; fields: string[]; unique: boolean; type?: "btree" | "hash" | "gin" | "gist"; } interface CollectionTypeConstraint { name: string; type: "primary_key" | "foreign_key" | "unique" | "check" | "not_null"; fields: string[]; reference_table?: string; reference_fields?: string[]; cascade_delete?: boolean; check_expression?: string; reference?: { table: string; field: string; onDelete?: string; onUpdate?: string; }; expression?: string; } interface CollectionTypeRelation { name: string; type: "one-to-one" | "one-to-many" | "many-to-one" | "many-to-many"; target_collection: string; source_field: string; target_field: string; cascade_delete: boolean; } interface CollectionTypeValidationRule { id: string; name: string; description: string; severity: "error" | "warning" | "info"; condition: string; message: string; } interface CollectionTypeAutoFixRule { id: string; name: string; description: string; action: "add_field" | "modify_field" | "add_index" | "add_constraint" | "drop_field"; parameters: Record<string, unknown>; priority: number; } interface CollectionTypeValidationResult { isValid: boolean; issues: CollectionTypeIssue[]; warnings: CollectionTypeIssue[]; suggestions: CollectionTypeIssue[]; } interface CollectionTypeIssue { id?: string; type: "error" | "warning" | "info" | "suggestion" | "missing_field" | "wrong_type" | "missing_index" | "missing_constraint" | "type_mismatch" | "extra_field"; severity: "critical" | "high" | "medium" | "low" | "info" | "error" | "warning"; category?: "schema" | "validation" | "performance" | "security"; description: string; field?: string; table?: string; suggestion?: string; auto_fixable: boolean; expected?: string; actual?: string; } interface CollectionTypeAutoFixResult { success: boolean; fixes_applied: CollectionTypeFix[]; fixes_failed: CollectionTypeFix[]; total_fixes: number; duration: number; details: string; fixesApplied?: CollectionTypeFix[]; fixesFailed?: CollectionTypeFix[]; totalFixes?: number; detailsArray?: string[]; fixes_applied_count?: number; details_array?: string[]; } interface CollectionTypeFix { id?: string; type: "add_field" | "modify_field" | "add_index" | "add_constraint" | "drop_field"; table?: string; field?: string; description: string; sql: string; parameters?: Record<string, unknown>; applied?: boolean; error?: string; success?: boolean; execution_time?: number; } interface CollectionTypeRegistry { types: Map<string, CollectionTypeDefinition>; version: string; last_sync: string; auto_fix_enabled: boolean; validation_strict: boolean; } interface ChangelogEntry { id: string; type: string; title: string; description: string; version: string; user_id: string; action: string; resource_type: string; resource_id: string; changes: Record<string, unknown>; created_at: string; metadata?: Record<string, unknown>; project_id?: string; entity_type?: string; entity_id?: string; performed_by?: string; session_id?: string; } interface CreateChangelogEntry { type: "feature" | "bugfix" | "breaking" | "deprecation" | "security"; title: string; description: string; version: string; author: string; breaking_changes?: string[]; migration_guide?: string; } interface StorageStats { total_size: number; file_count: number; collections_count: number; projects_count: number; last_updated: string; } interface EmailSendRequest { to: string | string[]; subject: string; body: string; html?: boolean; attachments?: EmailAttachment[]; template_id?: string; variables?: Record<string, unknown>; } interface EmailAttachment { filename: string; content: string | Buffer; content_type: string; } interface SystemInfo { version: string; build_date: string; node_version: string; platform: string; arch: string; uptime: number; memory_usage: { rss: number; heapTotal: number; heapUsed: number; external: number; }; } interface TestResult$1 { name: string; status: "passed" | "failed" | "skipped"; duration: number; error?: string; details?: Record<string, unknown>; } interface SystemSettings { debug_mode: boolean; log_level: "error" | "warn" | "info" | "debug"; rate_limiting: { enabled: boolean; window_ms: number; max_requests: number; }; security: { cors_enabled: boolean; allowed_origins: string[]; session_timeout: number; password_min_length: number; }; database: { connection_pool_size: number; query_timeout: number; max_connections: number; }; } interface AdminPermission { id: string; name: string; description: string; resource: string; action: "create" | "read" | "update" | "delete" | "manage"; scope: "global" | "project" | "collection" | "user"; } interface FileRelation { id: string; file_id: string; related_file_id: string; relation_type: "parent" | "child" | "sibling" | "version"; metadata?: Record<string, unknown>; } interface FileAttachment { id: string; file_id: string; attached_to_type: "document" | "email" | "project"; attached_to_id: string; attachment_type: "inline" | "attachment"; metadata?: Record<string, unknown>; } interface FilterCondition { field: string; operator: "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in" | "nin" | "like" | "ilike" | "regex" | "exists"; value: unknown; case_sensitive?: boolean; } interface ExpectedSchema { tables: TableDefinition[]; version: string; description?: string; } interface TableDefinition { name: string; fields: FieldDefinition[]; indexes: IndexDefinition[]; constraints: ConstraintDefinition[]; relations: RelationDefinition[]; } interface ConstraintDefinition { name: string; type: "primary_key" | "foreign_key" | "unique" | "check" | "not_null"; fields: string[]; reference_table?: string; reference_fields?: string[]; cascade_delete?: boolean; check_expression?: string; reference?: { table: string; field: string; onDelete?: string; onUpdate?: string; }; expression?: string; } interface RelationDefinition { name: string; type: "one-to-one" | "one-to-many" | "many-to-one" | "many-to-many"; target_table: string; source_field: string; target_field: string; cascade_delete: boolean; } declare enum SessionType { ADMIN = "admin", PROJECT = "project", USER = "user" } interface FileRecord { id: string; project_id: string; filename: string; original_name: string; mime_type: string; size: number; path: string; url: string; uploaded_by: string; created_at: string; updated_at: string; metadata?: Record<string, unknown>; } interface BackupMetadata { id: string; project_id?: string; type: "project" | "system"; created_at: string; size: number; encrypted: boolean; version: string; description?: string; /** Restic snapshot ID (for Restic backend) */ snapshot_id?: string; /** Unique data size after deduplication */ unique_size?: number; /** Number of files in backup */ file_count?: number; /** Backup tags */ tags?: string[]; } interface ChatMessage { role: "user" | "assistant" | "system"; content: string; timestamp?: string; } interface ChatResponse { message: string; model: string; usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; finish_reason?: string; } interface ModelCapabilities { models: string[]; features: string[]; max_tokens: number; supports_streaming: boolean; supports_functions: boolean; } interface Model { id: string; name: string; provider: string; capabilities: string[]; max_tokens: number; is_available: boolean; } /** * Backup API Manager * * Handles all backup-related API operations for the KRAPI client SDK. */ declare class BackupApiManager { private axiosInstance; constructor(axiosInstance: AxiosInstance); /** * Create a project backup */ createProject(projectId: string, options?: { description?: string; password?: string; }): Promise<ApiResponse<{ backup_id: string; password: string; created_at: string; size: number; }>>; /** * Restore a project from backup */ restoreProject(projectId: string, backupId: string, password: string, options?: { overwrite?: boolean; }): Promise<ApiResponse<{ success: boolean; }>>; /** * List backups */ list(projectId?: string, type?: "project" | "system"): Promise<ApiResponse<unknown[]>>; /** * Delete a backup */ delete(backupId: string): Promise<ApiResponse<{ success: boolean; }>>; /** * Create a system backup */ createSystem(options?: { description?: string; password?: string; }): Promise<ApiResponse<{ backup_id: string; password: string; created_at: string; size: number; }>>; } interface Document { id: string; collection_id: string; project_id: string; data: Record<string, unknown>; created_at: string; updated_at: string; created_by: string; updated_by: string; version: number; is_deleted: boolean; deleted_at?: string; deleted_by?: string; } interface DocumentFilter { field_filters?: Record<string, unknown>; search?: string; created_after?: string; created_before?: string; updated_after?: string; updated_before?: string; created_by?: string; updated_by?: string; include_deleted?: boolean; } interface DocumentQueryOptions { limit?: number; offset?: number; sort_by?: string; sort_order?: "asc" | "desc"; select_fields?: string[]; } interface CreateDocumentRequest { data: Record<string, unknown>; created_by?: string; } interface UpdateDocumentRequest { data: Record<string, unknown>; updated_by?: string; } interface DatabaseConnection { query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[]; rowCount: number; }>; } /** * Collections Service * * High-level service for managing dynamic collections with schema validation, * auto-fixing, and TypeScript interface generation. * * @class CollectionsService * @example * const collectionsService = new CollectionsService(dbConnection, logger); * const collection = await collectionsService.createCollection({ * name: 'users', * fields: [{ name: 'email', type: FieldType.string, required: true }] * }); */ declare class CollectionsService { private logger; private schemaManager; private schemaInspector; private db; /** * Create a new CollectionsService instance * * @param {DatabaseConnection} databaseConnection - Database connection * @param {Console} [logger=console] - Logger instance */ constructor(databaseConnection: DatabaseConnection, logger?: Console); /** * Map database row to Document interface */ private mapDocument; /** * Create a new collection with custom schema * Example: Create an "articles" collection with title, content, author fields */ /** * Create a new collection * * Creates a new collection with the specified schema and fields. * Automatically creates the database table and indexes. * * @param {Object} collectionData - Collection creation data * @param {string} collectionData.project_id - Project ID * @param {string} collectionData.name - Collection name (required) * @param {string} [collectionData.description] - Collection description * @param {CollectionField[]} collectionData.fields - Collection field definitions * @param {CollectionSettings} [collectionData.settings] - Collection settings * @returns {Promise<Collection>} Created collection * @throws {Error} If creation fails or collection name already exists * * @example * const collection = await collectionsService.createCollection({ * project_id: 'project-id', * name: 'users', * description: 'User collection', * fields: [ * { name: 'email', type: FieldType.string, required: true }, * { name: 'name', type: FieldType.string, required: true } * ] * }); */ createCollection(collectionData: { name: string; description?: string; fields: Array<{ name: string; type: FieldType; required?: boolean; unique?: boolean; indexed?: boolean; default?: unknown; description?: string; validation?: FieldValidation; relation?: RelationConfig; }>; indexes?: Array<{ name: string; fields: string[]; unique?: boolean; }>; }): Promise<Collection$1>; /** * Create a collection from a predefined template * * Creates a collection using a template (e.g., 'users', 'posts', 'products') * with optional customizations. * * @param {string} templateName - Template name * @param {Object} [customizations] - Optional customizations * @param {string} [customizations.name] - Custom collection name * @param {string} [customizations.description] - Custom description * @param {Array} [customizations.additionalFields] - Additional fields to add * @returns {Promise<Collection>} Created collection * @throws {Error} If template not found or creation fails * * @example * const collection = await collectionsService.createCollectionFromTemplate('users', { * name: 'customers', * additionalFields: [{ name: 'phone', type: FieldType.string }] * }); */ createCollectionFromTemplate(templateName: string, customizations?: { name?: string; description?: string; additionalFields?: Array<{ name: string; type: FieldType; required?: boolean; unique?: boolean; indexed?: boolean; description?: string; }>; }): Promise<Collection$1>; /** * Update collection schema * * Updates a collection's schema by adding, removing, or modifying fields. * Automatically updates the database table structure. * * @param {string} collectionId - Collection ID * @param {Object} updates - Schema updates * @param {Array} [updates.addFields] - Fields to add * @param {string[]} [updates.removeFields] - Field names to remove * @param {Array} [updates.modifyFields] - Fields to modify * @returns {Promise<Collection>} Updated collection * @throws {Error} If update fails or collection not found * * @example * const updated = await collectionsService.updateCollectionSchema('collection-id', { * addFields: [{ name: 'age', type: FieldType.number }], * removeFields: ['old_field'] * }); */ updateCollectionSchema(collectionId: string, updates: { addFields?: Array<{ name: string; type: FieldType; required?: boolean; unique?: boolean; indexed?: boolean; default?: unknown; description?: string; validation?: FieldValidation; relation?: RelationConfig; }>; removeFields?: string[]; modifyFields?: Array<{ name: string; type?: FieldType; required?: boolean; unique?: boolean; indexed?: boolean; default?: unknown; description?: string; validation?: FieldValidation; relation?: RelationConfig; }>; addIndexes?: Array<{ name: string; fields: string[]; unique?: boolean; }>; removeIndexes?: string[]; }): Promise<Collection$1>; /** * Validate collection schema against database */ validateCollection(collectionId: string): Promise<{ isValid: boolean; issues: Array<{ type: "missing_field" | "wrong_type" | "missing_index" | "missing_constraint" | "extra_field"; field?: string; expected?: string; actual?: string; description: string; severity: "error" | "warning" | "info"; }>; recommendations: string[]; }>; /** * Auto-fix collection schema issues */ autoFixCollection(collectionId: string): Promise<{ success: boolean; fixesApplied: number; details: string[]; remainingIssues: number; }>; /** * Generate TypeScript interface for a collection */ generateTypeScriptInterface(collectionId: string): Promise<string>; /** * Generate all TypeScript interfaces */ generateAllTypeScriptInterfaces(): Promise<string>; /** * Get collection health status */ getCollectionHealth(collectionId: string): Promise<{ status: "healthy" | "degraded" | "unhealthy"; schemaValid: boolean; dataIntegrity: { hasNullViolations: boolean; hasUniqueViolations: boolean; hasForeignKeyViolations: boolean; issues: string[]; }; tableStats: { rowCount: number; sizeBytes: number; indexSizeBytes: number; }; lastValidated: string; }>; /** * Get all collections with health status */ getAllCollectionsWithHealth(): Promise<Array<Collection$1 & { health: { status: "healthy" | "degraded" | "unhealthy"; issues: number; }; }>>; /** * Get all collections for a project * * Retrieves all collections associated with a specific project. * * @param {string} projectId - Project ID * @returns {Promise<Collection[]>} Array of collections * @throws {Error} If query fails * * @example * const collections = await collectionsService.getCollectionsByProject('project-id'); */ getCollectionsByProject(projectId: string): Promise<Collection$1[]>; /** * Get collections by project ID * * Alias for getCollectionsByProject. Retrieves all collections for a project. * * @param {string} projectId - Project ID * @returns {Promise<Collection[]>} Array of collections * @throws {Error} If query fails * * @example * const collections = await collectionsService.getProjectCollections('project-id'); */ getProjectCollections(projectId: string): Promise<Collection$1[]>; /** * Get a collection by ID or name * * Retrieves a single collection by its ID (UUID) or name (case-insensitive) within a project. * Supports both UUID lookup and case-insensitive name lookup. * * @param {string} projectId - Project ID * @param {string} collectionId - Collection ID (UUID) or name * @returns {Promise<Collection | null>} Collection or null if not found * @throws {Error} If query fails * * @example * const collection = await collectionsService.getCollection('project-id', 'collection-id'); * const collectionByName = await collectionsService.getCollection('project-id', 'test_collection'); */ getCollection(projectId: string, collectionId: string): Promise<Collection$1 | null>; /** * Update a collection * * Updates collection metadata (name, description, settings) without changing schema. * * @param {string} projectId - Project ID * @param {string} collectionId -