UNPKG

@insforge/sdk

Version:

TypeScript SDK for InsForge Backend-as-a-Service platform

1 lines 69.8 kB
{"version":3,"sources":["../src/types.ts","../src/lib/http-client.ts","../src/lib/token-manager.ts","../src/modules/database-postgrest.ts","../src/modules/auth.ts","../src/modules/storage.ts","../src/modules/ai.ts","../src/modules/functions.ts","../src/client.ts","../src/index.ts"],"sourcesContent":["/**\n * InsForge SDK Types - only SDK-specific types here\n * Use @insforge/shared-schemas directly for API types\n */\n\nimport type { UserSchema } from '@insforge/shared-schemas';\n\nexport interface InsForgeConfig {\n /**\n * The base URL of the InsForge backend API\n * @default \"http://localhost:7130\"\n */\n baseUrl?: string;\n\n /**\n * Anonymous API key (optional)\n * Used for public/unauthenticated requests when no user token is set\n */\n anonKey?: string;\n\n /**\n * Edge Function Token (optional)\n * Use this when running in edge functions/serverless with a user's JWT token\n * This token will be used for all authenticated requests\n */\n edgeFunctionToken?: string;\n\n /**\n * Custom fetch implementation (useful for Node.js environments)\n */\n fetch?: typeof fetch;\n\n /**\n * Storage adapter for persisting tokens\n */\n storage?: TokenStorage;\n\n /**\n * Whether to automatically refresh tokens before they expire\n * @default true\n */\n autoRefreshToken?: boolean;\n\n /**\n * Whether to persist session in storage\n * @default true\n */\n persistSession?: boolean;\n\n /**\n * Custom headers to include with every request\n */\n headers?: Record<string, string>;\n}\n\nexport interface TokenStorage {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n removeItem(key: string): void | Promise<void>;\n}\n\nexport interface AuthSession {\n user: UserSchema;\n accessToken: string;\n expiresAt?: Date;\n}\n\nexport interface ApiError {\n error: string;\n message: string;\n statusCode: number;\n nextActions?: string;\n}\n\nexport class InsForgeError extends Error {\n public statusCode: number;\n public error: string;\n public nextActions?: string;\n\n constructor(message: string, statusCode: number, error: string, nextActions?: string) {\n super(message);\n this.name = 'InsForgeError';\n this.statusCode = statusCode;\n this.error = error;\n this.nextActions = nextActions;\n }\n\n static fromApiError(apiError: ApiError): InsForgeError {\n return new InsForgeError(\n apiError.message,\n apiError.statusCode,\n apiError.error,\n apiError.nextActions\n );\n }\n}","import { InsForgeConfig, ApiError, InsForgeError } from '../types';\n\nexport interface RequestOptions extends RequestInit {\n params?: Record<string, string>;\n}\n\nexport class HttpClient {\n public readonly baseUrl: string;\n public readonly fetch: typeof fetch;\n private defaultHeaders: Record<string, string>;\n private anonKey: string | undefined;\n private userToken: string | null = null;\n\n constructor(config: InsForgeConfig) {\n this.baseUrl = config.baseUrl || 'http://localhost:7130';\n // Properly bind fetch to maintain its context\n this.fetch = config.fetch || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined as any);\n this.anonKey = config.anonKey;\n this.defaultHeaders = {\n ...config.headers,\n };\n\n if (!this.fetch) {\n throw new Error(\n 'Fetch is not available. Please provide a fetch implementation in the config.'\n );\n }\n }\n\n private buildUrl(path: string, params?: Record<string, string>): string {\n const url = new URL(path, this.baseUrl);\n if (params) {\n Object.entries(params).forEach(([key, value]) => {\n // For select parameter, preserve the exact formatting by normalizing whitespace\n // This ensures PostgREST relationship queries work correctly\n if (key === 'select') {\n // Normalize multiline select strings for PostgREST:\n // 1. Replace all whitespace (including newlines) with single space\n // 2. Remove spaces inside parentheses for proper PostgREST syntax\n // 3. Keep spaces after commas at the top level for readability\n let normalizedValue = value.replace(/\\s+/g, ' ').trim();\n \n // Fix spaces around parentheses and inside them\n normalizedValue = normalizedValue\n .replace(/\\s*\\(\\s*/g, '(') // Remove spaces around opening parens\n .replace(/\\s*\\)\\s*/g, ')') // Remove spaces around closing parens\n .replace(/\\(\\s+/g, '(') // Remove spaces after opening parens\n .replace(/\\s+\\)/g, ')') // Remove spaces before closing parens\n .replace(/,\\s+(?=[^()]*\\))/g, ','); // Remove spaces after commas inside parens\n \n url.searchParams.append(key, normalizedValue);\n } else {\n url.searchParams.append(key, value);\n }\n });\n }\n return url.toString();\n }\n\n async request<T>(\n method: string,\n path: string,\n options: RequestOptions = {}\n ): Promise<T> {\n const { params, headers = {}, body, ...fetchOptions } = options;\n \n const url = this.buildUrl(path, params);\n \n const requestHeaders: Record<string, string> = {\n ...this.defaultHeaders,\n };\n \n // Set Authorization header: prefer user token, fallback to anon key\n const authToken = this.userToken || this.anonKey;\n if (authToken) {\n requestHeaders['Authorization'] = `Bearer ${authToken}`;\n }\n \n // Handle body serialization\n let processedBody: any;\n if (body !== undefined) {\n // Check if body is FormData (for file uploads)\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\n // Don't set Content-Type for FormData, let browser set it with boundary\n processedBody = body;\n } else {\n // JSON body\n if (method !== 'GET') {\n requestHeaders['Content-Type'] = 'application/json;charset=UTF-8';\n }\n processedBody = JSON.stringify(body);\n }\n }\n \n Object.assign(requestHeaders, headers);\n \n const response = await this.fetch(url, {\n method,\n headers: requestHeaders,\n body: processedBody,\n ...fetchOptions,\n });\n\n // Handle 204 No Content\n if (response.status === 204) {\n return undefined as T;\n }\n\n // Try to parse JSON response\n let data: any;\n const contentType = response.headers.get('content-type');\n // Check for any JSON content type (including PostgREST's vnd.pgrst.object+json)\n if (contentType?.includes('json')) {\n data = await response.json();\n } else {\n // For non-JSON responses, return text\n data = await response.text();\n }\n\n // Handle errors\n if (!response.ok) {\n if (data && typeof data === 'object' && 'error' in data) {\n // Add the HTTP status code if not already in the data\n if (!data.statusCode && !data.status) {\n data.statusCode = response.status;\n }\n const error = InsForgeError.fromApiError(data as ApiError);\n // Preserve all additional fields from the error response\n Object.keys(data).forEach(key => {\n if (key !== 'error' && key !== 'message' && key !== 'statusCode') {\n (error as any)[key] = data[key];\n }\n });\n throw error;\n }\n throw new InsForgeError(\n `Request failed: ${response.statusText}`,\n response.status,\n 'REQUEST_FAILED'\n );\n }\n\n return data as T;\n }\n\n get<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('GET', path, options);\n }\n\n post<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\n return this.request<T>('POST', path, { ...options, body });\n }\n\n put<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\n return this.request<T>('PUT', path, { ...options, body });\n }\n\n patch<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\n return this.request<T>('PATCH', path, { ...options, body });\n }\n\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\n return this.request<T>('DELETE', path, options);\n }\n\n setAuthToken(token: string | null) {\n this.userToken = token;\n }\n\n getHeaders(): Record<string, string> {\n const headers = { ...this.defaultHeaders };\n \n // Include Authorization header if token is available (same logic as request method)\n const authToken = this.userToken || this.anonKey;\n if (authToken) {\n headers['Authorization'] = `Bearer ${authToken}`;\n }\n \n return headers;\n }\n}","import { TokenStorage, AuthSession } from '../types';\n\nconst TOKEN_KEY = 'insforge-auth-token';\nconst USER_KEY = 'insforge-auth-user';\n\nexport class TokenManager {\n private storage: TokenStorage;\n\n constructor(storage?: TokenStorage) {\n if (storage) {\n // Use provided storage\n this.storage = storage;\n } else if (typeof window !== 'undefined' && window.localStorage) {\n // Browser: use localStorage\n this.storage = window.localStorage;\n } else {\n // Node.js: use in-memory storage\n const store = new Map<string, string>();\n this.storage = {\n getItem: (key: string) => store.get(key) || null,\n setItem: (key: string, value: string) => { store.set(key, value); },\n removeItem: (key: string) => { store.delete(key); }\n };\n }\n }\n\n saveSession(session: AuthSession): void {\n this.storage.setItem(TOKEN_KEY, session.accessToken);\n this.storage.setItem(USER_KEY, JSON.stringify(session.user));\n }\n\n getSession(): AuthSession | null {\n const token = this.storage.getItem(TOKEN_KEY);\n const userStr = this.storage.getItem(USER_KEY);\n\n if (!token || !userStr) {\n return null;\n }\n\n try {\n const user = JSON.parse(userStr as string);\n return { accessToken: token as string, user };\n } catch {\n this.clearSession();\n return null;\n }\n }\n\n getAccessToken(): string | null {\n const token = this.storage.getItem(TOKEN_KEY);\n return typeof token === 'string' ? token : null;\n }\n\n clearSession(): void {\n this.storage.removeItem(TOKEN_KEY);\n this.storage.removeItem(USER_KEY);\n }\n}","/**\n * Database module using @supabase/postgrest-js\n * Complete replacement for custom QueryBuilder with full PostgREST features\n */\n\nimport { PostgrestClient } from '@supabase/postgrest-js';\nimport { HttpClient } from '../lib/http-client';\nimport { TokenManager } from '../lib/token-manager';\n\n\n/**\n * Custom fetch that transforms URLs and adds auth\n */\nfunction createInsForgePostgrestFetch(\n httpClient: HttpClient,\n tokenManager: TokenManager\n): typeof fetch {\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const url = typeof input === 'string' ? input : input.toString();\n const urlObj = new URL(url);\n \n // Extract table name from pathname\n // postgrest-js sends: http://dummy/tablename?params\n // We need: http://localhost:7130/api/database/records/tablename?params\n const tableName = urlObj.pathname.slice(1); // Remove leading /\n \n // Build InsForge URL\n const insforgeUrl = `${httpClient.baseUrl}/api/database/records/${tableName}${urlObj.search}`;\n \n // Get auth token from TokenManager or HttpClient\n const token = tokenManager.getAccessToken();\n const httpHeaders = httpClient.getHeaders();\n const authToken = token || httpHeaders['Authorization']?.replace('Bearer ', '');\n \n // Prepare headers\n const headers = new Headers(init?.headers);\n if (authToken && !headers.has('Authorization')) {\n headers.set('Authorization', `Bearer ${authToken}`);\n }\n \n // Make the actual request using native fetch\n const response = await fetch(insforgeUrl, {\n ...init,\n headers\n });\n \n return response;\n };\n}\n\n/**\n * Database client using postgrest-js\n * Drop-in replacement with FULL PostgREST capabilities\n */\nexport class Database {\n private postgrest: PostgrestClient<any, any, any>;\n \n constructor(httpClient: HttpClient, tokenManager: TokenManager) {\n // Create postgrest client with custom fetch\n this.postgrest = new PostgrestClient<any, any, any>('http://dummy', {\n fetch: createInsForgePostgrestFetch(httpClient, tokenManager),\n headers: {}\n });\n }\n \n /**\n * Create a query builder for a table\n * \n * @example\n * // Basic query\n * const { data, error } = await client.database\n * .from('posts')\n * .select('*')\n * .eq('user_id', userId);\n * \n * // With count (Supabase style!)\n * const { data, error, count } = await client.database\n * .from('posts')\n * .select('*', { count: 'exact' })\n * .range(0, 9);\n * \n * // Just get count, no data\n * const { count } = await client.database\n * .from('posts')\n * .select('*', { count: 'exact', head: true });\n * \n * // Complex queries with OR\n * const { data } = await client.database\n * .from('posts')\n * .select('*, users!inner(*)')\n * .or('status.eq.active,status.eq.pending');\n * \n * // All features work:\n * - Nested selects\n * - Foreign key expansion \n * - OR/AND/NOT conditions\n * - Count with head\n * - Range pagination\n * - Upserts\n */\n from(table: string) {\n // Return postgrest query builder with all features\n return this.postgrest.from(table);\n }\n}","/**\n * Auth module for InsForge SDK\n * Uses shared schemas for type safety\n */\n\nimport { HttpClient } from '../lib/http-client';\nimport { TokenManager } from '../lib/token-manager';\nimport { AuthSession, InsForgeError } from '../types';\nimport { Database } from './database-postgrest';\n\nimport type {\n CreateUserRequest,\n CreateUserResponse,\n CreateSessionRequest,\n CreateSessionResponse,\n GetCurrentSessionResponse,\n GetOauthUrlResponse,\n} from '@insforge/shared-schemas';\n\nexport class Auth {\n private database: Database;\n \n constructor(\n private http: HttpClient,\n private tokenManager: TokenManager\n ) {\n this.database = new Database(http, tokenManager);\n \n // Auto-detect OAuth callback parameters in the URL\n this.detectOAuthCallback();\n }\n\n /**\n * Automatically detect and handle OAuth callback parameters in the URL\n * This runs on initialization to seamlessly complete the OAuth flow\n * Matches the backend's OAuth callback response (backend/src/api/routes/auth.ts:540-544)\n */\n private detectOAuthCallback(): void {\n // Only run in browser environment\n if (typeof window === 'undefined') return;\n \n try {\n const params = new URLSearchParams(window.location.search);\n \n // Backend returns: access_token, user_id, email, name (optional)\n const accessToken = params.get('access_token');\n const userId = params.get('user_id');\n const email = params.get('email');\n const name = params.get('name');\n \n // Check if we have OAuth callback parameters\n if (accessToken && userId && email) {\n // Create session with the data from backend\n const session: AuthSession = {\n accessToken,\n user: {\n id: userId,\n email: email,\n name: name || '',\n // These fields are not provided by backend OAuth callback\n // They'll be populated when calling getCurrentUser()\n emailVerified: false,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n } as any,\n };\n \n // Save session and set auth token\n this.tokenManager.saveSession(session);\n this.http.setAuthToken(accessToken);\n \n // Clean up the URL to remove sensitive parameters\n const url = new URL(window.location.href);\n url.searchParams.delete('access_token');\n url.searchParams.delete('user_id');\n url.searchParams.delete('email');\n url.searchParams.delete('name');\n \n // Also handle error case from backend (line 581)\n if (params.has('error')) {\n url.searchParams.delete('error');\n }\n \n // Replace URL without adding to browser history\n window.history.replaceState({}, document.title, url.toString());\n }\n } catch (error) {\n // Silently continue - don't break initialization\n console.debug('OAuth callback detection skipped:', error);\n }\n }\n\n /**\n * Sign up a new user\n */\n async signUp(request: CreateUserRequest): Promise<{\n data: CreateUserResponse | null;\n error: InsForgeError | null;\n }> {\n try {\n const response = await this.http.post<CreateUserResponse>('/api/auth/users', request);\n \n // Save session internally\n const session: AuthSession = {\n accessToken: response.accessToken,\n user: response.user,\n };\n this.tokenManager.saveSession(session);\n this.http.setAuthToken(response.accessToken);\n\n return { \n data: response,\n error: null \n };\n } catch (error) {\n // Pass through API errors unchanged\n if (error instanceof InsForgeError) {\n return { data: null, error };\n }\n \n // Generic fallback for unexpected errors\n return { \n data: null, \n error: new InsForgeError(\n error instanceof Error ? error.message : 'An unexpected error occurred during sign up',\n 500,\n 'UNEXPECTED_ERROR'\n )\n };\n }\n }\n\n /**\n * Sign in with email and password\n */\n async signInWithPassword(request: CreateSessionRequest): Promise<{\n data: CreateSessionResponse | null;\n error: InsForgeError | null;\n }> {\n try {\n const response = await this.http.post<CreateSessionResponse>('/api/auth/sessions', request);\n \n // Save session internally\n const session: AuthSession = {\n accessToken: response.accessToken,\n user: response.user,\n };\n this.tokenManager.saveSession(session);\n this.http.setAuthToken(response.accessToken);\n\n return { \n data: response,\n error: null \n };\n } catch (error) {\n // Pass through API errors unchanged\n if (error instanceof InsForgeError) {\n return { data: null, error };\n }\n \n // Generic fallback for unexpected errors\n return { \n data: null, \n error: new InsForgeError(\n 'An unexpected error occurred during sign in',\n 500,\n 'UNEXPECTED_ERROR'\n )\n };\n }\n }\n\n /**\n * Sign in with OAuth provider\n */\n async signInWithOAuth(options: {\n provider: 'google' | 'github';\n redirectTo?: string;\n skipBrowserRedirect?: boolean;\n }): Promise<{\n data: { url?: string; provider?: string };\n error: InsForgeError | null;\n }> {\n try {\n const { provider, redirectTo, skipBrowserRedirect } = options;\n \n const params = redirectTo \n ? { redirect_uri: redirectTo } \n : undefined;\n \n const endpoint = `/api/auth/oauth/${provider}`;\n const response = await this.http.get<GetOauthUrlResponse>(endpoint, { params });\n \n // Automatically redirect in browser unless told not to\n if (typeof window !== 'undefined' && !skipBrowserRedirect) {\n window.location.href = response.authUrl;\n return { data: {}, error: null };\n }\n\n return { \n data: { \n url: response.authUrl,\n provider \n }, \n error: null \n };\n } catch (error) {\n // Pass through API errors unchanged\n if (error instanceof InsForgeError) {\n return { data: {}, error };\n }\n \n // Generic fallback for unexpected errors\n return { \n data: {}, \n error: new InsForgeError(\n 'An unexpected error occurred during OAuth initialization',\n 500,\n 'UNEXPECTED_ERROR'\n )\n };\n }\n }\n\n /**\n * Sign out the current user\n */\n async signOut(): Promise<{ error: InsForgeError | null }> {\n try {\n this.tokenManager.clearSession();\n this.http.setAuthToken(null);\n return { error: null };\n } catch (error) {\n return { \n error: new InsForgeError(\n 'Failed to sign out',\n 500,\n 'SIGNOUT_ERROR'\n )\n };\n }\n }\n\n /**\n * Get the current user with full profile information\n * Returns both auth info (id, email, role) and profile data (nickname, avatar_url, bio, etc.)\n */\n async getCurrentUser(): Promise<{\n data: { user: any; profile: any } | null;\n error: any | null;\n }> {\n try {\n // Check if we have a token\n const session = this.tokenManager.getSession();\n if (!session?.accessToken) {\n return { data: null, error: null };\n }\n\n // Call the API for auth info\n this.http.setAuthToken(session.accessToken);\n const authResponse = await this.http.get<GetCurrentSessionResponse>('/api/auth/sessions/current');\n \n // Get the user's profile using query builder\n const { data: profile, error: profileError } = await this.database\n .from('users')\n .select('*')\n .eq('id', authResponse.user.id)\n .single();\n \n // For database errors, return PostgrestError directly\n if (profileError && (profileError as any).code !== 'PGRST116') { // PGRST116 = not found\n return { data: null, error: profileError };\n }\n \n return {\n data: {\n user: authResponse.user,\n profile: profile\n },\n error: null\n };\n } catch (error) {\n // If unauthorized, clear session\n if (error instanceof InsForgeError && error.statusCode === 401) {\n await this.signOut();\n return { data: null, error: null };\n }\n \n // Pass through all other errors unchanged\n if (error instanceof InsForgeError) {\n return { data: null, error };\n }\n \n // Generic fallback for unexpected errors\n return { \n data: null, \n error: new InsForgeError(\n 'An unexpected error occurred while fetching user',\n 500,\n 'UNEXPECTED_ERROR'\n )\n };\n }\n }\n\n /**\n * Get any user's profile by ID\n * Returns profile information from the users table (nickname, avatar_url, bio, etc.)\n */\n async getProfile(userId: string): Promise<{\n data: any | null;\n error: any | null;\n }> {\n const { data, error } = await this.database\n .from('users')\n .select('*')\n .eq('id', userId)\n .single();\n \n // Handle not found as null, not error\n if (error && (error as any).code === 'PGRST116') {\n return { data: null, error: null };\n }\n \n // Return PostgrestError directly for database operations\n return { data, error };\n }\n\n /**\n * Get the current session (only session data, no API call)\n * Returns the stored JWT token and basic user info from local storage\n */\n getCurrentSession(): {\n data: { session: AuthSession | null };\n error: InsForgeError | null;\n } {\n try {\n const session = this.tokenManager.getSession();\n \n if (session?.accessToken) {\n this.http.setAuthToken(session.accessToken);\n return { data: { session }, error: null };\n }\n\n return { data: { session: null }, error: null };\n } catch (error) {\n // Pass through API errors unchanged\n if (error instanceof InsForgeError) {\n return { data: { session: null }, error };\n }\n \n // Generic fallback for unexpected errors\n return { \n data: { session: null }, \n error: new InsForgeError(\n 'An unexpected error occurred while getting session',\n 500,\n 'UNEXPECTED_ERROR'\n )\n };\n }\n }\n\n /**\n * Set/Update the current user's profile\n * Updates profile information in the users table (nickname, avatar_url, bio, etc.)\n */\n async setProfile(profile: {\n nickname?: string;\n avatar_url?: string;\n bio?: string;\n birthday?: string;\n [key: string]: any;\n }): Promise<{\n data: any | null;\n error: any | null;\n }> {\n // Get current session to get user ID\n const session = this.tokenManager.getSession();\n if (!session?.user?.id) {\n return { \n data: null, \n error: new InsForgeError(\n 'No authenticated user found',\n 401,\n 'UNAUTHENTICATED'\n )\n };\n }\n\n // Update the profile using query builder\n const { data, error } = await this.database\n .from('users')\n .update(profile)\n .eq('id', session.user.id)\n .select()\n .single();\n \n // Return PostgrestError directly for database operations\n return { data, error };\n }\n\n\n}","/**\n * Storage module for InsForge SDK\n * Handles file uploads, downloads, and bucket management\n */\n\nimport { HttpClient } from '../lib/http-client';\nimport { InsForgeError } from '../types';\nimport type { \n StorageFileSchema,\n ListObjectsResponseSchema\n} from '@insforge/shared-schemas';\n\nexport interface StorageResponse<T> {\n data: T | null;\n error: InsForgeError | null;\n}\n\ninterface UploadStrategy {\n method: 'direct' | 'presigned';\n uploadUrl: string;\n fields?: Record<string, string>;\n key: string;\n confirmRequired: boolean;\n confirmUrl?: string;\n expiresAt?: Date;\n}\n\ninterface DownloadStrategy {\n method: 'direct' | 'presigned';\n url: string;\n expiresAt?: Date;\n}\n\n/**\n * Storage bucket operations\n */\nexport class StorageBucket {\n constructor(\n private bucketName: string,\n private http: HttpClient\n ) {}\n\n /**\n * Upload a file with a specific key\n * Uses the upload strategy from backend (direct or presigned)\n * @param path - The object key/path\n * @param file - File or Blob to upload\n */\n async upload(\n path: string,\n file: File | Blob\n ): Promise<StorageResponse<StorageFileSchema>> {\n try {\n // Get upload strategy from backend - this is required\n const strategyResponse = await this.http.post<UploadStrategy>(\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\n {\n filename: path,\n contentType: file.type || 'application/octet-stream',\n size: file.size\n }\n );\n\n // Use presigned URL if available\n if (strategyResponse.method === 'presigned') {\n return await this.uploadWithPresignedUrl(strategyResponse, file);\n }\n\n // Use direct upload if strategy says so\n if (strategyResponse.method === 'direct') {\n const formData = new FormData();\n formData.append('file', file);\n\n const response = await this.http.request<StorageFileSchema>(\n 'PUT',\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`,\n {\n body: formData as any,\n headers: {\n // Don't set Content-Type, let browser set multipart boundary\n }\n }\n );\n\n return { data: response, error: null };\n }\n\n throw new InsForgeError(\n `Unsupported upload method: ${strategyResponse.method}`,\n 500,\n 'STORAGE_ERROR'\n );\n } catch (error) {\n return { \n data: null, \n error: error instanceof InsForgeError ? error : new InsForgeError(\n 'Upload failed',\n 500,\n 'STORAGE_ERROR'\n )\n };\n }\n }\n\n /**\n * Upload a file with auto-generated key\n * Uses the upload strategy from backend (direct or presigned)\n * @param file - File or Blob to upload\n */\n async uploadAuto(\n file: File | Blob\n ): Promise<StorageResponse<StorageFileSchema>> {\n try {\n const filename = file instanceof File ? file.name : 'file';\n \n // Get upload strategy from backend - this is required\n const strategyResponse = await this.http.post<UploadStrategy>(\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\n {\n filename,\n contentType: file.type || 'application/octet-stream',\n size: file.size\n }\n );\n\n // Use presigned URL if available\n if (strategyResponse.method === 'presigned') {\n return await this.uploadWithPresignedUrl(strategyResponse, file);\n }\n\n // Use direct upload if strategy says so\n if (strategyResponse.method === 'direct') {\n const formData = new FormData();\n formData.append('file', file);\n\n const response = await this.http.request<StorageFileSchema>(\n 'POST',\n `/api/storage/buckets/${this.bucketName}/objects`,\n {\n body: formData as any,\n headers: {\n // Don't set Content-Type, let browser set multipart boundary\n }\n }\n );\n\n return { data: response, error: null };\n }\n\n throw new InsForgeError(\n `Unsupported upload method: ${strategyResponse.method}`,\n 500,\n 'STORAGE_ERROR'\n );\n } catch (error) {\n return { \n data: null, \n error: error instanceof InsForgeError ? error : new InsForgeError(\n 'Upload failed',\n 500,\n 'STORAGE_ERROR'\n )\n };\n }\n }\n\n /**\n * Internal method to handle presigned URL uploads\n */\n private async uploadWithPresignedUrl(\n strategy: UploadStrategy,\n file: File | Blob\n ): Promise<StorageResponse<StorageFileSchema>> {\n try {\n // Upload to presigned URL (e.g., S3)\n const formData = new FormData();\n \n // Add all fields from the presigned URL\n if (strategy.fields) {\n Object.entries(strategy.fields).forEach(([key, value]) => {\n formData.append(key, value);\n });\n }\n \n // File must be the last field for S3\n formData.append('file', file);\n\n const uploadResponse = await fetch(strategy.uploadUrl, {\n method: 'POST',\n body: formData\n });\n\n if (!uploadResponse.ok) {\n throw new InsForgeError(\n `Upload to storage failed: ${uploadResponse.statusText}`,\n uploadResponse.status,\n 'STORAGE_ERROR'\n );\n }\n\n // Confirm upload with backend if required\n if (strategy.confirmRequired && strategy.confirmUrl) {\n const confirmResponse = await this.http.post<StorageFileSchema>(\n strategy.confirmUrl,\n {\n size: file.size,\n contentType: file.type || 'application/octet-stream'\n }\n );\n\n return { data: confirmResponse, error: null };\n }\n\n // If no confirmation required, return basic file info\n return {\n data: {\n key: strategy.key,\n bucket: this.bucketName,\n size: file.size,\n mimeType: file.type || 'application/octet-stream',\n uploadedAt: new Date().toISOString(),\n url: this.getPublicUrl(strategy.key)\n } as StorageFileSchema,\n error: null\n };\n } catch (error) {\n throw error instanceof InsForgeError ? error : new InsForgeError(\n 'Presigned upload failed',\n 500,\n 'STORAGE_ERROR'\n );\n }\n }\n\n /**\n * Download a file\n * Uses the download strategy from backend (direct or presigned)\n * @param path - The object key/path\n * Returns the file as a Blob\n */\n async download(path: string): Promise<{ data: Blob | null; error: InsForgeError | null }> {\n try {\n // Get download strategy from backend - this is required\n const strategyResponse = await this.http.post<DownloadStrategy>(\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}/download-strategy`,\n { expiresIn: 3600 }\n );\n\n // Use URL from strategy\n const downloadUrl = strategyResponse.url;\n \n // Download from the URL\n const headers: HeadersInit = {};\n \n // Only add auth header for direct downloads (not presigned URLs)\n if (strategyResponse.method === 'direct') {\n Object.assign(headers, this.http.getHeaders());\n }\n \n const response = await fetch(downloadUrl, {\n method: 'GET',\n headers\n });\n\n if (!response.ok) {\n try {\n const error = await response.json();\n throw InsForgeError.fromApiError(error);\n } catch {\n throw new InsForgeError(\n `Download failed: ${response.statusText}`,\n response.status,\n 'STORAGE_ERROR'\n );\n }\n }\n\n const blob = await response.blob();\n return { data: blob, error: null };\n } catch (error) {\n return { \n data: null, \n error: error instanceof InsForgeError ? error : new InsForgeError(\n 'Download failed',\n 500,\n 'STORAGE_ERROR'\n )\n };\n }\n }\n\n /**\n * Get public URL for a file\n * @param path - The object key/path\n */\n getPublicUrl(path: string): string {\n return `${this.http.baseUrl}/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`;\n }\n\n /**\n * List objects in the bucket\n * @param prefix - Filter by key prefix\n * @param search - Search in file names\n * @param limit - Maximum number of results (default: 100, max: 1000)\n * @param offset - Number of results to skip\n */\n async list(options?: {\n prefix?: string;\n search?: string;\n limit?: number;\n offset?: number;\n }): Promise<StorageResponse<ListObjectsResponseSchema>> {\n try {\n const params: Record<string, string> = {};\n \n if (options?.prefix) params.prefix = options.prefix;\n if (options?.search) params.search = options.search;\n if (options?.limit) params.limit = options.limit.toString();\n if (options?.offset) params.offset = options.offset.toString();\n\n const response = await this.http.get<ListObjectsResponseSchema>(\n `/api/storage/buckets/${this.bucketName}/objects`,\n { params }\n );\n\n return { data: response, error: null };\n } catch (error) {\n return { \n data: null, \n error: error instanceof InsForgeError ? error : new InsForgeError(\n 'List failed',\n 500,\n 'STORAGE_ERROR'\n )\n };\n }\n }\n\n /**\n * Delete a file\n * @param path - The object key/path\n */\n async remove(path: string): Promise<StorageResponse<{ message: string }>> {\n try {\n const response = await this.http.delete<{ message: string }>(\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`\n );\n\n return { data: response, error: null };\n } catch (error) {\n return { \n data: null, \n error: error instanceof InsForgeError ? error : new InsForgeError(\n 'Delete failed',\n 500,\n 'STORAGE_ERROR'\n )\n };\n }\n }\n}\n\n/**\n * Storage module for file operations\n */\nexport class Storage {\n constructor(private http: HttpClient) {}\n\n /**\n * Get a bucket instance for operations\n * @param bucketName - Name of the bucket\n */\n from(bucketName: string): StorageBucket {\n return new StorageBucket(bucketName, this.http);\n }\n}","/**\n * AI Module for Insforge SDK\n * Response format roughly matches OpenAI SDK for compatibility\n *\n * The backend handles all the complexity of different AI providers\n * and returns a unified format. This SDK transforms responses to match OpenAI-like format.\n */\n\nimport { HttpClient } from \"../lib/http-client\";\nimport {\n ChatCompletionRequest,\n ChatCompletionResponse,\n ImageGenerationRequest,\n ImageGenerationResponse,\n} from \"@insforge/shared-schemas\";\n\nexport class AI {\n public readonly chat: Chat;\n public readonly images: Images;\n\n constructor(private http: HttpClient) {\n this.chat = new Chat(http);\n this.images = new Images(http);\n }\n}\n\nclass Chat {\n public readonly completions: ChatCompletions;\n\n constructor(http: HttpClient) {\n this.completions = new ChatCompletions(http);\n }\n}\n\nclass ChatCompletions {\n constructor(private http: HttpClient) {}\n\n /**\n * Create a chat completion - OpenAI-like response format\n *\n * @example\n * ```typescript\n * // Non-streaming\n * const completion = await client.ai.chat.completions.create({\n * model: 'gpt-4',\n * messages: [{ role: 'user', content: 'Hello!' }]\n * });\n * console.log(completion.choices[0].message.content);\n *\n * // With images\n * const response = await client.ai.chat.completions.create({\n * model: 'gpt-4-vision',\n * messages: [{\n * role: 'user',\n * content: 'What is in this image?',\n * images: [{ url: 'https://example.com/image.jpg' }]\n * }]\n * });\n *\n * // Streaming - returns async iterable\n * const stream = await client.ai.chat.completions.create({\n * model: 'gpt-4',\n * messages: [{ role: 'user', content: 'Tell me a story' }],\n * stream: true\n * });\n *\n * for await (const chunk of stream) {\n * if (chunk.choices[0]?.delta?.content) {\n * process.stdout.write(chunk.choices[0].delta.content);\n * }\n * }\n * ```\n */\n async create(params: ChatCompletionRequest): Promise<any> {\n // Backend already expects camelCase, no transformation needed\n const backendParams = {\n model: params.model,\n messages: params.messages,\n temperature: params.temperature,\n maxTokens: params.maxTokens,\n topP: params.topP,\n stream: params.stream,\n };\n\n // For streaming, return an async iterable that yields OpenAI-like chunks\n if (params.stream) {\n const headers = this.http.getHeaders();\n headers[\"Content-Type\"] = \"application/json\";\n\n const response = await this.http.fetch(\n `${this.http.baseUrl}/api/ai/chat/completion`,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify(backendParams),\n }\n );\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error || \"Stream request failed\");\n }\n\n // Return async iterable that parses SSE and transforms to OpenAI-like format\n return this.parseSSEStream(response, params.model);\n }\n\n // Non-streaming: transform response to OpenAI-like format\n const response: ChatCompletionResponse = await this.http.post(\n \"/api/ai/chat/completion\",\n backendParams\n );\n\n // Transform to OpenAI-like format\n const content = response.text || \"\";\n\n return {\n id: `chatcmpl-${Date.now()}`,\n object: \"chat.completion\",\n created: Math.floor(Date.now() / 1000),\n model: response.metadata?.model,\n choices: [\n {\n index: 0,\n message: {\n role: \"assistant\",\n content,\n },\n finish_reason: \"stop\",\n },\n ],\n usage: response.metadata?.usage || {\n prompt_tokens: 0,\n completion_tokens: 0,\n total_tokens: 0,\n },\n };\n }\n\n /**\n * Parse SSE stream into async iterable of OpenAI-like chunks\n */\n private async *parseSSEStream(\n response: Response,\n model: string\n ): AsyncIterableIterator<any> {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const dataStr = line.slice(6).trim();\n if (dataStr) {\n try {\n const data = JSON.parse(dataStr);\n\n // Transform to OpenAI-like streaming format\n if (data.chunk || data.content) {\n yield {\n id: `chatcmpl-${Date.now()}`,\n object: \"chat.completion.chunk\",\n created: Math.floor(Date.now() / 1000),\n model,\n choices: [\n {\n index: 0,\n delta: {\n content: data.chunk || data.content,\n },\n finish_reason: data.done ? \"stop\" : null,\n },\n ],\n };\n }\n\n // If we received the done signal, we can stop\n if (data.done) {\n reader.releaseLock();\n return;\n }\n } catch (e) {\n // Skip invalid JSON\n console.warn(\"Failed to parse SSE data:\", dataStr);\n }\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n}\n\nclass Images {\n constructor(private http: HttpClient) {}\n\n /**\n * Generate images - OpenAI-like response format\n *\n * @example\n * ```typescript\n * // Text-to-image\n * const response = await client.ai.images.generate({\n * model: 'dall-e-3',\n * prompt: 'A sunset over mountains',\n * });\n * console.log(response.images[0].url);\n *\n * // Image-to-image (with input images)\n * const response = await client.ai.images.generate({\n * model: 'stable-diffusion-xl',\n * prompt: 'Transform this into a watercolor painting',\n * images: [\n * { url: 'https://example.com/input.jpg' },\n * // or base64-encoded Data URI:\n * { url: 'data:image/jpeg;base64,/9j/4AAQ...' }\n * ]\n * });\n * ```\n */\n async generate(params: ImageGenerationRequest): Promise<any> {\n const response: ImageGenerationResponse = await this.http.post(\n \"/api/ai/image/generation\",\n params\n );\n \n // Build data array based on response content\n let data: Array<{ b64_json?: string; content?: string }> = [];\n \n if (response.images && response.images.length > 0) {\n // Has images - extract base64 and include text\n data = response.images.map(img => ({\n b64_json: img.imageUrl.replace(/^data:image\\/\\w+;base64,/, ''),\n content: response.text\n }));\n } else if (response.text) {\n // Text-only response\n data = [{ content: response.text }];\n }\n \n // Return OpenAI-compatible format\n return {\n created: Math.floor(Date.now() / 1000),\n data,\n ...(response.metadata?.usage && {\n usage: {\n total_tokens: response.metadata.usage.totalTokens || 0,\n input_tokens: response.metadata.usage.promptTokens || 0,\n output_tokens: response.metadata.usage.completionTokens || 0,\n }\n })\n };\n }\n}\n","import { HttpClient } from '../lib/http-client';\n\nexport interface FunctionInvokeOptions {\n /**\n * The body of the request\n */\n body?: any;\n \n /**\n * Custom headers to send with the request\n */\n headers?: Record<string, string>;\n \n /**\n * HTTP method (default: POST)\n */\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n}\n\n/**\n * Edge Functions client for invoking serverless functions\n * \n * @example\n * ```typescript\n * // Invoke a function with JSON body\n * const { data, error } = await client.functions.invoke('hello-world', {\n * body: { name: 'World' }\n * });\n * \n * // GET request\n * const { data, error } = await client.functions.invoke('get-data', {\n * method: 'GET'\n * });\n * ```\n */\nexport class Functions {\n private http: HttpClient;\n\n constructor(http: HttpClient) {\n this.http = http;\n }\n\n /**\n * Invokes an Edge Function\n * @param slug The function slug to invoke\n * @param options Request options\n */\n async invoke<T = any>(\n slug: string,\n options: FunctionInvokeOptions = {}\n ): Promise<{ data: T | null; error: Error | null }> {\n try {\n const { method = 'POST', body, headers = {} } = options;\n \n // Simple path: /functions/{slug}\n const path = `/functions/${slug}`;\n \n // Use the HTTP client's request method\n const data = await this.http.request<T>(\n method,\n path,\n { body, headers }\n );\n \n return { data, error: null };\n } catch (error: any) {\n // The HTTP client throws InsForgeError with all properties from the response\n // including error, message, details, statusCode, etc.\n // We need to preserve all of that information\n return { \n data: null, \n error: error // Pass through the full error object with all properties\n };\n }\n }\n}","import { InsForgeConfig } from './types';\nimport { HttpClient } from './lib/http-client';\nimport { TokenManager } from './lib/token-manager';\nimport { Auth } from './modules/auth';\nimport { Database } from './modules/database-postgrest';\nimport { Storage } from './modules/storage';\nimport { AI } from './modules/ai';\nimport { Functions } from './modules/functions';\n\n/**\n * Main InsForge SDK Client\n * \n * @example\n * ```typescript\n * import { InsForgeClient } from '@insforge/sdk';\n * \n * const client = new InsForgeClient({\n * baseUrl: 'http://localhost:7130'\n * });\n * \n * // Authentication\n * const session = await client.auth.register({\n * email: 'user@example.com',\n * password: 'password123',\n * name: 'John Doe'\n * });\n * \n * // Database operations\n * const { data, error } = await client.database\n * .from('posts')\n * .select('*')\n * .eq('user_id', session.user.id)\n * .order('created_at', { ascending: false })\n * .limit(10);\n * \n * // Insert data\n * const { data: newPost } = await client.database\n * .from('posts')\n * .insert({ title: 'Hello', content: 'World' })\n * .single();\n * \n * // Invoke edge functions\n * const { data, error } = await client.functions.invoke('my-function', {\n * body: { message: 'Hello from SDK' }\n * });\n * ```\n */\nexport class InsForgeClient {\n private http: HttpClient;\n private tokenManager: TokenManager;\n \n public readonly auth: Auth;\n public readonly database: Database;\n public readonly storage: Storage;\n public readonly ai: AI;\n public readonly functions: Functions;\n\n constructor(config: InsForgeConfig = {}) {\n this.http = new HttpClient(config);\n this.tokenManager = new TokenManager(config.storage);\n \n // Check for edge function token\n if (config.edgeFunctionToken) {\n this.http.setAuthToken(config.edgeFunctionToken);\n // Save to token manager so getCurrentUser() works\n this.tokenManager.saveSession({\n accessToken: config.edgeFunctionToken,\n user: {} as any // Will be populated by getCurrentUser()\n });\n }\n \n // Check for existing session in storage\n const existingSession = this.tokenManager.getSession();\n if (existingSession?.accessToken) {\n this.http.setAuthToken(existingSession.accessToken);\n }\n \n this.auth = new Auth(\n this.http,\n this.tokenManager\n );\n \n this.database = new Database(this.http, this.tokenManager);\n this.storage = new Storage(this.http);\n this.ai = new AI(this.http);\n this.functions = new Functions(this.http);\n }\n\n /**\n * Get the underlying HTTP client for custom requests\n * \n * @example\n * ```typescript\n * const httpClient = client.getHttpClient();\n * const customData = await httpClient.get('/api/custom-endpoint');\n * ```\n */\n getHttpClient(): HttpClient {\n return this.http;\n }\n\n /**\n * Future modules will be added here:\n * - database: Database operations\n * - storage: File storage operations\n * - functions: Serverless functions\n * - tables: Table management\n * - metadata: Backend metadata\n */\n}","/**\n * @insforge/sdk - TypeScript SDK for InsForge Backend-as-a-Service\n * \n * @packageDocumentation\n */\n\n// Main client\nexport { InsForgeClient } from './client';\n\n// Types\nexport type {\n InsForgeConfig,\n InsForgeConfig as ClientOptions, // Alias for compatibility\n TokenStorage,\n AuthSession,\n ApiError,\n} from './types';\n\nexport { InsForgeError } from './types';\n\n// Re-export shared schemas that SDK users will need\nexport type {\n UserSchema,\n CreateUserRequest,\n CreateSessionRequest,\n AuthErrorResponse,\n} from '@insforge/shared-schemas';\n\n// Re-export auth module for advanced usage\nexport { Auth } from './modules/auth';\n\n// Re-export database module (using postgrest-js)\nexport { Database } from './modules/database-postgrest';\n// Note: QueryBuilder is no longer exported as we use postgrest-js QueryBuilder internally\n\n// Re-export st