@insforge/sdk 0.0.58-dev.3 → 0.0.58-dev.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -209,7 +209,7 @@ declare class Auth {
209
209
  }>;
210
210
  /**
211
211
  * Get any user's profile by ID
212
- * Returns profile information from the users table (nickname, avatar_url, bio, etc.)
212
+ * Returns profile information from the users table (nickname, avatarUrl, bio, etc.)
213
213
  */
214
214
  getProfile(userId: string): Promise<{
215
215
  data: ProfileSchema | null;
@@ -227,7 +227,7 @@ declare class Auth {
227
227
  };
228
228
  /**
229
229
  * Set/Update the current user's profile
230
- * Updates profile information in the users table (nickname, avatar_url, bio, etc.)
230
+ * Updates profile information in the users table (nickname, avatarUrl, bio, etc.)
231
231
  */
232
232
  setProfile(profile: UpdateProfileSchema): Promise<{
233
233
  data: ProfileSchema | null;
package/dist/index.d.ts CHANGED
@@ -209,7 +209,7 @@ declare class Auth {
209
209
  }>;
210
210
  /**
211
211
  * Get any user's profile by ID
212
- * Returns profile information from the users table (nickname, avatar_url, bio, etc.)
212
+ * Returns profile information from the users table (nickname, avatarUrl, bio, etc.)
213
213
  */
214
214
  getProfile(userId: string): Promise<{
215
215
  data: ProfileSchema | null;
@@ -227,7 +227,7 @@ declare class Auth {
227
227
  };
228
228
  /**
229
229
  * Set/Update the current user's profile
230
- * Updates profile information in the users table (nickname, avatar_url, bio, etc.)
230
+ * Updates profile information in the users table (nickname, avatarUrl, bio, etc.)
231
231
  */
232
232
  setProfile(profile: UpdateProfileSchema): Promise<{
233
233
  data: ProfileSchema | null;
package/dist/index.js CHANGED
@@ -292,6 +292,25 @@ var Database = class {
292
292
  };
293
293
 
294
294
  // src/modules/auth.ts
295
+ function convertDbProfileToSchema(dbProfile) {
296
+ return {
297
+ id: dbProfile.id,
298
+ nickname: dbProfile.nickname,
299
+ avatarUrl: dbProfile.avatar_url,
300
+ bio: dbProfile.bio,
301
+ birthday: dbProfile.birthday,
302
+ createdAt: dbProfile.created_at,
303
+ updatedAt: dbProfile.updated_at
304
+ };
305
+ }
306
+ function convertSchemaToDbProfile(profile) {
307
+ const dbProfile = {};
308
+ if (profile.nickname !== void 0) dbProfile.nickname = profile.nickname;
309
+ if (profile.avatarUrl !== void 0) dbProfile.avatar_url = profile.avatarUrl;
310
+ if (profile.bio !== void 0) dbProfile.bio = profile.bio;
311
+ if (profile.birthday !== void 0) dbProfile.birthday = profile.birthday;
312
+ return dbProfile;
313
+ }
295
314
  var Auth = class {
296
315
  constructor(http, tokenManager) {
297
316
  this.http = http;
@@ -557,7 +576,7 @@ var Auth = class {
557
576
  return {
558
577
  data: {
559
578
  user: authResponse.user,
560
- profile
579
+ profile: profile ? convertDbProfileToSchema(profile) : null
561
580
  },
562
581
  error: null
563
582
  };
@@ -581,14 +600,17 @@ var Auth = class {
581
600
  }
582
601
  /**
583
602
  * Get any user's profile by ID
584
- * Returns profile information from the users table (nickname, avatar_url, bio, etc.)
603
+ * Returns profile information from the users table (nickname, avatarUrl, bio, etc.)
585
604
  */
586
605
  async getProfile(userId) {
587
606
  const { data, error } = await this.database.from("users").select("*").eq("id", userId).single();
588
607
  if (error && error.code === "PGRST116") {
589
608
  return { data: null, error: null };
590
609
  }
591
- return { data, error };
610
+ if (data) {
611
+ return { data: convertDbProfileToSchema(data), error: null };
612
+ }
613
+ return { data: null, error };
592
614
  }
593
615
  /**
594
616
  * Get the current session (only session data, no API call)
@@ -618,7 +640,7 @@ var Auth = class {
618
640
  }
619
641
  /**
620
642
  * Set/Update the current user's profile
621
- * Updates profile information in the users table (nickname, avatar_url, bio, etc.)
643
+ * Updates profile information in the users table (nickname, avatarUrl, bio, etc.)
622
644
  */
623
645
  async setProfile(profile) {
624
646
  const session = this.tokenManager.getSession();
@@ -653,8 +675,12 @@ var Auth = class {
653
675
  this.tokenManager.saveSession(session);
654
676
  }
655
677
  }
656
- const { data, error } = await this.database.from("users").update(profile).eq("id", session.user.id).select().single();
657
- return { data, error };
678
+ const dbProfile = convertSchemaToDbProfile(profile);
679
+ const { data, error } = await this.database.from("users").update(dbProfile).eq("id", session.user.id).select().single();
680
+ if (data) {
681
+ return { data: convertDbProfileToSchema(data), error: null };
682
+ }
683
+ return { data: null, error };
658
684
  }
659
685
  };
660
686
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../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"],"sourcesContent":["/**\r\n * @insforge/sdk - TypeScript SDK for InsForge Backend-as-a-Service\r\n * \r\n * @packageDocumentation\r\n */\r\n\r\n// Main client\r\nexport { InsForgeClient } from './client';\r\n\r\n// Types\r\nexport type {\r\n InsForgeConfig,\r\n InsForgeConfig as ClientOptions, // Alias for compatibility\r\n TokenStorage,\r\n AuthSession,\r\n ApiError,\r\n} from './types';\r\n\r\nexport { InsForgeError } from './types';\r\n\r\n// Re-export shared schemas that SDK users will need\r\nexport type {\r\n UserSchema,\r\n CreateUserRequest,\r\n CreateSessionRequest,\r\n AuthErrorResponse,\r\n} from '@insforge/shared-schemas';\r\n\r\n// Re-export auth module for advanced usage\r\nexport { Auth } from './modules/auth';\r\n\r\n// Re-export database module (using postgrest-js)\r\nexport { Database } from './modules/database-postgrest';\r\n// Note: QueryBuilder is no longer exported as we use postgrest-js QueryBuilder internally\r\n\r\n// Re-export storage module and types\r\nexport { Storage, StorageBucket } from './modules/storage';\r\nexport type { StorageResponse } from './modules/storage';\r\n\r\n// Re-export AI module\r\nexport { AI } from './modules/ai';\r\n\r\n// Re-export Functions module\r\nexport { Functions } from './modules/functions';\r\nexport type { FunctionInvokeOptions } from './modules/functions';\r\n\r\n// Re-export utilities for advanced usage\r\nexport { HttpClient } from './lib/http-client';\r\nexport { TokenManager } from './lib/token-manager';\r\n\r\n// Factory function for creating clients (Supabase-style)\r\nimport { InsForgeClient } from './client';\r\nimport { InsForgeConfig } from './types';\r\n\r\nexport function createClient(config: InsForgeConfig): InsForgeClient {\r\n return new InsForgeClient(config);\r\n}\r\n\r\n// Default export for convenience\r\nexport default InsForgeClient;","/**\r\n * InsForge SDK Types - only SDK-specific types here\r\n * Use @insforge/shared-schemas directly for API types\r\n */\r\n\r\nimport type { UserSchema } from '@insforge/shared-schemas';\r\n\r\nexport interface InsForgeConfig {\r\n /**\r\n * The base URL of the InsForge backend API\r\n * @default \"http://localhost:7130\"\r\n */\r\n baseUrl?: string;\r\n\r\n /**\r\n * Anonymous API key (optional)\r\n * Used for public/unauthenticated requests when no user token is set\r\n */\r\n anonKey?: string;\r\n\r\n /**\r\n * Edge Function Token (optional)\r\n * Use this when running in edge functions/serverless with a user's JWT token\r\n * This token will be used for all authenticated requests\r\n */\r\n edgeFunctionToken?: string;\r\n\r\n /**\r\n * Custom fetch implementation (useful for Node.js environments)\r\n */\r\n fetch?: typeof fetch;\r\n\r\n /**\r\n * Storage adapter for persisting tokens\r\n */\r\n storage?: TokenStorage;\r\n\r\n /**\r\n * Whether to automatically refresh tokens before they expire\r\n * @default true\r\n */\r\n autoRefreshToken?: boolean;\r\n\r\n /**\r\n * Whether to persist session in storage\r\n * @default true\r\n */\r\n persistSession?: boolean;\r\n\r\n /**\r\n * Custom headers to include with every request\r\n */\r\n headers?: Record<string, string>;\r\n}\r\n\r\nexport interface TokenStorage {\r\n getItem(key: string): string | null | Promise<string | null>;\r\n setItem(key: string, value: string): void | Promise<void>;\r\n removeItem(key: string): void | Promise<void>;\r\n}\r\n\r\nexport interface AuthSession {\r\n user: UserSchema;\r\n accessToken: string;\r\n expiresAt?: Date;\r\n}\r\n\r\nexport interface ApiError {\r\n error: string;\r\n message: string;\r\n statusCode: number;\r\n nextActions?: string;\r\n}\r\n\r\nexport class InsForgeError extends Error {\r\n public statusCode: number;\r\n public error: string;\r\n public nextActions?: string;\r\n\r\n constructor(message: string, statusCode: number, error: string, nextActions?: string) {\r\n super(message);\r\n this.name = 'InsForgeError';\r\n this.statusCode = statusCode;\r\n this.error = error;\r\n this.nextActions = nextActions;\r\n }\r\n\r\n static fromApiError(apiError: ApiError): InsForgeError {\r\n return new InsForgeError(\r\n apiError.message,\r\n apiError.statusCode,\r\n apiError.error,\r\n apiError.nextActions\r\n );\r\n }\r\n}","import { InsForgeConfig, ApiError, InsForgeError } from '../types';\r\n\r\nexport interface RequestOptions extends RequestInit {\r\n params?: Record<string, string>;\r\n}\r\n\r\nexport class HttpClient {\r\n public readonly baseUrl: string;\r\n public readonly fetch: typeof fetch;\r\n private defaultHeaders: Record<string, string>;\r\n private anonKey: string | undefined;\r\n private userToken: string | null = null;\r\n\r\n constructor(config: InsForgeConfig) {\r\n this.baseUrl = config.baseUrl || 'http://localhost:7130';\r\n // Properly bind fetch to maintain its context\r\n this.fetch = config.fetch || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined as any);\r\n this.anonKey = config.anonKey;\r\n this.defaultHeaders = {\r\n ...config.headers,\r\n };\r\n\r\n if (!this.fetch) {\r\n throw new Error(\r\n 'Fetch is not available. Please provide a fetch implementation in the config.'\r\n );\r\n }\r\n }\r\n\r\n private buildUrl(path: string, params?: Record<string, string>): string {\r\n const url = new URL(path, this.baseUrl);\r\n if (params) {\r\n Object.entries(params).forEach(([key, value]) => {\r\n // For select parameter, preserve the exact formatting by normalizing whitespace\r\n // This ensures PostgREST relationship queries work correctly\r\n if (key === 'select') {\r\n // Normalize multiline select strings for PostgREST:\r\n // 1. Replace all whitespace (including newlines) with single space\r\n // 2. Remove spaces inside parentheses for proper PostgREST syntax\r\n // 3. Keep spaces after commas at the top level for readability\r\n let normalizedValue = value.replace(/\\s+/g, ' ').trim();\r\n \r\n // Fix spaces around parentheses and inside them\r\n normalizedValue = normalizedValue\r\n .replace(/\\s*\\(\\s*/g, '(') // Remove spaces around opening parens\r\n .replace(/\\s*\\)\\s*/g, ')') // Remove spaces around closing parens\r\n .replace(/\\(\\s+/g, '(') // Remove spaces after opening parens\r\n .replace(/\\s+\\)/g, ')') // Remove spaces before closing parens\r\n .replace(/,\\s+(?=[^()]*\\))/g, ','); // Remove spaces after commas inside parens\r\n \r\n url.searchParams.append(key, normalizedValue);\r\n } else {\r\n url.searchParams.append(key, value);\r\n }\r\n });\r\n }\r\n return url.toString();\r\n }\r\n\r\n async request<T>(\r\n method: string,\r\n path: string,\r\n options: RequestOptions = {}\r\n ): Promise<T> {\r\n const { params, headers = {}, body, ...fetchOptions } = options;\r\n \r\n const url = this.buildUrl(path, params);\r\n \r\n const requestHeaders: Record<string, string> = {\r\n ...this.defaultHeaders,\r\n };\r\n \r\n // Set Authorization header: prefer user token, fallback to anon key\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n requestHeaders['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n // Handle body serialization\r\n let processedBody: any;\r\n if (body !== undefined) {\r\n // Check if body is FormData (for file uploads)\r\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\r\n // Don't set Content-Type for FormData, let browser set it with boundary\r\n processedBody = body;\r\n } else {\r\n // JSON body\r\n if (method !== 'GET') {\r\n requestHeaders['Content-Type'] = 'application/json;charset=UTF-8';\r\n }\r\n processedBody = JSON.stringify(body);\r\n }\r\n }\r\n \r\n Object.assign(requestHeaders, headers);\r\n \r\n const response = await this.fetch(url, {\r\n method,\r\n headers: requestHeaders,\r\n body: processedBody,\r\n ...fetchOptions,\r\n });\r\n\r\n // Handle 204 No Content\r\n if (response.status === 204) {\r\n return undefined as T;\r\n }\r\n\r\n // Try to parse JSON response\r\n let data: any;\r\n const contentType = response.headers.get('content-type');\r\n // Check for any JSON content type (including PostgREST's vnd.pgrst.object+json)\r\n if (contentType?.includes('json')) {\r\n data = await response.json();\r\n } else {\r\n // For non-JSON responses, return text\r\n data = await response.text();\r\n }\r\n\r\n // Handle errors\r\n if (!response.ok) {\r\n if (data && typeof data === 'object' && 'error' in data) {\r\n // Add the HTTP status code if not already in the data\r\n if (!data.statusCode && !data.status) {\r\n data.statusCode = response.status;\r\n }\r\n const error = InsForgeError.fromApiError(data as ApiError);\r\n // Preserve all additional fields from the error response\r\n Object.keys(data).forEach(key => {\r\n if (key !== 'error' && key !== 'message' && key !== 'statusCode') {\r\n (error as any)[key] = data[key];\r\n }\r\n });\r\n throw error;\r\n }\r\n throw new InsForgeError(\r\n `Request failed: ${response.statusText}`,\r\n response.status,\r\n 'REQUEST_FAILED'\r\n );\r\n }\r\n\r\n return data as T;\r\n }\r\n\r\n get<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('GET', path, options);\r\n }\r\n\r\n post<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('POST', path, { ...options, body });\r\n }\r\n\r\n put<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PUT', path, { ...options, body });\r\n }\r\n\r\n patch<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PATCH', path, { ...options, body });\r\n }\r\n\r\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('DELETE', path, options);\r\n }\r\n\r\n setAuthToken(token: string | null) {\r\n this.userToken = token;\r\n }\r\n\r\n getHeaders(): Record<string, string> {\r\n const headers = { ...this.defaultHeaders };\r\n \r\n // Include Authorization header if token is available (same logic as request method)\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n headers['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n return headers;\r\n }\r\n}","import { TokenStorage, AuthSession } from '../types';\r\n\r\nconst TOKEN_KEY = 'insforge-auth-token';\r\nconst USER_KEY = 'insforge-auth-user';\r\n\r\nexport class TokenManager {\r\n private storage: TokenStorage;\r\n\r\n constructor(storage?: TokenStorage) {\r\n if (storage) {\r\n // Use provided storage\r\n this.storage = storage;\r\n } else if (typeof window !== 'undefined' && window.localStorage) {\r\n // Browser: use localStorage\r\n this.storage = window.localStorage;\r\n } else {\r\n // Node.js: use in-memory storage\r\n const store = new Map<string, string>();\r\n this.storage = {\r\n getItem: (key: string) => store.get(key) || null,\r\n setItem: (key: string, value: string) => { store.set(key, value); },\r\n removeItem: (key: string) => { store.delete(key); }\r\n };\r\n }\r\n }\r\n\r\n saveSession(session: AuthSession): void {\r\n this.storage.setItem(TOKEN_KEY, session.accessToken);\r\n this.storage.setItem(USER_KEY, JSON.stringify(session.user));\r\n }\r\n\r\n getSession(): AuthSession | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n const userStr = this.storage.getItem(USER_KEY);\r\n\r\n if (!token || !userStr) {\r\n return null;\r\n }\r\n\r\n try {\r\n const user = JSON.parse(userStr as string);\r\n return { accessToken: token as string, user };\r\n } catch {\r\n this.clearSession();\r\n return null;\r\n }\r\n }\r\n\r\n getAccessToken(): string | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n return typeof token === 'string' ? token : null;\r\n }\r\n\r\n clearSession(): void {\r\n this.storage.removeItem(TOKEN_KEY);\r\n this.storage.removeItem(USER_KEY);\r\n }\r\n}","/**\r\n * Database module using @supabase/postgrest-js\r\n * Complete replacement for custom QueryBuilder with full PostgREST features\r\n */\r\n\r\nimport { PostgrestClient } from '@supabase/postgrest-js';\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\n\r\n\r\n/**\r\n * Custom fetch that transforms URLs and adds auth\r\n */\r\nfunction createInsForgePostgrestFetch(\r\n httpClient: HttpClient,\r\n tokenManager: TokenManager\r\n): typeof fetch {\r\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\r\n const url = typeof input === 'string' ? input : input.toString();\r\n const urlObj = new URL(url);\r\n \r\n // Extract table name from pathname\r\n // postgrest-js sends: http://dummy/tablename?params\r\n // We need: http://localhost:7130/api/database/records/tablename?params\r\n const tableName = urlObj.pathname.slice(1); // Remove leading /\r\n \r\n // Build InsForge URL\r\n const insforgeUrl = `${httpClient.baseUrl}/api/database/records/${tableName}${urlObj.search}`;\r\n \r\n // Get auth token from TokenManager or HttpClient\r\n const token = tokenManager.getAccessToken();\r\n const httpHeaders = httpClient.getHeaders();\r\n const authToken = token || httpHeaders['Authorization']?.replace('Bearer ', '');\r\n \r\n // Prepare headers\r\n const headers = new Headers(init?.headers);\r\n if (authToken && !headers.has('Authorization')) {\r\n headers.set('Authorization', `Bearer ${authToken}`);\r\n }\r\n \r\n // Make the actual request using native fetch\r\n const response = await fetch(insforgeUrl, {\r\n ...init,\r\n headers\r\n });\r\n \r\n return response;\r\n };\r\n}\r\n\r\n/**\r\n * Database client using postgrest-js\r\n * Drop-in replacement with FULL PostgREST capabilities\r\n */\r\nexport class Database {\r\n private postgrest: PostgrestClient<any, any, any>;\r\n \r\n constructor(httpClient: HttpClient, tokenManager: TokenManager) {\r\n // Create postgrest client with custom fetch\r\n this.postgrest = new PostgrestClient<any, any, any>('http://dummy', {\r\n fetch: createInsForgePostgrestFetch(httpClient, tokenManager),\r\n headers: {}\r\n });\r\n }\r\n \r\n /**\r\n * Create a query builder for a table\r\n * \r\n * @example\r\n * // Basic query\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', userId);\r\n * \r\n * // With count (Supabase style!)\r\n * const { data, error, count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact' })\r\n * .range(0, 9);\r\n * \r\n * // Just get count, no data\r\n * const { count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact', head: true });\r\n * \r\n * // Complex queries with OR\r\n * const { data } = await client.database\r\n * .from('posts')\r\n * .select('*, users!inner(*)')\r\n * .or('status.eq.active,status.eq.pending');\r\n * \r\n * // All features work:\r\n * - Nested selects\r\n * - Foreign key expansion \r\n * - OR/AND/NOT conditions\r\n * - Count with head\r\n * - Range pagination\r\n * - Upserts\r\n */\r\n from(table: string) {\r\n // Return postgrest query builder with all features\r\n return this.postgrest.from(table);\r\n }\r\n}","/**\r\n * Auth module for InsForge SDK\r\n * Uses shared schemas for type safety\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\nimport { AuthSession, InsForgeError } from '../types';\r\nimport { Database } from './database-postgrest';\r\n\r\nimport type {\r\n CreateUserRequest,\r\n CreateUserResponse,\r\n CreateSessionRequest,\r\n CreateSessionResponse,\r\n GetCurrentSessionResponse,\r\n GetOauthUrlResponse,\r\n ListPublicOAuthProvidersResponse,\r\n OAuthProvidersSchema,\r\n PublicOAuthProvider,\r\n GetPublicEmailAuthConfigResponse,\r\n UserIdSchema,\r\n EmailSchema,\r\n RoleSchema,\r\n ProfileSchema,\r\n UpdateProfileSchema,\r\n} from '@insforge/shared-schemas';\r\n\r\nexport class Auth {\r\n private database: Database;\r\n \r\n constructor(\r\n private http: HttpClient,\r\n private tokenManager: TokenManager\r\n ) {\r\n this.database = new Database(http, tokenManager);\r\n \r\n // Auto-detect OAuth callback parameters in the URL\r\n this.detectOAuthCallback();\r\n }\r\n\r\n /**\r\n * Automatically detect and handle OAuth callback parameters in the URL\r\n * This runs on initialization to seamlessly complete the OAuth flow\r\n * Matches the backend's OAuth callback response (backend/src/api/routes/auth.ts:540-544)\r\n */\r\n private detectOAuthCallback(): void {\r\n // Only run in browser environment\r\n if (typeof window === 'undefined') return;\r\n \r\n try {\r\n const params = new URLSearchParams(window.location.search);\r\n \r\n // Backend returns: access_token, user_id, email, name (optional)\r\n const accessToken = params.get('access_token');\r\n const userId = params.get('user_id');\r\n const email = params.get('email');\r\n const name = params.get('name');\r\n \r\n // Check if we have OAuth callback parameters\r\n if (accessToken && userId && email) {\r\n // Create session with the data from backend\r\n const session: AuthSession = {\r\n accessToken,\r\n user: {\r\n id: userId,\r\n email: email,\r\n name: name || '',\r\n // These fields are not provided by backend OAuth callback\r\n // They'll be populated when calling getCurrentUser()\r\n emailVerified: false,\r\n createdAt: new Date().toISOString(),\r\n updatedAt: new Date().toISOString(),\r\n } as any,\r\n };\r\n \r\n // Save session and set auth token\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(accessToken);\r\n \r\n // Clean up the URL to remove sensitive parameters\r\n const url = new URL(window.location.href);\r\n url.searchParams.delete('access_token');\r\n url.searchParams.delete('user_id');\r\n url.searchParams.delete('email');\r\n url.searchParams.delete('name');\r\n \r\n // Also handle error case from backend (line 581)\r\n if (params.has('error')) {\r\n url.searchParams.delete('error');\r\n }\r\n \r\n // Replace URL without adding to browser history\r\n window.history.replaceState({}, document.title, url.toString());\r\n }\r\n } catch (error) {\r\n // Silently continue - don't break initialization\r\n console.debug('OAuth callback detection skipped:', error);\r\n }\r\n }\r\n\r\n /**\r\n * Sign up a new user\r\n */\r\n async signUp(request: CreateUserRequest): Promise<{\r\n data: CreateUserResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateUserResponse>('/api/auth/users', request);\r\n\r\n // Save session internally only if both accessToken and user exist\r\n if (response.accessToken && response.user) {\r\n const session: AuthSession = {\r\n accessToken: response.accessToken,\r\n user: response.user,\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken);\r\n }\r\n\r\n return {\r\n data: response,\r\n error: null\r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n error instanceof Error ? error.message : 'An unexpected error occurred during sign up',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with email and password\r\n */\r\n async signInWithPassword(request: CreateSessionRequest): Promise<{\r\n data: CreateSessionResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateSessionResponse>('/api/auth/sessions', request);\r\n \r\n // Save session internally\r\n const session: AuthSession = {\r\n accessToken: response.accessToken || '',\r\n user: response.user || {\r\n id: '',\r\n email: '',\r\n name: '',\r\n emailVerified: false,\r\n createdAt: '',\r\n updatedAt: '',\r\n },\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken || '');\r\n\r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during sign in',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with OAuth provider\r\n */\r\n async signInWithOAuth(options: {\r\n provider: OAuthProvidersSchema;\r\n redirectTo?: string;\r\n skipBrowserRedirect?: boolean;\r\n }): Promise<{\r\n data: { url?: string; provider?: string };\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const { provider, redirectTo, skipBrowserRedirect } = options;\r\n \r\n const params = redirectTo \r\n ? { redirect_uri: redirectTo } \r\n : undefined;\r\n \r\n const endpoint = `/api/auth/oauth/${provider}`;\r\n const response = await this.http.get<GetOauthUrlResponse>(endpoint, { params });\r\n \r\n // Automatically redirect in browser unless told not to\r\n if (typeof window !== 'undefined' && !skipBrowserRedirect) {\r\n window.location.href = response.authUrl;\r\n return { data: {}, error: null };\r\n }\r\n\r\n return { \r\n data: { \r\n url: response.authUrl,\r\n provider \r\n }, \r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: {}, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: {}, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during OAuth initialization',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign out the current user\r\n */\r\n async signOut(): Promise<{ error: InsForgeError | null }> {\r\n try {\r\n this.tokenManager.clearSession();\r\n this.http.setAuthToken(null);\r\n return { error: null };\r\n } catch (error) {\r\n return { \r\n error: new InsForgeError(\r\n 'Failed to sign out',\r\n 500,\r\n 'SIGNOUT_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get list of available OAuth providers\r\n * Returns the list of OAuth providers configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Array of configured OAuth providers with their configuration status\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getOAuthProviders();\r\n * if (data) {\r\n * // data is an array of PublicOAuthProvider: [{ provider: 'google', isConfigured: true }, ...]\r\n * data.forEach(p => console.log(`${p.provider}: ${p.isConfigured ? 'configured' : 'not configured'}`));\r\n * }\r\n * ```\r\n */\r\n async getOAuthProviders(): Promise<{\r\n data: PublicOAuthProvider[] | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<ListPublicOAuthProvidersResponse>('/api/auth/oauth/providers');\r\n \r\n return { \r\n data: response.data,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching OAuth providers',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public email authentication configuration\r\n * Returns email authentication settings configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Email authentication configuration including password requirements and email verification settings\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getEmailAuthConfig();\r\n * if (data) {\r\n * console.log(`Password min length: ${data.passwordMinLength}`);\r\n * console.log(`Requires email verification: ${data.requireEmailVerification}`);\r\n * console.log(`Requires uppercase: ${data.requireUppercase}`);\r\n * }\r\n * ```\r\n */\r\n async getEmailAuthConfig(): Promise<{\r\n data: GetPublicEmailAuthConfigResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<GetPublicEmailAuthConfigResponse>('/api/auth/email/public-config');\r\n \r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching email authentication configuration',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get the current user with full profile information\r\n * Returns both auth info (id, email, role) and profile data (nickname, avatar_url, bio, etc.)\r\n */\r\n async getCurrentUser(): Promise<{\r\n data: {\r\n user: {\r\n id: UserIdSchema;\r\n email: EmailSchema;\r\n role: RoleSchema;\r\n };\r\n profile: ProfileSchema | null;\r\n } | null;\r\n error: any | null;\r\n }> {\r\n try {\r\n // Check if we have a token\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { data: null, error: null };\r\n }\r\n\r\n // Call the API for auth info\r\n this.http.setAuthToken(session.accessToken);\r\n const authResponse = await this.http.get<GetCurrentSessionResponse>('/api/auth/sessions/current');\r\n \r\n // Get the user's profile using query builder\r\n const { data: profile, error: profileError } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', authResponse.user.id)\r\n .single();\r\n \r\n // For database errors, return PostgrestError directly\r\n if (profileError && (profileError as any).code !== 'PGRST116') { // PGRST116 = not found\r\n return { data: null, error: profileError };\r\n }\r\n \r\n return {\r\n data: {\r\n user: authResponse.user,\r\n profile: profile\r\n },\r\n error: null\r\n };\r\n } catch (error) {\r\n // If unauthorized, clear session\r\n if (error instanceof InsForgeError && error.statusCode === 401) {\r\n await this.signOut();\r\n return { data: null, error: null };\r\n }\r\n \r\n // Pass through all other errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching user',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get any user's profile by ID\r\n * Returns profile information from the users table (nickname, avatar_url, bio, etc.)\r\n */\r\n async getProfile(userId: string): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n const { data, error } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', userId)\r\n .single();\r\n \r\n // Handle not found as null, not error\r\n if (error && (error as any).code === 'PGRST116') {\r\n return { data: null, error: null };\r\n }\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data, error };\r\n }\r\n\r\n /**\r\n * Get the current session (only session data, no API call)\r\n * Returns the stored JWT token and basic user info from local storage\r\n */\r\n getCurrentSession(): {\r\n data: { session: AuthSession | null };\r\n error: InsForgeError | null;\r\n } {\r\n try {\r\n const session = this.tokenManager.getSession();\r\n \r\n if (session?.accessToken) {\r\n this.http.setAuthToken(session.accessToken);\r\n return { data: { session }, error: null };\r\n }\r\n\r\n return { data: { session: null }, error: null };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: { session: null }, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: { session: null }, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while getting session',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Set/Update the current user's profile\r\n * Updates profile information in the users table (nickname, avatar_url, bio, etc.)\r\n */\r\n async setProfile(profile: UpdateProfileSchema): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n // Get current session to get user ID\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'No authenticated user found',\r\n 401,\r\n 'UNAUTHENTICATED'\r\n )\r\n };\r\n }\r\n \r\n // If no user ID in session (edge function scenario), fetch it\r\n if (!session.user?.id) {\r\n const { data, error } = await this.getCurrentUser();\r\n if (error) {\r\n return { data: null, error };\r\n }\r\n if (data?.user) {\r\n // Update session with minimal user info\r\n session.user = {\r\n id: data.user.id,\r\n email: data.user.email,\r\n name: data.profile?.nickname || '', // Not available from API, but required by UserSchema\r\n emailVerified: false, // Not available from API, but required by UserSchema\r\n createdAt: new Date().toISOString(), // Fallback\r\n updatedAt: new Date().toISOString(), // Fallback\r\n };\r\n this.tokenManager.saveSession(session);\r\n }\r\n }\r\n\r\n // Update the profile using query builder\r\n const { data, error } = await this.database\r\n .from('users')\r\n .update(profile)\r\n .eq('id', session.user.id)\r\n .select()\r\n .single();\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data, error };\r\n }\r\n\r\n\r\n}","/**\r\n * Storage module for InsForge SDK\r\n * Handles file uploads, downloads, and bucket management\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { InsForgeError } from '../types';\r\nimport type { \r\n StorageFileSchema,\r\n ListObjectsResponseSchema\r\n} from '@insforge/shared-schemas';\r\n\r\nexport interface StorageResponse<T> {\r\n data: T | null;\r\n error: InsForgeError | null;\r\n}\r\n\r\ninterface UploadStrategy {\r\n method: 'direct' | 'presigned';\r\n uploadUrl: string;\r\n fields?: Record<string, string>;\r\n key: string;\r\n confirmRequired: boolean;\r\n confirmUrl?: string;\r\n expiresAt?: Date;\r\n}\r\n\r\ninterface DownloadStrategy {\r\n method: 'direct' | 'presigned';\r\n url: string;\r\n expiresAt?: Date;\r\n}\r\n\r\n/**\r\n * Storage bucket operations\r\n */\r\nexport class StorageBucket {\r\n constructor(\r\n private bucketName: string,\r\n private http: HttpClient\r\n ) {}\r\n\r\n /**\r\n * Upload a file with a specific key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * @param file - File or Blob to upload\r\n */\r\n async upload(\r\n path: string,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename: path,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'PUT',\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Upload a file with auto-generated key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param file - File or Blob to upload\r\n */\r\n async uploadAuto(\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n const filename = file instanceof File ? file.name : 'file';\r\n \r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'POST',\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Internal method to handle presigned URL uploads\r\n */\r\n private async uploadWithPresignedUrl(\r\n strategy: UploadStrategy,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Upload to presigned URL (e.g., S3)\r\n const formData = new FormData();\r\n \r\n // Add all fields from the presigned URL\r\n if (strategy.fields) {\r\n Object.entries(strategy.fields).forEach(([key, value]) => {\r\n formData.append(key, value);\r\n });\r\n }\r\n \r\n // File must be the last field for S3\r\n formData.append('file', file);\r\n\r\n const uploadResponse = await fetch(strategy.uploadUrl, {\r\n method: 'POST',\r\n body: formData\r\n });\r\n\r\n if (!uploadResponse.ok) {\r\n throw new InsForgeError(\r\n `Upload to storage failed: ${uploadResponse.statusText}`,\r\n uploadResponse.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n\r\n // Confirm upload with backend if required\r\n if (strategy.confirmRequired && strategy.confirmUrl) {\r\n const confirmResponse = await this.http.post<StorageFileSchema>(\r\n strategy.confirmUrl,\r\n {\r\n size: file.size,\r\n contentType: file.type || 'application/octet-stream'\r\n }\r\n );\r\n\r\n return { data: confirmResponse, error: null };\r\n }\r\n\r\n // If no confirmation required, return basic file info\r\n return {\r\n data: {\r\n key: strategy.key,\r\n bucket: this.bucketName,\r\n size: file.size,\r\n mimeType: file.type || 'application/octet-stream',\r\n uploadedAt: new Date().toISOString(),\r\n url: this.getPublicUrl(strategy.key)\r\n } as StorageFileSchema,\r\n error: null\r\n };\r\n } catch (error) {\r\n throw error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Presigned upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Download a file\r\n * Uses the download strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * Returns the file as a Blob\r\n */\r\n async download(path: string): Promise<{ data: Blob | null; error: InsForgeError | null }> {\r\n try {\r\n // Get download strategy from backend - this is required\r\n const strategyResponse = await this.http.post<DownloadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}/download-strategy`,\r\n { expiresIn: 3600 }\r\n );\r\n\r\n // Use URL from strategy\r\n const downloadUrl = strategyResponse.url;\r\n \r\n // Download from the URL\r\n const headers: HeadersInit = {};\r\n \r\n // Only add auth header for direct downloads (not presigned URLs)\r\n if (strategyResponse.method === 'direct') {\r\n Object.assign(headers, this.http.getHeaders());\r\n }\r\n \r\n const response = await fetch(downloadUrl, {\r\n method: 'GET',\r\n headers\r\n });\r\n\r\n if (!response.ok) {\r\n try {\r\n const error = await response.json();\r\n throw InsForgeError.fromApiError(error);\r\n } catch {\r\n throw new InsForgeError(\r\n `Download failed: ${response.statusText}`,\r\n response.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n const blob = await response.blob();\r\n return { data: blob, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Download failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public URL for a file\r\n * @param path - The object key/path\r\n */\r\n getPublicUrl(path: string): string {\r\n return `${this.http.baseUrl}/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`;\r\n }\r\n\r\n /**\r\n * List objects in the bucket\r\n * @param prefix - Filter by key prefix\r\n * @param search - Search in file names\r\n * @param limit - Maximum number of results (default: 100, max: 1000)\r\n * @param offset - Number of results to skip\r\n */\r\n async list(options?: {\r\n prefix?: string;\r\n search?: string;\r\n limit?: number;\r\n offset?: number;\r\n }): Promise<StorageResponse<ListObjectsResponseSchema>> {\r\n try {\r\n const params: Record<string, string> = {};\r\n \r\n if (options?.prefix) params.prefix = options.prefix;\r\n if (options?.search) params.search = options.search;\r\n if (options?.limit) params.limit = options.limit.toString();\r\n if (options?.offset) params.offset = options.offset.toString();\r\n\r\n const response = await this.http.get<ListObjectsResponseSchema>(\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n { params }\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'List failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Delete a file\r\n * @param path - The object key/path\r\n */\r\n async remove(path: string): Promise<StorageResponse<{ message: string }>> {\r\n try {\r\n const response = await this.http.delete<{ message: string }>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Delete failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Storage module for file operations\r\n */\r\nexport class Storage {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Get a bucket instance for operations\r\n * @param bucketName - Name of the bucket\r\n */\r\n from(bucketName: string): StorageBucket {\r\n return new StorageBucket(bucketName, this.http);\r\n }\r\n}","/**\r\n * AI Module for Insforge SDK\r\n * Response format roughly matches OpenAI SDK for compatibility\r\n *\r\n * The backend handles all the complexity of different AI providers\r\n * and returns a unified format. This SDK transforms responses to match OpenAI-like format.\r\n */\r\n\r\nimport { HttpClient } from \"../lib/http-client\";\r\nimport {\r\n ChatCompletionRequest,\r\n ChatCompletionResponse,\r\n ImageGenerationRequest,\r\n ImageGenerationResponse,\r\n} from \"@insforge/shared-schemas\";\r\n\r\nexport class AI {\r\n public readonly chat: Chat;\r\n public readonly images: Images;\r\n\r\n constructor(private http: HttpClient) {\r\n this.chat = new Chat(http);\r\n this.images = new Images(http);\r\n }\r\n}\r\n\r\nclass Chat {\r\n public readonly completions: ChatCompletions;\r\n\r\n constructor(http: HttpClient) {\r\n this.completions = new ChatCompletions(http);\r\n }\r\n}\r\n\r\nclass ChatCompletions {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Create a chat completion - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Non-streaming\r\n * const completion = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Hello!' }]\r\n * });\r\n * console.log(completion.choices[0].message.content);\r\n *\r\n * // With images\r\n * const response = await client.ai.chat.completions.create({\r\n * model: 'gpt-4-vision',\r\n * messages: [{\r\n * role: 'user',\r\n * content: 'What is in this image?',\r\n * images: [{ url: 'https://example.com/image.jpg' }]\r\n * }]\r\n * });\r\n *\r\n * // Streaming - returns async iterable\r\n * const stream = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Tell me a story' }],\r\n * stream: true\r\n * });\r\n *\r\n * for await (const chunk of stream) {\r\n * if (chunk.choices[0]?.delta?.content) {\r\n * process.stdout.write(chunk.choices[0].delta.content);\r\n * }\r\n * }\r\n * ```\r\n */\r\n async create(params: ChatCompletionRequest): Promise<any> {\r\n // Backend already expects camelCase, no transformation needed\r\n const backendParams = {\r\n model: params.model,\r\n messages: params.messages,\r\n temperature: params.temperature,\r\n maxTokens: params.maxTokens,\r\n topP: params.topP,\r\n stream: params.stream,\r\n };\r\n\r\n // For streaming, return an async iterable that yields OpenAI-like chunks\r\n if (params.stream) {\r\n const headers = this.http.getHeaders();\r\n headers[\"Content-Type\"] = \"application/json\";\r\n\r\n const response = await this.http.fetch(\r\n `${this.http.baseUrl}/api/ai/chat/completion`,\r\n {\r\n method: \"POST\",\r\n headers,\r\n body: JSON.stringify(backendParams),\r\n }\r\n );\r\n\r\n if (!response.ok) {\r\n const error = await response.json();\r\n throw new Error(error.error || \"Stream request failed\");\r\n }\r\n\r\n // Return async iterable that parses SSE and transforms to OpenAI-like format\r\n return this.parseSSEStream(response, params.model);\r\n }\r\n\r\n // Non-streaming: transform response to OpenAI-like format\r\n const response: ChatCompletionResponse = await this.http.post(\r\n \"/api/ai/chat/completion\",\r\n backendParams\r\n );\r\n\r\n // Transform to OpenAI-like format\r\n const content = response.text || \"\";\r\n\r\n return {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion\",\r\n created: Math.floor(Date.now() / 1000),\r\n model: response.metadata?.model,\r\n choices: [\r\n {\r\n index: 0,\r\n message: {\r\n role: \"assistant\",\r\n content,\r\n },\r\n finish_reason: \"stop\",\r\n },\r\n ],\r\n usage: response.metadata?.usage || {\r\n prompt_tokens: 0,\r\n completion_tokens: 0,\r\n total_tokens: 0,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Parse SSE stream into async iterable of OpenAI-like chunks\r\n */\r\n private async *parseSSEStream(\r\n response: Response,\r\n model: string\r\n ): AsyncIterableIterator<any> {\r\n const reader = response.body!.getReader();\r\n const decoder = new TextDecoder();\r\n let buffer = \"\";\r\n\r\n try {\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n\r\n buffer += decoder.decode(value, { stream: true });\r\n const lines = buffer.split(\"\\n\");\r\n buffer = lines.pop() || \"\";\r\n\r\n for (const line of lines) {\r\n if (line.startsWith(\"data: \")) {\r\n const dataStr = line.slice(6).trim();\r\n if (dataStr) {\r\n try {\r\n const data = JSON.parse(dataStr);\r\n\r\n // Transform to OpenAI-like streaming format\r\n if (data.chunk || data.content) {\r\n yield {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion.chunk\",\r\n created: Math.floor(Date.now() / 1000),\r\n model,\r\n choices: [\r\n {\r\n index: 0,\r\n delta: {\r\n content: data.chunk || data.content,\r\n },\r\n finish_reason: data.done ? \"stop\" : null,\r\n },\r\n ],\r\n };\r\n }\r\n\r\n // If we received the done signal, we can stop\r\n if (data.done) {\r\n reader.releaseLock();\r\n return;\r\n }\r\n } catch (e) {\r\n // Skip invalid JSON\r\n console.warn(\"Failed to parse SSE data:\", dataStr);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n reader.releaseLock();\r\n }\r\n }\r\n}\r\n\r\nclass Images {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Generate images - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Text-to-image\r\n * const response = await client.ai.images.generate({\r\n * model: 'dall-e-3',\r\n * prompt: 'A sunset over mountains',\r\n * });\r\n * console.log(response.images[0].url);\r\n *\r\n * // Image-to-image (with input images)\r\n * const response = await client.ai.images.generate({\r\n * model: 'stable-diffusion-xl',\r\n * prompt: 'Transform this into a watercolor painting',\r\n * images: [\r\n * { url: 'https://example.com/input.jpg' },\r\n * // or base64-encoded Data URI:\r\n * { url: 'data:image/jpeg;base64,/9j/4AAQ...' }\r\n * ]\r\n * });\r\n * ```\r\n */\r\n async generate(params: ImageGenerationRequest): Promise<any> {\r\n const response: ImageGenerationResponse = await this.http.post(\r\n \"/api/ai/image/generation\",\r\n params\r\n );\r\n \r\n // Build data array based on response content\r\n let data: Array<{ b64_json?: string; content?: string }> = [];\r\n \r\n if (response.images && response.images.length > 0) {\r\n // Has images - extract base64 and include text\r\n data = response.images.map(img => ({\r\n b64_json: img.imageUrl.replace(/^data:image\\/\\w+;base64,/, ''),\r\n content: response.text\r\n }));\r\n } else if (response.text) {\r\n // Text-only response\r\n data = [{ content: response.text }];\r\n }\r\n \r\n // Return OpenAI-compatible format\r\n return {\r\n created: Math.floor(Date.now() / 1000),\r\n data,\r\n ...(response.metadata?.usage && {\r\n usage: {\r\n total_tokens: response.metadata.usage.totalTokens || 0,\r\n input_tokens: response.metadata.usage.promptTokens || 0,\r\n output_tokens: response.metadata.usage.completionTokens || 0,\r\n }\r\n })\r\n };\r\n }\r\n}\r\n","import { HttpClient } from '../lib/http-client';\r\n\r\nexport interface FunctionInvokeOptions {\r\n /**\r\n * The body of the request\r\n */\r\n body?: any;\r\n \r\n /**\r\n * Custom headers to send with the request\r\n */\r\n headers?: Record<string, string>;\r\n \r\n /**\r\n * HTTP method (default: POST)\r\n */\r\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\r\n}\r\n\r\n/**\r\n * Edge Functions client for invoking serverless functions\r\n * \r\n * @example\r\n * ```typescript\r\n * // Invoke a function with JSON body\r\n * const { data, error } = await client.functions.invoke('hello-world', {\r\n * body: { name: 'World' }\r\n * });\r\n * \r\n * // GET request\r\n * const { data, error } = await client.functions.invoke('get-data', {\r\n * method: 'GET'\r\n * });\r\n * ```\r\n */\r\nexport class Functions {\r\n private http: HttpClient;\r\n\r\n constructor(http: HttpClient) {\r\n this.http = http;\r\n }\r\n\r\n /**\r\n * Invokes an Edge Function\r\n * @param slug The function slug to invoke\r\n * @param options Request options\r\n */\r\n async invoke<T = any>(\r\n slug: string,\r\n options: FunctionInvokeOptions = {}\r\n ): Promise<{ data: T | null; error: Error | null }> {\r\n try {\r\n const { method = 'POST', body, headers = {} } = options;\r\n \r\n // Simple path: /functions/{slug}\r\n const path = `/functions/${slug}`;\r\n \r\n // Use the HTTP client's request method\r\n const data = await this.http.request<T>(\r\n method,\r\n path,\r\n { body, headers }\r\n );\r\n \r\n return { data, error: null };\r\n } catch (error: any) {\r\n // The HTTP client throws InsForgeError with all properties from the response\r\n // including error, message, details, statusCode, etc.\r\n // We need to preserve all of that information\r\n return { \r\n data: null, \r\n error: error // Pass through the full error object with all properties\r\n };\r\n }\r\n }\r\n}","import { InsForgeConfig } from './types';\r\nimport { HttpClient } from './lib/http-client';\r\nimport { TokenManager } from './lib/token-manager';\r\nimport { Auth } from './modules/auth';\r\nimport { Database } from './modules/database-postgrest';\r\nimport { Storage } from './modules/storage';\r\nimport { AI } from './modules/ai';\r\nimport { Functions } from './modules/functions';\r\n\r\n/**\r\n * Main InsForge SDK Client\r\n * \r\n * @example\r\n * ```typescript\r\n * import { InsForgeClient } from '@insforge/sdk';\r\n * \r\n * const client = new InsForgeClient({\r\n * baseUrl: 'http://localhost:7130'\r\n * });\r\n * \r\n * // Authentication\r\n * const session = await client.auth.register({\r\n * email: 'user@example.com',\r\n * password: 'password123',\r\n * name: 'John Doe'\r\n * });\r\n * \r\n * // Database operations\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', session.user.id)\r\n * .order('created_at', { ascending: false })\r\n * .limit(10);\r\n * \r\n * // Insert data\r\n * const { data: newPost } = await client.database\r\n * .from('posts')\r\n * .insert({ title: 'Hello', content: 'World' })\r\n * .single();\r\n * \r\n * // Invoke edge functions\r\n * const { data, error } = await client.functions.invoke('my-function', {\r\n * body: { message: 'Hello from SDK' }\r\n * });\r\n * ```\r\n */\r\nexport class InsForgeClient {\r\n private http: HttpClient;\r\n private tokenManager: TokenManager;\r\n \r\n public readonly auth: Auth;\r\n public readonly database: Database;\r\n public readonly storage: Storage;\r\n public readonly ai: AI;\r\n public readonly functions: Functions;\r\n\r\n constructor(config: InsForgeConfig = {}) {\r\n this.http = new HttpClient(config);\r\n this.tokenManager = new TokenManager(config.storage);\r\n \r\n // Check for edge function token\r\n if (config.edgeFunctionToken) {\r\n this.http.setAuthToken(config.edgeFunctionToken);\r\n // Save to token manager so getCurrentUser() works\r\n this.tokenManager.saveSession({\r\n accessToken: config.edgeFunctionToken,\r\n user: {} as any // Will be populated by getCurrentUser()\r\n });\r\n }\r\n \r\n // Check for existing session in storage\r\n const existingSession = this.tokenManager.getSession();\r\n if (existingSession?.accessToken) {\r\n this.http.setAuthToken(existingSession.accessToken);\r\n }\r\n \r\n this.auth = new Auth(\r\n this.http,\r\n this.tokenManager\r\n );\r\n \r\n this.database = new Database(this.http, this.tokenManager);\r\n this.storage = new Storage(this.http);\r\n this.ai = new AI(this.http);\r\n this.functions = new Functions(this.http);\r\n }\r\n\r\n /**\r\n * Get the underlying HTTP client for custom requests\r\n * \r\n * @example\r\n * ```typescript\r\n * const httpClient = client.getHttpClient();\r\n * const customData = await httpClient.get('/api/custom-endpoint');\r\n * ```\r\n */\r\n getHttpClient(): HttpClient {\r\n return this.http;\r\n }\r\n\r\n /**\r\n * Future modules will be added here:\r\n * - database: Database operations\r\n * - storage: File storage operations\r\n * - functions: Serverless functions\r\n * - tables: Table management\r\n * - metadata: Backend metadata\r\n */\r\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0EO,IAAM,gBAAN,MAAM,uBAAsB,MAAM;AAAA,EAKvC,YAAY,SAAiB,YAAoB,OAAe,aAAsB;AACpF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,QAAQ;AACb,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,OAAO,aAAa,UAAmC;AACrD,WAAO,IAAI;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,IACX;AAAA,EACF;AACF;;;ACzFO,IAAM,aAAN,MAAiB;AAAA,EAOtB,YAAY,QAAwB;AAFpC,SAAQ,YAA2B;AAGjC,SAAK,UAAU,OAAO,WAAW;AAEjC,SAAK,QAAQ,OAAO,UAAU,WAAW,QAAQ,WAAW,MAAM,KAAK,UAAU,IAAI;AACrF,SAAK,UAA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MAAM,OAAO,KAAK;AAAA,IAC7B,SAAS,OAAY;AAInB,aAAO;AAAA,QACL,MAAM;AAAA,QACN;AAAA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AC5BO,IAAM,iBAAN,MAAqB;AAAA,EAU1B,YAAY,SAAyB,CAAC,GAAG;AACvC,SAAK,OAAO,IAAI,WAAW,MAAM;AACjC,SAAK,eAAe,IAAI,aAAa,OAAO,OAAO;AAGnD,QAAI,OAAO,mBAAmB;AAC5B,WAAK,KAAK,aAAa,OAAO,iBAAiB;AAE/C,WAAK,aAAa,YAAY;AAAA,QAC5B,aAAa,OAAO;AAAA,QACpB,MAAM,CAAC;AAAA;AAAA,MACT,CAAC;AAAA,IACH;AAGA,UAAM,kBAAkB,KAAK,aAAa,WAAW;AACrD,QAAI,iBAAiB,aAAa;AAChC,WAAK,KAAK,aAAa,gBAAgB,WAAW;AAAA,IACpD;AAEA,SAAK,OAAO,IAAI;AAAA,MACd,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAEA,SAAK,WAAW,IAAI,SAAS,KAAK,MAAM,KAAK,YAAY;AACzD,SAAK,UAAU,IAAI,QAAQ,KAAK,IAAI;AACpC,SAAK,KAAK,IAAI,GAAG,KAAK,IAAI;AAC1B,SAAK,YAAY,IAAI,UAAU,KAAK,IAAI;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,gBAA4B;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUF;;;ATvDO,SAAS,aAAa,QAAwC;AACnE,SAAO,IAAI,eAAe,MAAM;AAClC;AAGA,IAAO,gBAAQ;","names":["data","error","response"]}
1
+ {"version":3,"sources":["../src/index.ts","../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"],"sourcesContent":["/**\r\n * @insforge/sdk - TypeScript SDK for InsForge Backend-as-a-Service\r\n * \r\n * @packageDocumentation\r\n */\r\n\r\n// Main client\r\nexport { InsForgeClient } from './client';\r\n\r\n// Types\r\nexport type {\r\n InsForgeConfig,\r\n InsForgeConfig as ClientOptions, // Alias for compatibility\r\n TokenStorage,\r\n AuthSession,\r\n ApiError,\r\n} from './types';\r\n\r\nexport { InsForgeError } from './types';\r\n\r\n// Re-export shared schemas that SDK users will need\r\nexport type {\r\n UserSchema,\r\n CreateUserRequest,\r\n CreateSessionRequest,\r\n AuthErrorResponse,\r\n} from '@insforge/shared-schemas';\r\n\r\n// Re-export auth module for advanced usage\r\nexport { Auth } from './modules/auth';\r\n\r\n// Re-export database module (using postgrest-js)\r\nexport { Database } from './modules/database-postgrest';\r\n// Note: QueryBuilder is no longer exported as we use postgrest-js QueryBuilder internally\r\n\r\n// Re-export storage module and types\r\nexport { Storage, StorageBucket } from './modules/storage';\r\nexport type { StorageResponse } from './modules/storage';\r\n\r\n// Re-export AI module\r\nexport { AI } from './modules/ai';\r\n\r\n// Re-export Functions module\r\nexport { Functions } from './modules/functions';\r\nexport type { FunctionInvokeOptions } from './modules/functions';\r\n\r\n// Re-export utilities for advanced usage\r\nexport { HttpClient } from './lib/http-client';\r\nexport { TokenManager } from './lib/token-manager';\r\n\r\n// Factory function for creating clients (Supabase-style)\r\nimport { InsForgeClient } from './client';\r\nimport { InsForgeConfig } from './types';\r\n\r\nexport function createClient(config: InsForgeConfig): InsForgeClient {\r\n return new InsForgeClient(config);\r\n}\r\n\r\n// Default export for convenience\r\nexport default InsForgeClient;","/**\r\n * InsForge SDK Types - only SDK-specific types here\r\n * Use @insforge/shared-schemas directly for API types\r\n */\r\n\r\nimport type { UserSchema } from '@insforge/shared-schemas';\r\n\r\nexport interface InsForgeConfig {\r\n /**\r\n * The base URL of the InsForge backend API\r\n * @default \"http://localhost:7130\"\r\n */\r\n baseUrl?: string;\r\n\r\n /**\r\n * Anonymous API key (optional)\r\n * Used for public/unauthenticated requests when no user token is set\r\n */\r\n anonKey?: string;\r\n\r\n /**\r\n * Edge Function Token (optional)\r\n * Use this when running in edge functions/serverless with a user's JWT token\r\n * This token will be used for all authenticated requests\r\n */\r\n edgeFunctionToken?: string;\r\n\r\n /**\r\n * Custom fetch implementation (useful for Node.js environments)\r\n */\r\n fetch?: typeof fetch;\r\n\r\n /**\r\n * Storage adapter for persisting tokens\r\n */\r\n storage?: TokenStorage;\r\n\r\n /**\r\n * Whether to automatically refresh tokens before they expire\r\n * @default true\r\n */\r\n autoRefreshToken?: boolean;\r\n\r\n /**\r\n * Whether to persist session in storage\r\n * @default true\r\n */\r\n persistSession?: boolean;\r\n\r\n /**\r\n * Custom headers to include with every request\r\n */\r\n headers?: Record<string, string>;\r\n}\r\n\r\nexport interface TokenStorage {\r\n getItem(key: string): string | null | Promise<string | null>;\r\n setItem(key: string, value: string): void | Promise<void>;\r\n removeItem(key: string): void | Promise<void>;\r\n}\r\n\r\nexport interface AuthSession {\r\n user: UserSchema;\r\n accessToken: string;\r\n expiresAt?: Date;\r\n}\r\n\r\nexport interface ApiError {\r\n error: string;\r\n message: string;\r\n statusCode: number;\r\n nextActions?: string;\r\n}\r\n\r\nexport class InsForgeError extends Error {\r\n public statusCode: number;\r\n public error: string;\r\n public nextActions?: string;\r\n\r\n constructor(message: string, statusCode: number, error: string, nextActions?: string) {\r\n super(message);\r\n this.name = 'InsForgeError';\r\n this.statusCode = statusCode;\r\n this.error = error;\r\n this.nextActions = nextActions;\r\n }\r\n\r\n static fromApiError(apiError: ApiError): InsForgeError {\r\n return new InsForgeError(\r\n apiError.message,\r\n apiError.statusCode,\r\n apiError.error,\r\n apiError.nextActions\r\n );\r\n }\r\n}","import { InsForgeConfig, ApiError, InsForgeError } from '../types';\r\n\r\nexport interface RequestOptions extends RequestInit {\r\n params?: Record<string, string>;\r\n}\r\n\r\nexport class HttpClient {\r\n public readonly baseUrl: string;\r\n public readonly fetch: typeof fetch;\r\n private defaultHeaders: Record<string, string>;\r\n private anonKey: string | undefined;\r\n private userToken: string | null = null;\r\n\r\n constructor(config: InsForgeConfig) {\r\n this.baseUrl = config.baseUrl || 'http://localhost:7130';\r\n // Properly bind fetch to maintain its context\r\n this.fetch = config.fetch || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined as any);\r\n this.anonKey = config.anonKey;\r\n this.defaultHeaders = {\r\n ...config.headers,\r\n };\r\n\r\n if (!this.fetch) {\r\n throw new Error(\r\n 'Fetch is not available. Please provide a fetch implementation in the config.'\r\n );\r\n }\r\n }\r\n\r\n private buildUrl(path: string, params?: Record<string, string>): string {\r\n const url = new URL(path, this.baseUrl);\r\n if (params) {\r\n Object.entries(params).forEach(([key, value]) => {\r\n // For select parameter, preserve the exact formatting by normalizing whitespace\r\n // This ensures PostgREST relationship queries work correctly\r\n if (key === 'select') {\r\n // Normalize multiline select strings for PostgREST:\r\n // 1. Replace all whitespace (including newlines) with single space\r\n // 2. Remove spaces inside parentheses for proper PostgREST syntax\r\n // 3. Keep spaces after commas at the top level for readability\r\n let normalizedValue = value.replace(/\\s+/g, ' ').trim();\r\n \r\n // Fix spaces around parentheses and inside them\r\n normalizedValue = normalizedValue\r\n .replace(/\\s*\\(\\s*/g, '(') // Remove spaces around opening parens\r\n .replace(/\\s*\\)\\s*/g, ')') // Remove spaces around closing parens\r\n .replace(/\\(\\s+/g, '(') // Remove spaces after opening parens\r\n .replace(/\\s+\\)/g, ')') // Remove spaces before closing parens\r\n .replace(/,\\s+(?=[^()]*\\))/g, ','); // Remove spaces after commas inside parens\r\n \r\n url.searchParams.append(key, normalizedValue);\r\n } else {\r\n url.searchParams.append(key, value);\r\n }\r\n });\r\n }\r\n return url.toString();\r\n }\r\n\r\n async request<T>(\r\n method: string,\r\n path: string,\r\n options: RequestOptions = {}\r\n ): Promise<T> {\r\n const { params, headers = {}, body, ...fetchOptions } = options;\r\n \r\n const url = this.buildUrl(path, params);\r\n \r\n const requestHeaders: Record<string, string> = {\r\n ...this.defaultHeaders,\r\n };\r\n \r\n // Set Authorization header: prefer user token, fallback to anon key\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n requestHeaders['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n // Handle body serialization\r\n let processedBody: any;\r\n if (body !== undefined) {\r\n // Check if body is FormData (for file uploads)\r\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\r\n // Don't set Content-Type for FormData, let browser set it with boundary\r\n processedBody = body;\r\n } else {\r\n // JSON body\r\n if (method !== 'GET') {\r\n requestHeaders['Content-Type'] = 'application/json;charset=UTF-8';\r\n }\r\n processedBody = JSON.stringify(body);\r\n }\r\n }\r\n \r\n Object.assign(requestHeaders, headers);\r\n \r\n const response = await this.fetch(url, {\r\n method,\r\n headers: requestHeaders,\r\n body: processedBody,\r\n ...fetchOptions,\r\n });\r\n\r\n // Handle 204 No Content\r\n if (response.status === 204) {\r\n return undefined as T;\r\n }\r\n\r\n // Try to parse JSON response\r\n let data: any;\r\n const contentType = response.headers.get('content-type');\r\n // Check for any JSON content type (including PostgREST's vnd.pgrst.object+json)\r\n if (contentType?.includes('json')) {\r\n data = await response.json();\r\n } else {\r\n // For non-JSON responses, return text\r\n data = await response.text();\r\n }\r\n\r\n // Handle errors\r\n if (!response.ok) {\r\n if (data && typeof data === 'object' && 'error' in data) {\r\n // Add the HTTP status code if not already in the data\r\n if (!data.statusCode && !data.status) {\r\n data.statusCode = response.status;\r\n }\r\n const error = InsForgeError.fromApiError(data as ApiError);\r\n // Preserve all additional fields from the error response\r\n Object.keys(data).forEach(key => {\r\n if (key !== 'error' && key !== 'message' && key !== 'statusCode') {\r\n (error as any)[key] = data[key];\r\n }\r\n });\r\n throw error;\r\n }\r\n throw new InsForgeError(\r\n `Request failed: ${response.statusText}`,\r\n response.status,\r\n 'REQUEST_FAILED'\r\n );\r\n }\r\n\r\n return data as T;\r\n }\r\n\r\n get<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('GET', path, options);\r\n }\r\n\r\n post<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('POST', path, { ...options, body });\r\n }\r\n\r\n put<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PUT', path, { ...options, body });\r\n }\r\n\r\n patch<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PATCH', path, { ...options, body });\r\n }\r\n\r\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('DELETE', path, options);\r\n }\r\n\r\n setAuthToken(token: string | null) {\r\n this.userToken = token;\r\n }\r\n\r\n getHeaders(): Record<string, string> {\r\n const headers = { ...this.defaultHeaders };\r\n \r\n // Include Authorization header if token is available (same logic as request method)\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n headers['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n return headers;\r\n }\r\n}","import { TokenStorage, AuthSession } from '../types';\r\n\r\nconst TOKEN_KEY = 'insforge-auth-token';\r\nconst USER_KEY = 'insforge-auth-user';\r\n\r\nexport class TokenManager {\r\n private storage: TokenStorage;\r\n\r\n constructor(storage?: TokenStorage) {\r\n if (storage) {\r\n // Use provided storage\r\n this.storage = storage;\r\n } else if (typeof window !== 'undefined' && window.localStorage) {\r\n // Browser: use localStorage\r\n this.storage = window.localStorage;\r\n } else {\r\n // Node.js: use in-memory storage\r\n const store = new Map<string, string>();\r\n this.storage = {\r\n getItem: (key: string) => store.get(key) || null,\r\n setItem: (key: string, value: string) => { store.set(key, value); },\r\n removeItem: (key: string) => { store.delete(key); }\r\n };\r\n }\r\n }\r\n\r\n saveSession(session: AuthSession): void {\r\n this.storage.setItem(TOKEN_KEY, session.accessToken);\r\n this.storage.setItem(USER_KEY, JSON.stringify(session.user));\r\n }\r\n\r\n getSession(): AuthSession | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n const userStr = this.storage.getItem(USER_KEY);\r\n\r\n if (!token || !userStr) {\r\n return null;\r\n }\r\n\r\n try {\r\n const user = JSON.parse(userStr as string);\r\n return { accessToken: token as string, user };\r\n } catch {\r\n this.clearSession();\r\n return null;\r\n }\r\n }\r\n\r\n getAccessToken(): string | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n return typeof token === 'string' ? token : null;\r\n }\r\n\r\n clearSession(): void {\r\n this.storage.removeItem(TOKEN_KEY);\r\n this.storage.removeItem(USER_KEY);\r\n }\r\n}","/**\r\n * Database module using @supabase/postgrest-js\r\n * Complete replacement for custom QueryBuilder with full PostgREST features\r\n */\r\n\r\nimport { PostgrestClient } from '@supabase/postgrest-js';\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\n\r\n\r\n/**\r\n * Custom fetch that transforms URLs and adds auth\r\n */\r\nfunction createInsForgePostgrestFetch(\r\n httpClient: HttpClient,\r\n tokenManager: TokenManager\r\n): typeof fetch {\r\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\r\n const url = typeof input === 'string' ? input : input.toString();\r\n const urlObj = new URL(url);\r\n \r\n // Extract table name from pathname\r\n // postgrest-js sends: http://dummy/tablename?params\r\n // We need: http://localhost:7130/api/database/records/tablename?params\r\n const tableName = urlObj.pathname.slice(1); // Remove leading /\r\n \r\n // Build InsForge URL\r\n const insforgeUrl = `${httpClient.baseUrl}/api/database/records/${tableName}${urlObj.search}`;\r\n \r\n // Get auth token from TokenManager or HttpClient\r\n const token = tokenManager.getAccessToken();\r\n const httpHeaders = httpClient.getHeaders();\r\n const authToken = token || httpHeaders['Authorization']?.replace('Bearer ', '');\r\n \r\n // Prepare headers\r\n const headers = new Headers(init?.headers);\r\n if (authToken && !headers.has('Authorization')) {\r\n headers.set('Authorization', `Bearer ${authToken}`);\r\n }\r\n \r\n // Make the actual request using native fetch\r\n const response = await fetch(insforgeUrl, {\r\n ...init,\r\n headers\r\n });\r\n \r\n return response;\r\n };\r\n}\r\n\r\n/**\r\n * Database client using postgrest-js\r\n * Drop-in replacement with FULL PostgREST capabilities\r\n */\r\nexport class Database {\r\n private postgrest: PostgrestClient<any, any, any>;\r\n \r\n constructor(httpClient: HttpClient, tokenManager: TokenManager) {\r\n // Create postgrest client with custom fetch\r\n this.postgrest = new PostgrestClient<any, any, any>('http://dummy', {\r\n fetch: createInsForgePostgrestFetch(httpClient, tokenManager),\r\n headers: {}\r\n });\r\n }\r\n \r\n /**\r\n * Create a query builder for a table\r\n * \r\n * @example\r\n * // Basic query\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', userId);\r\n * \r\n * // With count (Supabase style!)\r\n * const { data, error, count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact' })\r\n * .range(0, 9);\r\n * \r\n * // Just get count, no data\r\n * const { count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact', head: true });\r\n * \r\n * // Complex queries with OR\r\n * const { data } = await client.database\r\n * .from('posts')\r\n * .select('*, users!inner(*)')\r\n * .or('status.eq.active,status.eq.pending');\r\n * \r\n * // All features work:\r\n * - Nested selects\r\n * - Foreign key expansion \r\n * - OR/AND/NOT conditions\r\n * - Count with head\r\n * - Range pagination\r\n * - Upserts\r\n */\r\n from(table: string) {\r\n // Return postgrest query builder with all features\r\n return this.postgrest.from(table);\r\n }\r\n}","/**\r\n * Auth module for InsForge SDK\r\n * Uses shared schemas for type safety\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\nimport { AuthSession, InsForgeError } from '../types';\r\nimport { Database } from './database-postgrest';\r\n\r\nimport type {\r\n CreateUserRequest,\r\n CreateUserResponse,\r\n CreateSessionRequest,\r\n CreateSessionResponse,\r\n GetCurrentSessionResponse,\r\n GetOauthUrlResponse,\r\n ListPublicOAuthProvidersResponse,\r\n OAuthProvidersSchema,\r\n PublicOAuthProvider,\r\n GetPublicEmailAuthConfigResponse,\r\n UserIdSchema,\r\n EmailSchema,\r\n RoleSchema,\r\n ProfileSchema,\r\n UpdateProfileSchema,\r\n} from '@insforge/shared-schemas';\r\n\r\n/**\r\n * Convert database profile (snake_case) to ProfileSchema (camelCase)\r\n */\r\nfunction convertDbProfileToSchema(dbProfile: any): ProfileSchema {\r\n return {\r\n id: dbProfile.id,\r\n nickname: dbProfile.nickname,\r\n avatarUrl: dbProfile.avatar_url,\r\n bio: dbProfile.bio,\r\n birthday: dbProfile.birthday,\r\n createdAt: dbProfile.created_at,\r\n updatedAt: dbProfile.updated_at,\r\n };\r\n}\r\n\r\n/**\r\n * Convert ProfileSchema (camelCase) to database format (snake_case)\r\n */\r\nfunction convertSchemaToDbProfile(profile: UpdateProfileSchema): any {\r\n const dbProfile: any = {};\r\n \r\n if (profile.nickname !== undefined) dbProfile.nickname = profile.nickname;\r\n if (profile.avatarUrl !== undefined) dbProfile.avatar_url = profile.avatarUrl;\r\n if (profile.bio !== undefined) dbProfile.bio = profile.bio;\r\n if (profile.birthday !== undefined) dbProfile.birthday = profile.birthday;\r\n \r\n return dbProfile;\r\n}\r\n\r\nexport class Auth {\r\n private database: Database;\r\n \r\n constructor(\r\n private http: HttpClient,\r\n private tokenManager: TokenManager\r\n ) {\r\n this.database = new Database(http, tokenManager);\r\n \r\n // Auto-detect OAuth callback parameters in the URL\r\n this.detectOAuthCallback();\r\n }\r\n\r\n /**\r\n * Automatically detect and handle OAuth callback parameters in the URL\r\n * This runs on initialization to seamlessly complete the OAuth flow\r\n * Matches the backend's OAuth callback response (backend/src/api/routes/auth.ts:540-544)\r\n */\r\n private detectOAuthCallback(): void {\r\n // Only run in browser environment\r\n if (typeof window === 'undefined') return;\r\n \r\n try {\r\n const params = new URLSearchParams(window.location.search);\r\n \r\n // Backend returns: access_token, user_id, email, name (optional)\r\n const accessToken = params.get('access_token');\r\n const userId = params.get('user_id');\r\n const email = params.get('email');\r\n const name = params.get('name');\r\n \r\n // Check if we have OAuth callback parameters\r\n if (accessToken && userId && email) {\r\n // Create session with the data from backend\r\n const session: AuthSession = {\r\n accessToken,\r\n user: {\r\n id: userId,\r\n email: email,\r\n name: name || '',\r\n // These fields are not provided by backend OAuth callback\r\n // They'll be populated when calling getCurrentUser()\r\n emailVerified: false,\r\n createdAt: new Date().toISOString(),\r\n updatedAt: new Date().toISOString(),\r\n } as any,\r\n };\r\n \r\n // Save session and set auth token\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(accessToken);\r\n \r\n // Clean up the URL to remove sensitive parameters\r\n const url = new URL(window.location.href);\r\n url.searchParams.delete('access_token');\r\n url.searchParams.delete('user_id');\r\n url.searchParams.delete('email');\r\n url.searchParams.delete('name');\r\n \r\n // Also handle error case from backend (line 581)\r\n if (params.has('error')) {\r\n url.searchParams.delete('error');\r\n }\r\n \r\n // Replace URL without adding to browser history\r\n window.history.replaceState({}, document.title, url.toString());\r\n }\r\n } catch (error) {\r\n // Silently continue - don't break initialization\r\n console.debug('OAuth callback detection skipped:', error);\r\n }\r\n }\r\n\r\n /**\r\n * Sign up a new user\r\n */\r\n async signUp(request: CreateUserRequest): Promise<{\r\n data: CreateUserResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateUserResponse>('/api/auth/users', request);\r\n\r\n // Save session internally only if both accessToken and user exist\r\n if (response.accessToken && response.user) {\r\n const session: AuthSession = {\r\n accessToken: response.accessToken,\r\n user: response.user,\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken);\r\n }\r\n\r\n return {\r\n data: response,\r\n error: null\r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n error instanceof Error ? error.message : 'An unexpected error occurred during sign up',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with email and password\r\n */\r\n async signInWithPassword(request: CreateSessionRequest): Promise<{\r\n data: CreateSessionResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateSessionResponse>('/api/auth/sessions', request);\r\n \r\n // Save session internally\r\n const session: AuthSession = {\r\n accessToken: response.accessToken || '',\r\n user: response.user || {\r\n id: '',\r\n email: '',\r\n name: '',\r\n emailVerified: false,\r\n createdAt: '',\r\n updatedAt: '',\r\n },\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken || '');\r\n\r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during sign in',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with OAuth provider\r\n */\r\n async signInWithOAuth(options: {\r\n provider: OAuthProvidersSchema;\r\n redirectTo?: string;\r\n skipBrowserRedirect?: boolean;\r\n }): Promise<{\r\n data: { url?: string; provider?: string };\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const { provider, redirectTo, skipBrowserRedirect } = options;\r\n \r\n const params = redirectTo \r\n ? { redirect_uri: redirectTo } \r\n : undefined;\r\n \r\n const endpoint = `/api/auth/oauth/${provider}`;\r\n const response = await this.http.get<GetOauthUrlResponse>(endpoint, { params });\r\n \r\n // Automatically redirect in browser unless told not to\r\n if (typeof window !== 'undefined' && !skipBrowserRedirect) {\r\n window.location.href = response.authUrl;\r\n return { data: {}, error: null };\r\n }\r\n\r\n return { \r\n data: { \r\n url: response.authUrl,\r\n provider \r\n }, \r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: {}, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: {}, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during OAuth initialization',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign out the current user\r\n */\r\n async signOut(): Promise<{ error: InsForgeError | null }> {\r\n try {\r\n this.tokenManager.clearSession();\r\n this.http.setAuthToken(null);\r\n return { error: null };\r\n } catch (error) {\r\n return { \r\n error: new InsForgeError(\r\n 'Failed to sign out',\r\n 500,\r\n 'SIGNOUT_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get list of available OAuth providers\r\n * Returns the list of OAuth providers configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Array of configured OAuth providers with their configuration status\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getOAuthProviders();\r\n * if (data) {\r\n * // data is an array of PublicOAuthProvider: [{ provider: 'google', isConfigured: true }, ...]\r\n * data.forEach(p => console.log(`${p.provider}: ${p.isConfigured ? 'configured' : 'not configured'}`));\r\n * }\r\n * ```\r\n */\r\n async getOAuthProviders(): Promise<{\r\n data: PublicOAuthProvider[] | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<ListPublicOAuthProvidersResponse>('/api/auth/oauth/providers');\r\n \r\n return { \r\n data: response.data,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching OAuth providers',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public email authentication configuration\r\n * Returns email authentication settings configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Email authentication configuration including password requirements and email verification settings\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getEmailAuthConfig();\r\n * if (data) {\r\n * console.log(`Password min length: ${data.passwordMinLength}`);\r\n * console.log(`Requires email verification: ${data.requireEmailVerification}`);\r\n * console.log(`Requires uppercase: ${data.requireUppercase}`);\r\n * }\r\n * ```\r\n */\r\n async getEmailAuthConfig(): Promise<{\r\n data: GetPublicEmailAuthConfigResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<GetPublicEmailAuthConfigResponse>('/api/auth/email/public-config');\r\n \r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching email authentication configuration',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get the current user with full profile information\r\n * Returns both auth info (id, email, role) and profile data (nickname, avatar_url, bio, etc.)\r\n */\r\n async getCurrentUser(): Promise<{\r\n data: {\r\n user: {\r\n id: UserIdSchema;\r\n email: EmailSchema;\r\n role: RoleSchema;\r\n };\r\n profile: ProfileSchema | null;\r\n } | null;\r\n error: any | null;\r\n }> {\r\n try {\r\n // Check if we have a token\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { data: null, error: null };\r\n }\r\n\r\n // Call the API for auth info\r\n this.http.setAuthToken(session.accessToken);\r\n const authResponse = await this.http.get<GetCurrentSessionResponse>('/api/auth/sessions/current');\r\n \r\n // Get the user's profile using query builder\r\n const { data: profile, error: profileError } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', authResponse.user.id)\r\n .single();\r\n \r\n // For database errors, return PostgrestError directly\r\n if (profileError && (profileError as any).code !== 'PGRST116') { // PGRST116 = not found\r\n return { data: null, error: profileError };\r\n }\r\n \r\n return {\r\n data: {\r\n user: authResponse.user,\r\n profile: profile ? convertDbProfileToSchema(profile) : null\r\n },\r\n error: null\r\n };\r\n } catch (error) {\r\n // If unauthorized, clear session\r\n if (error instanceof InsForgeError && error.statusCode === 401) {\r\n await this.signOut();\r\n return { data: null, error: null };\r\n }\r\n \r\n // Pass through all other errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching user',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get any user's profile by ID\r\n * Returns profile information from the users table (nickname, avatarUrl, bio, etc.)\r\n */\r\n async getProfile(userId: string): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n const { data, error } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', userId)\r\n .single();\r\n \r\n // Handle not found as null, not error\r\n if (error && (error as any).code === 'PGRST116') {\r\n return { data: null, error: null };\r\n }\r\n \r\n // Convert database format to schema format\r\n if (data) {\r\n return { data: convertDbProfileToSchema(data), error: null };\r\n }\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data: null, error };\r\n }\r\n\r\n /**\r\n * Get the current session (only session data, no API call)\r\n * Returns the stored JWT token and basic user info from local storage\r\n */\r\n getCurrentSession(): {\r\n data: { session: AuthSession | null };\r\n error: InsForgeError | null;\r\n } {\r\n try {\r\n const session = this.tokenManager.getSession();\r\n \r\n if (session?.accessToken) {\r\n this.http.setAuthToken(session.accessToken);\r\n return { data: { session }, error: null };\r\n }\r\n\r\n return { data: { session: null }, error: null };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: { session: null }, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: { session: null }, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while getting session',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Set/Update the current user's profile\r\n * Updates profile information in the users table (nickname, avatarUrl, bio, etc.)\r\n */\r\n async setProfile(profile: UpdateProfileSchema): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n // Get current session to get user ID\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'No authenticated user found',\r\n 401,\r\n 'UNAUTHENTICATED'\r\n )\r\n };\r\n }\r\n \r\n // If no user ID in session (edge function scenario), fetch it\r\n if (!session.user?.id) {\r\n const { data, error } = await this.getCurrentUser();\r\n if (error) {\r\n return { data: null, error };\r\n }\r\n if (data?.user) {\r\n // Update session with minimal user info\r\n session.user = {\r\n id: data.user.id,\r\n email: data.user.email,\r\n name: data.profile?.nickname || '', // Not available from API, but required by UserSchema\r\n emailVerified: false, // Not available from API, but required by UserSchema\r\n createdAt: new Date().toISOString(), // Fallback\r\n updatedAt: new Date().toISOString(), // Fallback\r\n };\r\n this.tokenManager.saveSession(session);\r\n }\r\n }\r\n\r\n // Convert schema format to database format\r\n const dbProfile = convertSchemaToDbProfile(profile);\r\n\r\n // Update the profile using query builder\r\n const { data, error } = await this.database\r\n .from('users')\r\n .update(dbProfile)\r\n .eq('id', session.user.id)\r\n .select()\r\n .single();\r\n \r\n // Convert database format back to schema format\r\n if (data) {\r\n return { data: convertDbProfileToSchema(data), error: null };\r\n }\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data: null, error };\r\n }\r\n\r\n\r\n}","/**\r\n * Storage module for InsForge SDK\r\n * Handles file uploads, downloads, and bucket management\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { InsForgeError } from '../types';\r\nimport type { \r\n StorageFileSchema,\r\n ListObjectsResponseSchema\r\n} from '@insforge/shared-schemas';\r\n\r\nexport interface StorageResponse<T> {\r\n data: T | null;\r\n error: InsForgeError | null;\r\n}\r\n\r\ninterface UploadStrategy {\r\n method: 'direct' | 'presigned';\r\n uploadUrl: string;\r\n fields?: Record<string, string>;\r\n key: string;\r\n confirmRequired: boolean;\r\n confirmUrl?: string;\r\n expiresAt?: Date;\r\n}\r\n\r\ninterface DownloadStrategy {\r\n method: 'direct' | 'presigned';\r\n url: string;\r\n expiresAt?: Date;\r\n}\r\n\r\n/**\r\n * Storage bucket operations\r\n */\r\nexport class StorageBucket {\r\n constructor(\r\n private bucketName: string,\r\n private http: HttpClient\r\n ) {}\r\n\r\n /**\r\n * Upload a file with a specific key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * @param file - File or Blob to upload\r\n */\r\n async upload(\r\n path: string,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename: path,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'PUT',\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Upload a file with auto-generated key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param file - File or Blob to upload\r\n */\r\n async uploadAuto(\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n const filename = file instanceof File ? file.name : 'file';\r\n \r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'POST',\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Internal method to handle presigned URL uploads\r\n */\r\n private async uploadWithPresignedUrl(\r\n strategy: UploadStrategy,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Upload to presigned URL (e.g., S3)\r\n const formData = new FormData();\r\n \r\n // Add all fields from the presigned URL\r\n if (strategy.fields) {\r\n Object.entries(strategy.fields).forEach(([key, value]) => {\r\n formData.append(key, value);\r\n });\r\n }\r\n \r\n // File must be the last field for S3\r\n formData.append('file', file);\r\n\r\n const uploadResponse = await fetch(strategy.uploadUrl, {\r\n method: 'POST',\r\n body: formData\r\n });\r\n\r\n if (!uploadResponse.ok) {\r\n throw new InsForgeError(\r\n `Upload to storage failed: ${uploadResponse.statusText}`,\r\n uploadResponse.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n\r\n // Confirm upload with backend if required\r\n if (strategy.confirmRequired && strategy.confirmUrl) {\r\n const confirmResponse = await this.http.post<StorageFileSchema>(\r\n strategy.confirmUrl,\r\n {\r\n size: file.size,\r\n contentType: file.type || 'application/octet-stream'\r\n }\r\n );\r\n\r\n return { data: confirmResponse, error: null };\r\n }\r\n\r\n // If no confirmation required, return basic file info\r\n return {\r\n data: {\r\n key: strategy.key,\r\n bucket: this.bucketName,\r\n size: file.size,\r\n mimeType: file.type || 'application/octet-stream',\r\n uploadedAt: new Date().toISOString(),\r\n url: this.getPublicUrl(strategy.key)\r\n } as StorageFileSchema,\r\n error: null\r\n };\r\n } catch (error) {\r\n throw error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Presigned upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Download a file\r\n * Uses the download strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * Returns the file as a Blob\r\n */\r\n async download(path: string): Promise<{ data: Blob | null; error: InsForgeError | null }> {\r\n try {\r\n // Get download strategy from backend - this is required\r\n const strategyResponse = await this.http.post<DownloadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}/download-strategy`,\r\n { expiresIn: 3600 }\r\n );\r\n\r\n // Use URL from strategy\r\n const downloadUrl = strategyResponse.url;\r\n \r\n // Download from the URL\r\n const headers: HeadersInit = {};\r\n \r\n // Only add auth header for direct downloads (not presigned URLs)\r\n if (strategyResponse.method === 'direct') {\r\n Object.assign(headers, this.http.getHeaders());\r\n }\r\n \r\n const response = await fetch(downloadUrl, {\r\n method: 'GET',\r\n headers\r\n });\r\n\r\n if (!response.ok) {\r\n try {\r\n const error = await response.json();\r\n throw InsForgeError.fromApiError(error);\r\n } catch {\r\n throw new InsForgeError(\r\n `Download failed: ${response.statusText}`,\r\n response.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n const blob = await response.blob();\r\n return { data: blob, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Download failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public URL for a file\r\n * @param path - The object key/path\r\n */\r\n getPublicUrl(path: string): string {\r\n return `${this.http.baseUrl}/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`;\r\n }\r\n\r\n /**\r\n * List objects in the bucket\r\n * @param prefix - Filter by key prefix\r\n * @param search - Search in file names\r\n * @param limit - Maximum number of results (default: 100, max: 1000)\r\n * @param offset - Number of results to skip\r\n */\r\n async list(options?: {\r\n prefix?: string;\r\n search?: string;\r\n limit?: number;\r\n offset?: number;\r\n }): Promise<StorageResponse<ListObjectsResponseSchema>> {\r\n try {\r\n const params: Record<string, string> = {};\r\n \r\n if (options?.prefix) params.prefix = options.prefix;\r\n if (options?.search) params.search = options.search;\r\n if (options?.limit) params.limit = options.limit.toString();\r\n if (options?.offset) params.offset = options.offset.toString();\r\n\r\n const response = await this.http.get<ListObjectsResponseSchema>(\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n { params }\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'List failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Delete a file\r\n * @param path - The object key/path\r\n */\r\n async remove(path: string): Promise<StorageResponse<{ message: string }>> {\r\n try {\r\n const response = await this.http.delete<{ message: string }>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Delete failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Storage module for file operations\r\n */\r\nexport class Storage {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Get a bucket instance for operations\r\n * @param bucketName - Name of the bucket\r\n */\r\n from(bucketName: string): StorageBucket {\r\n return new StorageBucket(bucketName, this.http);\r\n }\r\n}","/**\r\n * AI Module for Insforge SDK\r\n * Response format roughly matches OpenAI SDK for compatibility\r\n *\r\n * The backend handles all the complexity of different AI providers\r\n * and returns a unified format. This SDK transforms responses to match OpenAI-like format.\r\n */\r\n\r\nimport { HttpClient } from \"../lib/http-client\";\r\nimport {\r\n ChatCompletionRequest,\r\n ChatCompletionResponse,\r\n ImageGenerationRequest,\r\n ImageGenerationResponse,\r\n} from \"@insforge/shared-schemas\";\r\n\r\nexport class AI {\r\n public readonly chat: Chat;\r\n public readonly images: Images;\r\n\r\n constructor(private http: HttpClient) {\r\n this.chat = new Chat(http);\r\n this.images = new Images(http);\r\n }\r\n}\r\n\r\nclass Chat {\r\n public readonly completions: ChatCompletions;\r\n\r\n constructor(http: HttpClient) {\r\n this.completions = new ChatCompletions(http);\r\n }\r\n}\r\n\r\nclass ChatCompletions {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Create a chat completion - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Non-streaming\r\n * const completion = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Hello!' }]\r\n * });\r\n * console.log(completion.choices[0].message.content);\r\n *\r\n * // With images\r\n * const response = await client.ai.chat.completions.create({\r\n * model: 'gpt-4-vision',\r\n * messages: [{\r\n * role: 'user',\r\n * content: 'What is in this image?',\r\n * images: [{ url: 'https://example.com/image.jpg' }]\r\n * }]\r\n * });\r\n *\r\n * // Streaming - returns async iterable\r\n * const stream = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Tell me a story' }],\r\n * stream: true\r\n * });\r\n *\r\n * for await (const chunk of stream) {\r\n * if (chunk.choices[0]?.delta?.content) {\r\n * process.stdout.write(chunk.choices[0].delta.content);\r\n * }\r\n * }\r\n * ```\r\n */\r\n async create(params: ChatCompletionRequest): Promise<any> {\r\n // Backend already expects camelCase, no transformation needed\r\n const backendParams = {\r\n model: params.model,\r\n messages: params.messages,\r\n temperature: params.temperature,\r\n maxTokens: params.maxTokens,\r\n topP: params.topP,\r\n stream: params.stream,\r\n };\r\n\r\n // For streaming, return an async iterable that yields OpenAI-like chunks\r\n if (params.stream) {\r\n const headers = this.http.getHeaders();\r\n headers[\"Content-Type\"] = \"application/json\";\r\n\r\n const response = await this.http.fetch(\r\n `${this.http.baseUrl}/api/ai/chat/completion`,\r\n {\r\n method: \"POST\",\r\n headers,\r\n body: JSON.stringify(backendParams),\r\n }\r\n );\r\n\r\n if (!response.ok) {\r\n const error = await response.json();\r\n throw new Error(error.error || \"Stream request failed\");\r\n }\r\n\r\n // Return async iterable that parses SSE and transforms to OpenAI-like format\r\n return this.parseSSEStream(response, params.model);\r\n }\r\n\r\n // Non-streaming: transform response to OpenAI-like format\r\n const response: ChatCompletionResponse = await this.http.post(\r\n \"/api/ai/chat/completion\",\r\n backendParams\r\n );\r\n\r\n // Transform to OpenAI-like format\r\n const content = response.text || \"\";\r\n\r\n return {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion\",\r\n created: Math.floor(Date.now() / 1000),\r\n model: response.metadata?.model,\r\n choices: [\r\n {\r\n index: 0,\r\n message: {\r\n role: \"assistant\",\r\n content,\r\n },\r\n finish_reason: \"stop\",\r\n },\r\n ],\r\n usage: response.metadata?.usage || {\r\n prompt_tokens: 0,\r\n completion_tokens: 0,\r\n total_tokens: 0,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Parse SSE stream into async iterable of OpenAI-like chunks\r\n */\r\n private async *parseSSEStream(\r\n response: Response,\r\n model: string\r\n ): AsyncIterableIterator<any> {\r\n const reader = response.body!.getReader();\r\n const decoder = new TextDecoder();\r\n let buffer = \"\";\r\n\r\n try {\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n\r\n buffer += decoder.decode(value, { stream: true });\r\n const lines = buffer.split(\"\\n\");\r\n buffer = lines.pop() || \"\";\r\n\r\n for (const line of lines) {\r\n if (line.startsWith(\"data: \")) {\r\n const dataStr = line.slice(6).trim();\r\n if (dataStr) {\r\n try {\r\n const data = JSON.parse(dataStr);\r\n\r\n // Transform to OpenAI-like streaming format\r\n if (data.chunk || data.content) {\r\n yield {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion.chunk\",\r\n created: Math.floor(Date.now() / 1000),\r\n model,\r\n choices: [\r\n {\r\n index: 0,\r\n delta: {\r\n content: data.chunk || data.content,\r\n },\r\n finish_reason: data.done ? \"stop\" : null,\r\n },\r\n ],\r\n };\r\n }\r\n\r\n // If we received the done signal, we can stop\r\n if (data.done) {\r\n reader.releaseLock();\r\n return;\r\n }\r\n } catch (e) {\r\n // Skip invalid JSON\r\n console.warn(\"Failed to parse SSE data:\", dataStr);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n reader.releaseLock();\r\n }\r\n }\r\n}\r\n\r\nclass Images {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Generate images - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Text-to-image\r\n * const response = await client.ai.images.generate({\r\n * model: 'dall-e-3',\r\n * prompt: 'A sunset over mountains',\r\n * });\r\n * console.log(response.images[0].url);\r\n *\r\n * // Image-to-image (with input images)\r\n * const response = await client.ai.images.generate({\r\n * model: 'stable-diffusion-xl',\r\n * prompt: 'Transform this into a watercolor painting',\r\n * images: [\r\n * { url: 'https://example.com/input.jpg' },\r\n * // or base64-encoded Data URI:\r\n * { url: 'data:image/jpeg;base64,/9j/4AAQ...' }\r\n * ]\r\n * });\r\n * ```\r\n */\r\n async generate(params: ImageGenerationRequest): Promise<any> {\r\n const response: ImageGenerationResponse = await this.http.post(\r\n \"/api/ai/image/generation\",\r\n params\r\n );\r\n \r\n // Build data array based on response content\r\n let data: Array<{ b64_json?: string; content?: string }> = [];\r\n \r\n if (response.images && response.images.length > 0) {\r\n // Has images - extract base64 and include text\r\n data = response.images.map(img => ({\r\n b64_json: img.imageUrl.replace(/^data:image\\/\\w+;base64,/, ''),\r\n content: response.text\r\n }));\r\n } else if (response.text) {\r\n // Text-only response\r\n data = [{ content: response.text }];\r\n }\r\n \r\n // Return OpenAI-compatible format\r\n return {\r\n created: Math.floor(Date.now() / 1000),\r\n data,\r\n ...(response.metadata?.usage && {\r\n usage: {\r\n total_tokens: response.metadata.usage.totalTokens || 0,\r\n input_tokens: response.metadata.usage.promptTokens || 0,\r\n output_tokens: response.metadata.usage.completionTokens || 0,\r\n }\r\n })\r\n };\r\n }\r\n}\r\n","import { HttpClient } from '../lib/http-client';\r\n\r\nexport interface FunctionInvokeOptions {\r\n /**\r\n * The body of the request\r\n */\r\n body?: any;\r\n \r\n /**\r\n * Custom headers to send with the request\r\n */\r\n headers?: Record<string, string>;\r\n \r\n /**\r\n * HTTP method (default: POST)\r\n */\r\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\r\n}\r\n\r\n/**\r\n * Edge Functions client for invoking serverless functions\r\n * \r\n * @example\r\n * ```typescript\r\n * // Invoke a function with JSON body\r\n * const { data, error } = await client.functions.invoke('hello-world', {\r\n * body: { name: 'World' }\r\n * });\r\n * \r\n * // GET request\r\n * const { data, error } = await client.functions.invoke('get-data', {\r\n * method: 'GET'\r\n * });\r\n * ```\r\n */\r\nexport class Functions {\r\n private http: HttpClient;\r\n\r\n constructor(http: HttpClient) {\r\n this.http = http;\r\n }\r\n\r\n /**\r\n * Invokes an Edge Function\r\n * @param slug The function slug to invoke\r\n * @param options Request options\r\n */\r\n async invoke<T = any>(\r\n slug: string,\r\n options: FunctionInvokeOptions = {}\r\n ): Promise<{ data: T | null; error: Error | null }> {\r\n try {\r\n const { method = 'POST', body, headers = {} } = options;\r\n \r\n // Simple path: /functions/{slug}\r\n const path = `/functions/${slug}`;\r\n \r\n // Use the HTTP client's request method\r\n const data = await this.http.request<T>(\r\n method,\r\n path,\r\n { body, headers }\r\n );\r\n \r\n return { data, error: null };\r\n } catch (error: any) {\r\n // The HTTP client throws InsForgeError with all properties from the response\r\n // including error, message, details, statusCode, etc.\r\n // We need to preserve all of that information\r\n return { \r\n data: null, \r\n error: error // Pass through the full error object with all properties\r\n };\r\n }\r\n }\r\n}","import { InsForgeConfig } from './types';\r\nimport { HttpClient } from './lib/http-client';\r\nimport { TokenManager } from './lib/token-manager';\r\nimport { Auth } from './modules/auth';\r\nimport { Database } from './modules/database-postgrest';\r\nimport { Storage } from './modules/storage';\r\nimport { AI } from './modules/ai';\r\nimport { Functions } from './modules/functions';\r\n\r\n/**\r\n * Main InsForge SDK Client\r\n * \r\n * @example\r\n * ```typescript\r\n * import { InsForgeClient } from '@insforge/sdk';\r\n * \r\n * const client = new InsForgeClient({\r\n * baseUrl: 'http://localhost:7130'\r\n * });\r\n * \r\n * // Authentication\r\n * const session = await client.auth.register({\r\n * email: 'user@example.com',\r\n * password: 'password123',\r\n * name: 'John Doe'\r\n * });\r\n * \r\n * // Database operations\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', session.user.id)\r\n * .order('created_at', { ascending: false })\r\n * .limit(10);\r\n * \r\n * // Insert data\r\n * const { data: newPost } = await client.database\r\n * .from('posts')\r\n * .insert({ title: 'Hello', content: 'World' })\r\n * .single();\r\n * \r\n * // Invoke edge functions\r\n * const { data, error } = await client.functions.invoke('my-function', {\r\n * body: { message: 'Hello from SDK' }\r\n * });\r\n * ```\r\n */\r\nexport class InsForgeClient {\r\n private http: HttpClient;\r\n private tokenManager: TokenManager;\r\n \r\n public readonly auth: Auth;\r\n public readonly database: Database;\r\n public readonly storage: Storage;\r\n public readonly ai: AI;\r\n public readonly functions: Functions;\r\n\r\n constructor(config: InsForgeConfig = {}) {\r\n this.http = new HttpClient(config);\r\n this.tokenManager = new TokenManager(config.storage);\r\n \r\n // Check for edge function token\r\n if (config.edgeFunctionToken) {\r\n this.http.setAuthToken(config.edgeFunctionToken);\r\n // Save to token manager so getCurrentUser() works\r\n this.tokenManager.saveSession({\r\n accessToken: config.edgeFunctionToken,\r\n user: {} as any // Will be populated by getCurrentUser()\r\n });\r\n }\r\n \r\n // Check for existing session in storage\r\n const existingSession = this.tokenManager.getSession();\r\n if (existingSession?.accessToken) {\r\n this.http.setAuthToken(existingSession.accessToken);\r\n }\r\n \r\n this.auth = new Auth(\r\n this.http,\r\n this.tokenManager\r\n );\r\n \r\n this.database = new Database(this.http, this.tokenManager);\r\n this.storage = new Storage(this.http);\r\n this.ai = new AI(this.http);\r\n this.functions = new Functions(this.http);\r\n }\r\n\r\n /**\r\n * Get the underlying HTTP client for custom requests\r\n * \r\n * @example\r\n * ```typescript\r\n * const httpClient = client.getHttpClient();\r\n * const customData = await httpClient.get('/api/custom-endpoint');\r\n * ```\r\n */\r\n getHttpClient(): HttpClient {\r\n return this.http;\r\n }\r\n\r\n /**\r\n * Future modules will be added here:\r\n * - database: Database operations\r\n * - storage: File storage operations\r\n * - functions: Serverless functions\r\n * - tables: Table management\r\n * - metadata: Backend metadata\r\n */\r\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC0EO,IAAM,gBAAN,MAAM,uBAAsB,MAAM;AAAA,EAKvC,YAAY,SAAiB,YAAoB,O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A,IAC7B,SAAS,OAAY;AAInB,aAAO;AAAA,QACL,MAAM;AAAA,QACN;AAAA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AC5BO,IAAM,iBAAN,MAAqB;AAAA,EAU1B,YAAY,SAAyB,CAAC,GAAG;AACvC,SAAK,OAAO,IAAI,WAAW,MAAM;AACjC,SAAK,eAAe,IAAI,aAAa,OAAO,OAAO;AAGnD,QAAI,OAAO,mBAAmB;AAC5B,WAAK,KAAK,aAAa,OAAO,iBAAiB;AAE/C,WAAK,aAAa,YAAY;AAAA,QAC5B,aAAa,OAAO;AAAA,QACpB,MAAM,CAAC;AAAA;AAAA,MACT,CAAC;AAAA,IACH;AAGA,UAAM,kBAAkB,KAAK,aAAa,WAAW;AACrD,QAAI,iBAAiB,aAAa;AAChC,WAAK,KAAK,aAAa,gBAAgB,WAAW;AAAA,IACpD;AAEA,SAAK,OAAO,IAAI;AAAA,MACd,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAEA,SAAK,WAAW,IAAI,SAAS,KAAK,MAAM,KAAK,YAAY;AACzD,SAAK,UAAU,IAAI,QAAQ,KAAK,IAAI;AACpC,SAAK,KAAK,IAAI,GAAG,KAAK,IAAI;AAC1B,SAAK,YAAY,IAAI,UAAU,KAAK,IAAI;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,gBAA4B;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUF;;;ATvDO,SAAS,aAAa,QAAwC;AACnE,SAAO,IAAI,eAAe,MAAM;AAClC;AAGA,IAAO,gBAAQ;","names":["data","error","response"]}
package/dist/index.mjs CHANGED
@@ -255,6 +255,25 @@ var Database = class {
255
255
  };
256
256
 
257
257
  // src/modules/auth.ts
258
+ function convertDbProfileToSchema(dbProfile) {
259
+ return {
260
+ id: dbProfile.id,
261
+ nickname: dbProfile.nickname,
262
+ avatarUrl: dbProfile.avatar_url,
263
+ bio: dbProfile.bio,
264
+ birthday: dbProfile.birthday,
265
+ createdAt: dbProfile.created_at,
266
+ updatedAt: dbProfile.updated_at
267
+ };
268
+ }
269
+ function convertSchemaToDbProfile(profile) {
270
+ const dbProfile = {};
271
+ if (profile.nickname !== void 0) dbProfile.nickname = profile.nickname;
272
+ if (profile.avatarUrl !== void 0) dbProfile.avatar_url = profile.avatarUrl;
273
+ if (profile.bio !== void 0) dbProfile.bio = profile.bio;
274
+ if (profile.birthday !== void 0) dbProfile.birthday = profile.birthday;
275
+ return dbProfile;
276
+ }
258
277
  var Auth = class {
259
278
  constructor(http, tokenManager) {
260
279
  this.http = http;
@@ -520,7 +539,7 @@ var Auth = class {
520
539
  return {
521
540
  data: {
522
541
  user: authResponse.user,
523
- profile
542
+ profile: profile ? convertDbProfileToSchema(profile) : null
524
543
  },
525
544
  error: null
526
545
  };
@@ -544,14 +563,17 @@ var Auth = class {
544
563
  }
545
564
  /**
546
565
  * Get any user's profile by ID
547
- * Returns profile information from the users table (nickname, avatar_url, bio, etc.)
566
+ * Returns profile information from the users table (nickname, avatarUrl, bio, etc.)
548
567
  */
549
568
  async getProfile(userId) {
550
569
  const { data, error } = await this.database.from("users").select("*").eq("id", userId).single();
551
570
  if (error && error.code === "PGRST116") {
552
571
  return { data: null, error: null };
553
572
  }
554
- return { data, error };
573
+ if (data) {
574
+ return { data: convertDbProfileToSchema(data), error: null };
575
+ }
576
+ return { data: null, error };
555
577
  }
556
578
  /**
557
579
  * Get the current session (only session data, no API call)
@@ -581,7 +603,7 @@ var Auth = class {
581
603
  }
582
604
  /**
583
605
  * Set/Update the current user's profile
584
- * Updates profile information in the users table (nickname, avatar_url, bio, etc.)
606
+ * Updates profile information in the users table (nickname, avatarUrl, bio, etc.)
585
607
  */
586
608
  async setProfile(profile) {
587
609
  const session = this.tokenManager.getSession();
@@ -616,8 +638,12 @@ var Auth = class {
616
638
  this.tokenManager.saveSession(session);
617
639
  }
618
640
  }
619
- const { data, error } = await this.database.from("users").update(profile).eq("id", session.user.id).select().single();
620
- return { data, error };
641
+ const dbProfile = convertSchemaToDbProfile(profile);
642
+ const { data, error } = await this.database.from("users").update(dbProfile).eq("id", session.user.id).select().single();
643
+ if (data) {
644
+ return { data: convertDbProfileToSchema(data), error: null };
645
+ }
646
+ return { data: null, error };
621
647
  }
622
648
  };
623
649
 
@@ -1 +1 @@
1
- {"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":["/**\r\n * InsForge SDK Types - only SDK-specific types here\r\n * Use @insforge/shared-schemas directly for API types\r\n */\r\n\r\nimport type { UserSchema } from '@insforge/shared-schemas';\r\n\r\nexport interface InsForgeConfig {\r\n /**\r\n * The base URL of the InsForge backend API\r\n * @default \"http://localhost:7130\"\r\n */\r\n baseUrl?: string;\r\n\r\n /**\r\n * Anonymous API key (optional)\r\n * Used for public/unauthenticated requests when no user token is set\r\n */\r\n anonKey?: string;\r\n\r\n /**\r\n * Edge Function Token (optional)\r\n * Use this when running in edge functions/serverless with a user's JWT token\r\n * This token will be used for all authenticated requests\r\n */\r\n edgeFunctionToken?: string;\r\n\r\n /**\r\n * Custom fetch implementation (useful for Node.js environments)\r\n */\r\n fetch?: typeof fetch;\r\n\r\n /**\r\n * Storage adapter for persisting tokens\r\n */\r\n storage?: TokenStorage;\r\n\r\n /**\r\n * Whether to automatically refresh tokens before they expire\r\n * @default true\r\n */\r\n autoRefreshToken?: boolean;\r\n\r\n /**\r\n * Whether to persist session in storage\r\n * @default true\r\n */\r\n persistSession?: boolean;\r\n\r\n /**\r\n * Custom headers to include with every request\r\n */\r\n headers?: Record<string, string>;\r\n}\r\n\r\nexport interface TokenStorage {\r\n getItem(key: string): string | null | Promise<string | null>;\r\n setItem(key: string, value: string): void | Promise<void>;\r\n removeItem(key: string): void | Promise<void>;\r\n}\r\n\r\nexport interface AuthSession {\r\n user: UserSchema;\r\n accessToken: string;\r\n expiresAt?: Date;\r\n}\r\n\r\nexport interface ApiError {\r\n error: string;\r\n message: string;\r\n statusCode: number;\r\n nextActions?: string;\r\n}\r\n\r\nexport class InsForgeError extends Error {\r\n public statusCode: number;\r\n public error: string;\r\n public nextActions?: string;\r\n\r\n constructor(message: string, statusCode: number, error: string, nextActions?: string) {\r\n super(message);\r\n this.name = 'InsForgeError';\r\n this.statusCode = statusCode;\r\n this.error = error;\r\n this.nextActions = nextActions;\r\n }\r\n\r\n static fromApiError(apiError: ApiError): InsForgeError {\r\n return new InsForgeError(\r\n apiError.message,\r\n apiError.statusCode,\r\n apiError.error,\r\n apiError.nextActions\r\n );\r\n }\r\n}","import { InsForgeConfig, ApiError, InsForgeError } from '../types';\r\n\r\nexport interface RequestOptions extends RequestInit {\r\n params?: Record<string, string>;\r\n}\r\n\r\nexport class HttpClient {\r\n public readonly baseUrl: string;\r\n public readonly fetch: typeof fetch;\r\n private defaultHeaders: Record<string, string>;\r\n private anonKey: string | undefined;\r\n private userToken: string | null = null;\r\n\r\n constructor(config: InsForgeConfig) {\r\n this.baseUrl = config.baseUrl || 'http://localhost:7130';\r\n // Properly bind fetch to maintain its context\r\n this.fetch = config.fetch || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined as any);\r\n this.anonKey = config.anonKey;\r\n this.defaultHeaders = {\r\n ...config.headers,\r\n };\r\n\r\n if (!this.fetch) {\r\n throw new Error(\r\n 'Fetch is not available. Please provide a fetch implementation in the config.'\r\n );\r\n }\r\n }\r\n\r\n private buildUrl(path: string, params?: Record<string, string>): string {\r\n const url = new URL(path, this.baseUrl);\r\n if (params) {\r\n Object.entries(params).forEach(([key, value]) => {\r\n // For select parameter, preserve the exact formatting by normalizing whitespace\r\n // This ensures PostgREST relationship queries work correctly\r\n if (key === 'select') {\r\n // Normalize multiline select strings for PostgREST:\r\n // 1. Replace all whitespace (including newlines) with single space\r\n // 2. Remove spaces inside parentheses for proper PostgREST syntax\r\n // 3. Keep spaces after commas at the top level for readability\r\n let normalizedValue = value.replace(/\\s+/g, ' ').trim();\r\n \r\n // Fix spaces around parentheses and inside them\r\n normalizedValue = normalizedValue\r\n .replace(/\\s*\\(\\s*/g, '(') // Remove spaces around opening parens\r\n .replace(/\\s*\\)\\s*/g, ')') // Remove spaces around closing parens\r\n .replace(/\\(\\s+/g, '(') // Remove spaces after opening parens\r\n .replace(/\\s+\\)/g, ')') // Remove spaces before closing parens\r\n .replace(/,\\s+(?=[^()]*\\))/g, ','); // Remove spaces after commas inside parens\r\n \r\n url.searchParams.append(key, normalizedValue);\r\n } else {\r\n url.searchParams.append(key, value);\r\n }\r\n });\r\n }\r\n return url.toString();\r\n }\r\n\r\n async request<T>(\r\n method: string,\r\n path: string,\r\n options: RequestOptions = {}\r\n ): Promise<T> {\r\n const { params, headers = {}, body, ...fetchOptions } = options;\r\n \r\n const url = this.buildUrl(path, params);\r\n \r\n const requestHeaders: Record<string, string> = {\r\n ...this.defaultHeaders,\r\n };\r\n \r\n // Set Authorization header: prefer user token, fallback to anon key\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n requestHeaders['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n // Handle body serialization\r\n let processedBody: any;\r\n if (body !== undefined) {\r\n // Check if body is FormData (for file uploads)\r\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\r\n // Don't set Content-Type for FormData, let browser set it with boundary\r\n processedBody = body;\r\n } else {\r\n // JSON body\r\n if (method !== 'GET') {\r\n requestHeaders['Content-Type'] = 'application/json;charset=UTF-8';\r\n }\r\n processedBody = JSON.stringify(body);\r\n }\r\n }\r\n \r\n Object.assign(requestHeaders, headers);\r\n \r\n const response = await this.fetch(url, {\r\n method,\r\n headers: requestHeaders,\r\n body: processedBody,\r\n ...fetchOptions,\r\n });\r\n\r\n // Handle 204 No Content\r\n if (response.status === 204) {\r\n return undefined as T;\r\n }\r\n\r\n // Try to parse JSON response\r\n let data: any;\r\n const contentType = response.headers.get('content-type');\r\n // Check for any JSON content type (including PostgREST's vnd.pgrst.object+json)\r\n if (contentType?.includes('json')) {\r\n data = await response.json();\r\n } else {\r\n // For non-JSON responses, return text\r\n data = await response.text();\r\n }\r\n\r\n // Handle errors\r\n if (!response.ok) {\r\n if (data && typeof data === 'object' && 'error' in data) {\r\n // Add the HTTP status code if not already in the data\r\n if (!data.statusCode && !data.status) {\r\n data.statusCode = response.status;\r\n }\r\n const error = InsForgeError.fromApiError(data as ApiError);\r\n // Preserve all additional fields from the error response\r\n Object.keys(data).forEach(key => {\r\n if (key !== 'error' && key !== 'message' && key !== 'statusCode') {\r\n (error as any)[key] = data[key];\r\n }\r\n });\r\n throw error;\r\n }\r\n throw new InsForgeError(\r\n `Request failed: ${response.statusText}`,\r\n response.status,\r\n 'REQUEST_FAILED'\r\n );\r\n }\r\n\r\n return data as T;\r\n }\r\n\r\n get<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('GET', path, options);\r\n }\r\n\r\n post<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('POST', path, { ...options, body });\r\n }\r\n\r\n put<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PUT', path, { ...options, body });\r\n }\r\n\r\n patch<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PATCH', path, { ...options, body });\r\n }\r\n\r\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('DELETE', path, options);\r\n }\r\n\r\n setAuthToken(token: string | null) {\r\n this.userToken = token;\r\n }\r\n\r\n getHeaders(): Record<string, string> {\r\n const headers = { ...this.defaultHeaders };\r\n \r\n // Include Authorization header if token is available (same logic as request method)\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n headers['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n return headers;\r\n }\r\n}","import { TokenStorage, AuthSession } from '../types';\r\n\r\nconst TOKEN_KEY = 'insforge-auth-token';\r\nconst USER_KEY = 'insforge-auth-user';\r\n\r\nexport class TokenManager {\r\n private storage: TokenStorage;\r\n\r\n constructor(storage?: TokenStorage) {\r\n if (storage) {\r\n // Use provided storage\r\n this.storage = storage;\r\n } else if (typeof window !== 'undefined' && window.localStorage) {\r\n // Browser: use localStorage\r\n this.storage = window.localStorage;\r\n } else {\r\n // Node.js: use in-memory storage\r\n const store = new Map<string, string>();\r\n this.storage = {\r\n getItem: (key: string) => store.get(key) || null,\r\n setItem: (key: string, value: string) => { store.set(key, value); },\r\n removeItem: (key: string) => { store.delete(key); }\r\n };\r\n }\r\n }\r\n\r\n saveSession(session: AuthSession): void {\r\n this.storage.setItem(TOKEN_KEY, session.accessToken);\r\n this.storage.setItem(USER_KEY, JSON.stringify(session.user));\r\n }\r\n\r\n getSession(): AuthSession | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n const userStr = this.storage.getItem(USER_KEY);\r\n\r\n if (!token || !userStr) {\r\n return null;\r\n }\r\n\r\n try {\r\n const user = JSON.parse(userStr as string);\r\n return { accessToken: token as string, user };\r\n } catch {\r\n this.clearSession();\r\n return null;\r\n }\r\n }\r\n\r\n getAccessToken(): string | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n return typeof token === 'string' ? token : null;\r\n }\r\n\r\n clearSession(): void {\r\n this.storage.removeItem(TOKEN_KEY);\r\n this.storage.removeItem(USER_KEY);\r\n }\r\n}","/**\r\n * Database module using @supabase/postgrest-js\r\n * Complete replacement for custom QueryBuilder with full PostgREST features\r\n */\r\n\r\nimport { PostgrestClient } from '@supabase/postgrest-js';\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\n\r\n\r\n/**\r\n * Custom fetch that transforms URLs and adds auth\r\n */\r\nfunction createInsForgePostgrestFetch(\r\n httpClient: HttpClient,\r\n tokenManager: TokenManager\r\n): typeof fetch {\r\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\r\n const url = typeof input === 'string' ? input : input.toString();\r\n const urlObj = new URL(url);\r\n \r\n // Extract table name from pathname\r\n // postgrest-js sends: http://dummy/tablename?params\r\n // We need: http://localhost:7130/api/database/records/tablename?params\r\n const tableName = urlObj.pathname.slice(1); // Remove leading /\r\n \r\n // Build InsForge URL\r\n const insforgeUrl = `${httpClient.baseUrl}/api/database/records/${tableName}${urlObj.search}`;\r\n \r\n // Get auth token from TokenManager or HttpClient\r\n const token = tokenManager.getAccessToken();\r\n const httpHeaders = httpClient.getHeaders();\r\n const authToken = token || httpHeaders['Authorization']?.replace('Bearer ', '');\r\n \r\n // Prepare headers\r\n const headers = new Headers(init?.headers);\r\n if (authToken && !headers.has('Authorization')) {\r\n headers.set('Authorization', `Bearer ${authToken}`);\r\n }\r\n \r\n // Make the actual request using native fetch\r\n const response = await fetch(insforgeUrl, {\r\n ...init,\r\n headers\r\n });\r\n \r\n return response;\r\n };\r\n}\r\n\r\n/**\r\n * Database client using postgrest-js\r\n * Drop-in replacement with FULL PostgREST capabilities\r\n */\r\nexport class Database {\r\n private postgrest: PostgrestClient<any, any, any>;\r\n \r\n constructor(httpClient: HttpClient, tokenManager: TokenManager) {\r\n // Create postgrest client with custom fetch\r\n this.postgrest = new PostgrestClient<any, any, any>('http://dummy', {\r\n fetch: createInsForgePostgrestFetch(httpClient, tokenManager),\r\n headers: {}\r\n });\r\n }\r\n \r\n /**\r\n * Create a query builder for a table\r\n * \r\n * @example\r\n * // Basic query\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', userId);\r\n * \r\n * // With count (Supabase style!)\r\n * const { data, error, count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact' })\r\n * .range(0, 9);\r\n * \r\n * // Just get count, no data\r\n * const { count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact', head: true });\r\n * \r\n * // Complex queries with OR\r\n * const { data } = await client.database\r\n * .from('posts')\r\n * .select('*, users!inner(*)')\r\n * .or('status.eq.active,status.eq.pending');\r\n * \r\n * // All features work:\r\n * - Nested selects\r\n * - Foreign key expansion \r\n * - OR/AND/NOT conditions\r\n * - Count with head\r\n * - Range pagination\r\n * - Upserts\r\n */\r\n from(table: string) {\r\n // Return postgrest query builder with all features\r\n return this.postgrest.from(table);\r\n }\r\n}","/**\r\n * Auth module for InsForge SDK\r\n * Uses shared schemas for type safety\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\nimport { AuthSession, InsForgeError } from '../types';\r\nimport { Database } from './database-postgrest';\r\n\r\nimport type {\r\n CreateUserRequest,\r\n CreateUserResponse,\r\n CreateSessionRequest,\r\n CreateSessionResponse,\r\n GetCurrentSessionResponse,\r\n GetOauthUrlResponse,\r\n ListPublicOAuthProvidersResponse,\r\n OAuthProvidersSchema,\r\n PublicOAuthProvider,\r\n GetPublicEmailAuthConfigResponse,\r\n UserIdSchema,\r\n EmailSchema,\r\n RoleSchema,\r\n ProfileSchema,\r\n UpdateProfileSchema,\r\n} from '@insforge/shared-schemas';\r\n\r\nexport class Auth {\r\n private database: Database;\r\n \r\n constructor(\r\n private http: HttpClient,\r\n private tokenManager: TokenManager\r\n ) {\r\n this.database = new Database(http, tokenManager);\r\n \r\n // Auto-detect OAuth callback parameters in the URL\r\n this.detectOAuthCallback();\r\n }\r\n\r\n /**\r\n * Automatically detect and handle OAuth callback parameters in the URL\r\n * This runs on initialization to seamlessly complete the OAuth flow\r\n * Matches the backend's OAuth callback response (backend/src/api/routes/auth.ts:540-544)\r\n */\r\n private detectOAuthCallback(): void {\r\n // Only run in browser environment\r\n if (typeof window === 'undefined') return;\r\n \r\n try {\r\n const params = new URLSearchParams(window.location.search);\r\n \r\n // Backend returns: access_token, user_id, email, name (optional)\r\n const accessToken = params.get('access_token');\r\n const userId = params.get('user_id');\r\n const email = params.get('email');\r\n const name = params.get('name');\r\n \r\n // Check if we have OAuth callback parameters\r\n if (accessToken && userId && email) {\r\n // Create session with the data from backend\r\n const session: AuthSession = {\r\n accessToken,\r\n user: {\r\n id: userId,\r\n email: email,\r\n name: name || '',\r\n // These fields are not provided by backend OAuth callback\r\n // They'll be populated when calling getCurrentUser()\r\n emailVerified: false,\r\n createdAt: new Date().toISOString(),\r\n updatedAt: new Date().toISOString(),\r\n } as any,\r\n };\r\n \r\n // Save session and set auth token\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(accessToken);\r\n \r\n // Clean up the URL to remove sensitive parameters\r\n const url = new URL(window.location.href);\r\n url.searchParams.delete('access_token');\r\n url.searchParams.delete('user_id');\r\n url.searchParams.delete('email');\r\n url.searchParams.delete('name');\r\n \r\n // Also handle error case from backend (line 581)\r\n if (params.has('error')) {\r\n url.searchParams.delete('error');\r\n }\r\n \r\n // Replace URL without adding to browser history\r\n window.history.replaceState({}, document.title, url.toString());\r\n }\r\n } catch (error) {\r\n // Silently continue - don't break initialization\r\n console.debug('OAuth callback detection skipped:', error);\r\n }\r\n }\r\n\r\n /**\r\n * Sign up a new user\r\n */\r\n async signUp(request: CreateUserRequest): Promise<{\r\n data: CreateUserResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateUserResponse>('/api/auth/users', request);\r\n\r\n // Save session internally only if both accessToken and user exist\r\n if (response.accessToken && response.user) {\r\n const session: AuthSession = {\r\n accessToken: response.accessToken,\r\n user: response.user,\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken);\r\n }\r\n\r\n return {\r\n data: response,\r\n error: null\r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n error instanceof Error ? error.message : 'An unexpected error occurred during sign up',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with email and password\r\n */\r\n async signInWithPassword(request: CreateSessionRequest): Promise<{\r\n data: CreateSessionResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateSessionResponse>('/api/auth/sessions', request);\r\n \r\n // Save session internally\r\n const session: AuthSession = {\r\n accessToken: response.accessToken || '',\r\n user: response.user || {\r\n id: '',\r\n email: '',\r\n name: '',\r\n emailVerified: false,\r\n createdAt: '',\r\n updatedAt: '',\r\n },\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken || '');\r\n\r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during sign in',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with OAuth provider\r\n */\r\n async signInWithOAuth(options: {\r\n provider: OAuthProvidersSchema;\r\n redirectTo?: string;\r\n skipBrowserRedirect?: boolean;\r\n }): Promise<{\r\n data: { url?: string; provider?: string };\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const { provider, redirectTo, skipBrowserRedirect } = options;\r\n \r\n const params = redirectTo \r\n ? { redirect_uri: redirectTo } \r\n : undefined;\r\n \r\n const endpoint = `/api/auth/oauth/${provider}`;\r\n const response = await this.http.get<GetOauthUrlResponse>(endpoint, { params });\r\n \r\n // Automatically redirect in browser unless told not to\r\n if (typeof window !== 'undefined' && !skipBrowserRedirect) {\r\n window.location.href = response.authUrl;\r\n return { data: {}, error: null };\r\n }\r\n\r\n return { \r\n data: { \r\n url: response.authUrl,\r\n provider \r\n }, \r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: {}, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: {}, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during OAuth initialization',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign out the current user\r\n */\r\n async signOut(): Promise<{ error: InsForgeError | null }> {\r\n try {\r\n this.tokenManager.clearSession();\r\n this.http.setAuthToken(null);\r\n return { error: null };\r\n } catch (error) {\r\n return { \r\n error: new InsForgeError(\r\n 'Failed to sign out',\r\n 500,\r\n 'SIGNOUT_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get list of available OAuth providers\r\n * Returns the list of OAuth providers configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Array of configured OAuth providers with their configuration status\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getOAuthProviders();\r\n * if (data) {\r\n * // data is an array of PublicOAuthProvider: [{ provider: 'google', isConfigured: true }, ...]\r\n * data.forEach(p => console.log(`${p.provider}: ${p.isConfigured ? 'configured' : 'not configured'}`));\r\n * }\r\n * ```\r\n */\r\n async getOAuthProviders(): Promise<{\r\n data: PublicOAuthProvider[] | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<ListPublicOAuthProvidersResponse>('/api/auth/oauth/providers');\r\n \r\n return { \r\n data: response.data,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching OAuth providers',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public email authentication configuration\r\n * Returns email authentication settings configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Email authentication configuration including password requirements and email verification settings\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getEmailAuthConfig();\r\n * if (data) {\r\n * console.log(`Password min length: ${data.passwordMinLength}`);\r\n * console.log(`Requires email verification: ${data.requireEmailVerification}`);\r\n * console.log(`Requires uppercase: ${data.requireUppercase}`);\r\n * }\r\n * ```\r\n */\r\n async getEmailAuthConfig(): Promise<{\r\n data: GetPublicEmailAuthConfigResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<GetPublicEmailAuthConfigResponse>('/api/auth/email/public-config');\r\n \r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching email authentication configuration',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get the current user with full profile information\r\n * Returns both auth info (id, email, role) and profile data (nickname, avatar_url, bio, etc.)\r\n */\r\n async getCurrentUser(): Promise<{\r\n data: {\r\n user: {\r\n id: UserIdSchema;\r\n email: EmailSchema;\r\n role: RoleSchema;\r\n };\r\n profile: ProfileSchema | null;\r\n } | null;\r\n error: any | null;\r\n }> {\r\n try {\r\n // Check if we have a token\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { data: null, error: null };\r\n }\r\n\r\n // Call the API for auth info\r\n this.http.setAuthToken(session.accessToken);\r\n const authResponse = await this.http.get<GetCurrentSessionResponse>('/api/auth/sessions/current');\r\n \r\n // Get the user's profile using query builder\r\n const { data: profile, error: profileError } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', authResponse.user.id)\r\n .single();\r\n \r\n // For database errors, return PostgrestError directly\r\n if (profileError && (profileError as any).code !== 'PGRST116') { // PGRST116 = not found\r\n return { data: null, error: profileError };\r\n }\r\n \r\n return {\r\n data: {\r\n user: authResponse.user,\r\n profile: profile\r\n },\r\n error: null\r\n };\r\n } catch (error) {\r\n // If unauthorized, clear session\r\n if (error instanceof InsForgeError && error.statusCode === 401) {\r\n await this.signOut();\r\n return { data: null, error: null };\r\n }\r\n \r\n // Pass through all other errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching user',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get any user's profile by ID\r\n * Returns profile information from the users table (nickname, avatar_url, bio, etc.)\r\n */\r\n async getProfile(userId: string): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n const { data, error } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', userId)\r\n .single();\r\n \r\n // Handle not found as null, not error\r\n if (error && (error as any).code === 'PGRST116') {\r\n return { data: null, error: null };\r\n }\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data, error };\r\n }\r\n\r\n /**\r\n * Get the current session (only session data, no API call)\r\n * Returns the stored JWT token and basic user info from local storage\r\n */\r\n getCurrentSession(): {\r\n data: { session: AuthSession | null };\r\n error: InsForgeError | null;\r\n } {\r\n try {\r\n const session = this.tokenManager.getSession();\r\n \r\n if (session?.accessToken) {\r\n this.http.setAuthToken(session.accessToken);\r\n return { data: { session }, error: null };\r\n }\r\n\r\n return { data: { session: null }, error: null };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: { session: null }, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: { session: null }, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while getting session',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Set/Update the current user's profile\r\n * Updates profile information in the users table (nickname, avatar_url, bio, etc.)\r\n */\r\n async setProfile(profile: UpdateProfileSchema): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n // Get current session to get user ID\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'No authenticated user found',\r\n 401,\r\n 'UNAUTHENTICATED'\r\n )\r\n };\r\n }\r\n \r\n // If no user ID in session (edge function scenario), fetch it\r\n if (!session.user?.id) {\r\n const { data, error } = await this.getCurrentUser();\r\n if (error) {\r\n return { data: null, error };\r\n }\r\n if (data?.user) {\r\n // Update session with minimal user info\r\n session.user = {\r\n id: data.user.id,\r\n email: data.user.email,\r\n name: data.profile?.nickname || '', // Not available from API, but required by UserSchema\r\n emailVerified: false, // Not available from API, but required by UserSchema\r\n createdAt: new Date().toISOString(), // Fallback\r\n updatedAt: new Date().toISOString(), // Fallback\r\n };\r\n this.tokenManager.saveSession(session);\r\n }\r\n }\r\n\r\n // Update the profile using query builder\r\n const { data, error } = await this.database\r\n .from('users')\r\n .update(profile)\r\n .eq('id', session.user.id)\r\n .select()\r\n .single();\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data, error };\r\n }\r\n\r\n\r\n}","/**\r\n * Storage module for InsForge SDK\r\n * Handles file uploads, downloads, and bucket management\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { InsForgeError } from '../types';\r\nimport type { \r\n StorageFileSchema,\r\n ListObjectsResponseSchema\r\n} from '@insforge/shared-schemas';\r\n\r\nexport interface StorageResponse<T> {\r\n data: T | null;\r\n error: InsForgeError | null;\r\n}\r\n\r\ninterface UploadStrategy {\r\n method: 'direct' | 'presigned';\r\n uploadUrl: string;\r\n fields?: Record<string, string>;\r\n key: string;\r\n confirmRequired: boolean;\r\n confirmUrl?: string;\r\n expiresAt?: Date;\r\n}\r\n\r\ninterface DownloadStrategy {\r\n method: 'direct' | 'presigned';\r\n url: string;\r\n expiresAt?: Date;\r\n}\r\n\r\n/**\r\n * Storage bucket operations\r\n */\r\nexport class StorageBucket {\r\n constructor(\r\n private bucketName: string,\r\n private http: HttpClient\r\n ) {}\r\n\r\n /**\r\n * Upload a file with a specific key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * @param file - File or Blob to upload\r\n */\r\n async upload(\r\n path: string,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename: path,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'PUT',\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Upload a file with auto-generated key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param file - File or Blob to upload\r\n */\r\n async uploadAuto(\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n const filename = file instanceof File ? file.name : 'file';\r\n \r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'POST',\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Internal method to handle presigned URL uploads\r\n */\r\n private async uploadWithPresignedUrl(\r\n strategy: UploadStrategy,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Upload to presigned URL (e.g., S3)\r\n const formData = new FormData();\r\n \r\n // Add all fields from the presigned URL\r\n if (strategy.fields) {\r\n Object.entries(strategy.fields).forEach(([key, value]) => {\r\n formData.append(key, value);\r\n });\r\n }\r\n \r\n // File must be the last field for S3\r\n formData.append('file', file);\r\n\r\n const uploadResponse = await fetch(strategy.uploadUrl, {\r\n method: 'POST',\r\n body: formData\r\n });\r\n\r\n if (!uploadResponse.ok) {\r\n throw new InsForgeError(\r\n `Upload to storage failed: ${uploadResponse.statusText}`,\r\n uploadResponse.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n\r\n // Confirm upload with backend if required\r\n if (strategy.confirmRequired && strategy.confirmUrl) {\r\n const confirmResponse = await this.http.post<StorageFileSchema>(\r\n strategy.confirmUrl,\r\n {\r\n size: file.size,\r\n contentType: file.type || 'application/octet-stream'\r\n }\r\n );\r\n\r\n return { data: confirmResponse, error: null };\r\n }\r\n\r\n // If no confirmation required, return basic file info\r\n return {\r\n data: {\r\n key: strategy.key,\r\n bucket: this.bucketName,\r\n size: file.size,\r\n mimeType: file.type || 'application/octet-stream',\r\n uploadedAt: new Date().toISOString(),\r\n url: this.getPublicUrl(strategy.key)\r\n } as StorageFileSchema,\r\n error: null\r\n };\r\n } catch (error) {\r\n throw error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Presigned upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Download a file\r\n * Uses the download strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * Returns the file as a Blob\r\n */\r\n async download(path: string): Promise<{ data: Blob | null; error: InsForgeError | null }> {\r\n try {\r\n // Get download strategy from backend - this is required\r\n const strategyResponse = await this.http.post<DownloadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}/download-strategy`,\r\n { expiresIn: 3600 }\r\n );\r\n\r\n // Use URL from strategy\r\n const downloadUrl = strategyResponse.url;\r\n \r\n // Download from the URL\r\n const headers: HeadersInit = {};\r\n \r\n // Only add auth header for direct downloads (not presigned URLs)\r\n if (strategyResponse.method === 'direct') {\r\n Object.assign(headers, this.http.getHeaders());\r\n }\r\n \r\n const response = await fetch(downloadUrl, {\r\n method: 'GET',\r\n headers\r\n });\r\n\r\n if (!response.ok) {\r\n try {\r\n const error = await response.json();\r\n throw InsForgeError.fromApiError(error);\r\n } catch {\r\n throw new InsForgeError(\r\n `Download failed: ${response.statusText}`,\r\n response.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n const blob = await response.blob();\r\n return { data: blob, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Download failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public URL for a file\r\n * @param path - The object key/path\r\n */\r\n getPublicUrl(path: string): string {\r\n return `${this.http.baseUrl}/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`;\r\n }\r\n\r\n /**\r\n * List objects in the bucket\r\n * @param prefix - Filter by key prefix\r\n * @param search - Search in file names\r\n * @param limit - Maximum number of results (default: 100, max: 1000)\r\n * @param offset - Number of results to skip\r\n */\r\n async list(options?: {\r\n prefix?: string;\r\n search?: string;\r\n limit?: number;\r\n offset?: number;\r\n }): Promise<StorageResponse<ListObjectsResponseSchema>> {\r\n try {\r\n const params: Record<string, string> = {};\r\n \r\n if (options?.prefix) params.prefix = options.prefix;\r\n if (options?.search) params.search = options.search;\r\n if (options?.limit) params.limit = options.limit.toString();\r\n if (options?.offset) params.offset = options.offset.toString();\r\n\r\n const response = await this.http.get<ListObjectsResponseSchema>(\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n { params }\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'List failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Delete a file\r\n * @param path - The object key/path\r\n */\r\n async remove(path: string): Promise<StorageResponse<{ message: string }>> {\r\n try {\r\n const response = await this.http.delete<{ message: string }>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Delete failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Storage module for file operations\r\n */\r\nexport class Storage {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Get a bucket instance for operations\r\n * @param bucketName - Name of the bucket\r\n */\r\n from(bucketName: string): StorageBucket {\r\n return new StorageBucket(bucketName, this.http);\r\n }\r\n}","/**\r\n * AI Module for Insforge SDK\r\n * Response format roughly matches OpenAI SDK for compatibility\r\n *\r\n * The backend handles all the complexity of different AI providers\r\n * and returns a unified format. This SDK transforms responses to match OpenAI-like format.\r\n */\r\n\r\nimport { HttpClient } from \"../lib/http-client\";\r\nimport {\r\n ChatCompletionRequest,\r\n ChatCompletionResponse,\r\n ImageGenerationRequest,\r\n ImageGenerationResponse,\r\n} from \"@insforge/shared-schemas\";\r\n\r\nexport class AI {\r\n public readonly chat: Chat;\r\n public readonly images: Images;\r\n\r\n constructor(private http: HttpClient) {\r\n this.chat = new Chat(http);\r\n this.images = new Images(http);\r\n }\r\n}\r\n\r\nclass Chat {\r\n public readonly completions: ChatCompletions;\r\n\r\n constructor(http: HttpClient) {\r\n this.completions = new ChatCompletions(http);\r\n }\r\n}\r\n\r\nclass ChatCompletions {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Create a chat completion - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Non-streaming\r\n * const completion = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Hello!' }]\r\n * });\r\n * console.log(completion.choices[0].message.content);\r\n *\r\n * // With images\r\n * const response = await client.ai.chat.completions.create({\r\n * model: 'gpt-4-vision',\r\n * messages: [{\r\n * role: 'user',\r\n * content: 'What is in this image?',\r\n * images: [{ url: 'https://example.com/image.jpg' }]\r\n * }]\r\n * });\r\n *\r\n * // Streaming - returns async iterable\r\n * const stream = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Tell me a story' }],\r\n * stream: true\r\n * });\r\n *\r\n * for await (const chunk of stream) {\r\n * if (chunk.choices[0]?.delta?.content) {\r\n * process.stdout.write(chunk.choices[0].delta.content);\r\n * }\r\n * }\r\n * ```\r\n */\r\n async create(params: ChatCompletionRequest): Promise<any> {\r\n // Backend already expects camelCase, no transformation needed\r\n const backendParams = {\r\n model: params.model,\r\n messages: params.messages,\r\n temperature: params.temperature,\r\n maxTokens: params.maxTokens,\r\n topP: params.topP,\r\n stream: params.stream,\r\n };\r\n\r\n // For streaming, return an async iterable that yields OpenAI-like chunks\r\n if (params.stream) {\r\n const headers = this.http.getHeaders();\r\n headers[\"Content-Type\"] = \"application/json\";\r\n\r\n const response = await this.http.fetch(\r\n `${this.http.baseUrl}/api/ai/chat/completion`,\r\n {\r\n method: \"POST\",\r\n headers,\r\n body: JSON.stringify(backendParams),\r\n }\r\n );\r\n\r\n if (!response.ok) {\r\n const error = await response.json();\r\n throw new Error(error.error || \"Stream request failed\");\r\n }\r\n\r\n // Return async iterable that parses SSE and transforms to OpenAI-like format\r\n return this.parseSSEStream(response, params.model);\r\n }\r\n\r\n // Non-streaming: transform response to OpenAI-like format\r\n const response: ChatCompletionResponse = await this.http.post(\r\n \"/api/ai/chat/completion\",\r\n backendParams\r\n );\r\n\r\n // Transform to OpenAI-like format\r\n const content = response.text || \"\";\r\n\r\n return {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion\",\r\n created: Math.floor(Date.now() / 1000),\r\n model: response.metadata?.model,\r\n choices: [\r\n {\r\n index: 0,\r\n message: {\r\n role: \"assistant\",\r\n content,\r\n },\r\n finish_reason: \"stop\",\r\n },\r\n ],\r\n usage: response.metadata?.usage || {\r\n prompt_tokens: 0,\r\n completion_tokens: 0,\r\n total_tokens: 0,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Parse SSE stream into async iterable of OpenAI-like chunks\r\n */\r\n private async *parseSSEStream(\r\n response: Response,\r\n model: string\r\n ): AsyncIterableIterator<any> {\r\n const reader = response.body!.getReader();\r\n const decoder = new TextDecoder();\r\n let buffer = \"\";\r\n\r\n try {\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n\r\n buffer += decoder.decode(value, { stream: true });\r\n const lines = buffer.split(\"\\n\");\r\n buffer = lines.pop() || \"\";\r\n\r\n for (const line of lines) {\r\n if (line.startsWith(\"data: \")) {\r\n const dataStr = line.slice(6).trim();\r\n if (dataStr) {\r\n try {\r\n const data = JSON.parse(dataStr);\r\n\r\n // Transform to OpenAI-like streaming format\r\n if (data.chunk || data.content) {\r\n yield {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion.chunk\",\r\n created: Math.floor(Date.now() / 1000),\r\n model,\r\n choices: [\r\n {\r\n index: 0,\r\n delta: {\r\n content: data.chunk || data.content,\r\n },\r\n finish_reason: data.done ? \"stop\" : null,\r\n },\r\n ],\r\n };\r\n }\r\n\r\n // If we received the done signal, we can stop\r\n if (data.done) {\r\n reader.releaseLock();\r\n return;\r\n }\r\n } catch (e) {\r\n // Skip invalid JSON\r\n console.warn(\"Failed to parse SSE data:\", dataStr);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n reader.releaseLock();\r\n }\r\n }\r\n}\r\n\r\nclass Images {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Generate images - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Text-to-image\r\n * const response = await client.ai.images.generate({\r\n * model: 'dall-e-3',\r\n * prompt: 'A sunset over mountains',\r\n * });\r\n * console.log(response.images[0].url);\r\n *\r\n * // Image-to-image (with input images)\r\n * const response = await client.ai.images.generate({\r\n * model: 'stable-diffusion-xl',\r\n * prompt: 'Transform this into a watercolor painting',\r\n * images: [\r\n * { url: 'https://example.com/input.jpg' },\r\n * // or base64-encoded Data URI:\r\n * { url: 'data:image/jpeg;base64,/9j/4AAQ...' }\r\n * ]\r\n * });\r\n * ```\r\n */\r\n async generate(params: ImageGenerationRequest): Promise<any> {\r\n const response: ImageGenerationResponse = await this.http.post(\r\n \"/api/ai/image/generation\",\r\n params\r\n );\r\n \r\n // Build data array based on response content\r\n let data: Array<{ b64_json?: string; content?: string }> = [];\r\n \r\n if (response.images && response.images.length > 0) {\r\n // Has images - extract base64 and include text\r\n data = response.images.map(img => ({\r\n b64_json: img.imageUrl.replace(/^data:image\\/\\w+;base64,/, ''),\r\n content: response.text\r\n }));\r\n } else if (response.text) {\r\n // Text-only response\r\n data = [{ content: response.text }];\r\n }\r\n \r\n // Return OpenAI-compatible format\r\n return {\r\n created: Math.floor(Date.now() / 1000),\r\n data,\r\n ...(response.metadata?.usage && {\r\n usage: {\r\n total_tokens: response.metadata.usage.totalTokens || 0,\r\n input_tokens: response.metadata.usage.promptTokens || 0,\r\n output_tokens: response.metadata.usage.completionTokens || 0,\r\n }\r\n })\r\n };\r\n }\r\n}\r\n","import { HttpClient } from '../lib/http-client';\r\n\r\nexport interface FunctionInvokeOptions {\r\n /**\r\n * The body of the request\r\n */\r\n body?: any;\r\n \r\n /**\r\n * Custom headers to send with the request\r\n */\r\n headers?: Record<string, string>;\r\n \r\n /**\r\n * HTTP method (default: POST)\r\n */\r\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\r\n}\r\n\r\n/**\r\n * Edge Functions client for invoking serverless functions\r\n * \r\n * @example\r\n * ```typescript\r\n * // Invoke a function with JSON body\r\n * const { data, error } = await client.functions.invoke('hello-world', {\r\n * body: { name: 'World' }\r\n * });\r\n * \r\n * // GET request\r\n * const { data, error } = await client.functions.invoke('get-data', {\r\n * method: 'GET'\r\n * });\r\n * ```\r\n */\r\nexport class Functions {\r\n private http: HttpClient;\r\n\r\n constructor(http: HttpClient) {\r\n this.http = http;\r\n }\r\n\r\n /**\r\n * Invokes an Edge Function\r\n * @param slug The function slug to invoke\r\n * @param options Request options\r\n */\r\n async invoke<T = any>(\r\n slug: string,\r\n options: FunctionInvokeOptions = {}\r\n ): Promise<{ data: T | null; error: Error | null }> {\r\n try {\r\n const { method = 'POST', body, headers = {} } = options;\r\n \r\n // Simple path: /functions/{slug}\r\n const path = `/functions/${slug}`;\r\n \r\n // Use the HTTP client's request method\r\n const data = await this.http.request<T>(\r\n method,\r\n path,\r\n { body, headers }\r\n );\r\n \r\n return { data, error: null };\r\n } catch (error: any) {\r\n // The HTTP client throws InsForgeError with all properties from the response\r\n // including error, message, details, statusCode, etc.\r\n // We need to preserve all of that information\r\n return { \r\n data: null, \r\n error: error // Pass through the full error object with all properties\r\n };\r\n }\r\n }\r\n}","import { InsForgeConfig } from './types';\r\nimport { HttpClient } from './lib/http-client';\r\nimport { TokenManager } from './lib/token-manager';\r\nimport { Auth } from './modules/auth';\r\nimport { Database } from './modules/database-postgrest';\r\nimport { Storage } from './modules/storage';\r\nimport { AI } from './modules/ai';\r\nimport { Functions } from './modules/functions';\r\n\r\n/**\r\n * Main InsForge SDK Client\r\n * \r\n * @example\r\n * ```typescript\r\n * import { InsForgeClient } from '@insforge/sdk';\r\n * \r\n * const client = new InsForgeClient({\r\n * baseUrl: 'http://localhost:7130'\r\n * });\r\n * \r\n * // Authentication\r\n * const session = await client.auth.register({\r\n * email: 'user@example.com',\r\n * password: 'password123',\r\n * name: 'John Doe'\r\n * });\r\n * \r\n * // Database operations\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', session.user.id)\r\n * .order('created_at', { ascending: false })\r\n * .limit(10);\r\n * \r\n * // Insert data\r\n * const { data: newPost } = await client.database\r\n * .from('posts')\r\n * .insert({ title: 'Hello', content: 'World' })\r\n * .single();\r\n * \r\n * // Invoke edge functions\r\n * const { data, error } = await client.functions.invoke('my-function', {\r\n * body: { message: 'Hello from SDK' }\r\n * });\r\n * ```\r\n */\r\nexport class InsForgeClient {\r\n private http: HttpClient;\r\n private tokenManager: TokenManager;\r\n \r\n public readonly auth: Auth;\r\n public readonly database: Database;\r\n public readonly storage: Storage;\r\n public readonly ai: AI;\r\n public readonly functions: Functions;\r\n\r\n constructor(config: InsForgeConfig = {}) {\r\n this.http = new HttpClient(config);\r\n this.tokenManager = new TokenManager(config.storage);\r\n \r\n // Check for edge function token\r\n if (config.edgeFunctionToken) {\r\n this.http.setAuthToken(config.edgeFunctionToken);\r\n // Save to token manager so getCurrentUser() works\r\n this.tokenManager.saveSession({\r\n accessToken: config.edgeFunctionToken,\r\n user: {} as any // Will be populated by getCurrentUser()\r\n });\r\n }\r\n \r\n // Check for existing session in storage\r\n const existingSession = this.tokenManager.getSession();\r\n if (existingSession?.accessToken) {\r\n this.http.setAuthToken(existingSession.accessToken);\r\n }\r\n \r\n this.auth = new Auth(\r\n this.http,\r\n this.tokenManager\r\n );\r\n \r\n this.database = new Database(this.http, this.tokenManager);\r\n this.storage = new Storage(this.http);\r\n this.ai = new AI(this.http);\r\n this.functions = new Functions(this.http);\r\n }\r\n\r\n /**\r\n * Get the underlying HTTP client for custom requests\r\n * \r\n * @example\r\n * ```typescript\r\n * const httpClient = client.getHttpClient();\r\n * const customData = await httpClient.get('/api/custom-endpoint');\r\n * ```\r\n */\r\n getHttpClient(): HttpClient {\r\n return this.http;\r\n }\r\n\r\n /**\r\n * Future modules will be added here:\r\n * - database: Database operations\r\n * - storage: File storage operations\r\n * - functions: Serverless functions\r\n * - tables: Table management\r\n * - metadata: Backend metadata\r\n */\r\n}","/**\r\n * @insforge/sdk - TypeScript SDK for InsForge Backend-as-a-Service\r\n * \r\n * @packageDocumentation\r\n */\r\n\r\n// Main client\r\nexport { InsForgeClient } from './client';\r\n\r\n// Types\r\nexport type {\r\n InsForgeConfig,\r\n InsForgeConfig as ClientOptions, // Alias for compatibility\r\n TokenStorage,\r\n AuthSession,\r\n ApiError,\r\n} from './types';\r\n\r\nexport { InsForgeError } from './types';\r\n\r\n// Re-export shared schemas that SDK users will need\r\nexport type {\r\n UserSchema,\r\n CreateUserRequest,\r\n CreateSessionRequest,\r\n AuthErrorResponse,\r\n} from '@insforge/shared-schemas';\r\n\r\n// Re-export auth module for advanced usage\r\nexport { Auth } from './modules/auth';\r\n\r\n// Re-export database module (using postgrest-js)\r\nexport { Database } from './modules/database-postgrest';\r\n// Note: QueryBuilder is no longer exported as we use postgrest-js QueryBuilder internally\r\n\r\n// Re-export storage module and types\r\nexport { Storage, StorageBucket } from './modules/storage';\r\nexport type { StorageResponse } from './modules/storage';\r\n\r\n// Re-export AI module\r\nexport { AI } from './modules/ai';\r\n\r\n// Re-export Functions module\r\nexport { Functions } from './modules/functions';\r\nexport type { FunctionInvokeOptions } from './modules/functions';\r\n\r\n// Re-export utilities for advanced usage\r\nexport { HttpClient } from './lib/http-client';\r\nexport { TokenManager } from './lib/token-manager';\r\n\r\n// Factory function for creating clients (Supabase-style)\r\nimport { InsForgeClient } from './client';\r\nimport { InsForgeConfig } from './types';\r\n\r\nexport function createClient(config: InsForgeConfig): InsForgeClient {\r\n return new InsForgeClient(config);\r\n}\r\n\r\n// Default export for convenience\r\nexport default InsForgeClient;"],"mappings":";AA0EO,IAAM,gBAAN,MAAM,uBAAsB,MAAM;AAAA,EAKvC,YAAY,SAAiB,YAAoB,OAAe,aAAsB;AACpF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,QAAQ;AACb,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,OAAO,aAAa,UAAmC;AACrD,WAAO,IAAI;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,IACX;AAAA,EACF;AACF;;;ACzFO,IAAM,aAAN,MAAiB;AAAA,EAOtB,YAAY,QAAwB;AAFpC,SAAQ,YAA2B;AAGjC,SAAK,UAAU,OAAO,WAAW;AAEjC,SAAK,QAAQ,OAAO,UAAU,WAAW,QAAQ,WAAW,MAAM,KAAK,UAAU,IAAI;AACrF,SAAK,UAAU,OAAO;AACtB,SAAK,iBAAiB;AAAA,MACpB,GAAG,OAAO;AAAA,IACZ;AAEA,QAAI,CAAC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A,QACN;AAAA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;;;AC5BO,IAAM,iBAAN,MAAqB;AAAA,EAU1B,YAAY,SAAyB,CAAC,GAAG;AACvC,SAAK,OAAO,IAAI,WAAW,MAAM;AACjC,SAAK,eAAe,IAAI,aAAa,OAAO,OAAO;AAGnD,QAAI,OAAO,mBAAmB;AAC5B,WAAK,KAAK,aAAa,OAAO,iBAAiB;AAE/C,WAAK,aAAa,YAAY;AAAA,QAC5B,aAAa,OAAO;AAAA,QACpB,MAAM,CAAC;AAAA;AAAA,MACT,CAAC;AAAA,IACH;AAGA,UAAM,kBAAkB,KAAK,aAAa,WAAW;AACrD,QAAI,iBAAiB,aAAa;AAChC,WAAK,KAAK,aAAa,gBAAgB,WAAW;AAAA,IACpD;AAEA,SAAK,OAAO,IAAI;AAAA,MACd,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAEA,SAAK,WAAW,IAAI,SAAS,KAAK,MAAM,KAAK,YAAY;AACzD,SAAK,UAAU,IAAI,QAAQ,KAAK,IAAI;AACpC,SAAK,KAAK,IAAI,GAAG,KAAK,IAAI;AAC1B,SAAK,YAAY,IAAI,UAAU,KAAK,IAAI;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,gBAA4B;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUF;;;ACvDO,SAAS,aAAa,QAAwC;AACnE,SAAO,IAAI,eAAe,MAAM;AAClC;AAGA,IAAO,gBAAQ;","names":["data","error","response"]}
1
+ {"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":["/**\r\n * InsForge SDK Types - only SDK-specific types here\r\n * Use @insforge/shared-schemas directly for API types\r\n */\r\n\r\nimport type { UserSchema } from '@insforge/shared-schemas';\r\n\r\nexport interface InsForgeConfig {\r\n /**\r\n * The base URL of the InsForge backend API\r\n * @default \"http://localhost:7130\"\r\n */\r\n baseUrl?: string;\r\n\r\n /**\r\n * Anonymous API key (optional)\r\n * Used for public/unauthenticated requests when no user token is set\r\n */\r\n anonKey?: string;\r\n\r\n /**\r\n * Edge Function Token (optional)\r\n * Use this when running in edge functions/serverless with a user's JWT token\r\n * This token will be used for all authenticated requests\r\n */\r\n edgeFunctionToken?: string;\r\n\r\n /**\r\n * Custom fetch implementation (useful for Node.js environments)\r\n */\r\n fetch?: typeof fetch;\r\n\r\n /**\r\n * Storage adapter for persisting tokens\r\n */\r\n storage?: TokenStorage;\r\n\r\n /**\r\n * Whether to automatically refresh tokens before they expire\r\n * @default true\r\n */\r\n autoRefreshToken?: boolean;\r\n\r\n /**\r\n * Whether to persist session in storage\r\n * @default true\r\n */\r\n persistSession?: boolean;\r\n\r\n /**\r\n * Custom headers to include with every request\r\n */\r\n headers?: Record<string, string>;\r\n}\r\n\r\nexport interface TokenStorage {\r\n getItem(key: string): string | null | Promise<string | null>;\r\n setItem(key: string, value: string): void | Promise<void>;\r\n removeItem(key: string): void | Promise<void>;\r\n}\r\n\r\nexport interface AuthSession {\r\n user: UserSchema;\r\n accessToken: string;\r\n expiresAt?: Date;\r\n}\r\n\r\nexport interface ApiError {\r\n error: string;\r\n message: string;\r\n statusCode: number;\r\n nextActions?: string;\r\n}\r\n\r\nexport class InsForgeError extends Error {\r\n public statusCode: number;\r\n public error: string;\r\n public nextActions?: string;\r\n\r\n constructor(message: string, statusCode: number, error: string, nextActions?: string) {\r\n super(message);\r\n this.name = 'InsForgeError';\r\n this.statusCode = statusCode;\r\n this.error = error;\r\n this.nextActions = nextActions;\r\n }\r\n\r\n static fromApiError(apiError: ApiError): InsForgeError {\r\n return new InsForgeError(\r\n apiError.message,\r\n apiError.statusCode,\r\n apiError.error,\r\n apiError.nextActions\r\n );\r\n }\r\n}","import { InsForgeConfig, ApiError, InsForgeError } from '../types';\r\n\r\nexport interface RequestOptions extends RequestInit {\r\n params?: Record<string, string>;\r\n}\r\n\r\nexport class HttpClient {\r\n public readonly baseUrl: string;\r\n public readonly fetch: typeof fetch;\r\n private defaultHeaders: Record<string, string>;\r\n private anonKey: string | undefined;\r\n private userToken: string | null = null;\r\n\r\n constructor(config: InsForgeConfig) {\r\n this.baseUrl = config.baseUrl || 'http://localhost:7130';\r\n // Properly bind fetch to maintain its context\r\n this.fetch = config.fetch || (globalThis.fetch ? globalThis.fetch.bind(globalThis) : undefined as any);\r\n this.anonKey = config.anonKey;\r\n this.defaultHeaders = {\r\n ...config.headers,\r\n };\r\n\r\n if (!this.fetch) {\r\n throw new Error(\r\n 'Fetch is not available. Please provide a fetch implementation in the config.'\r\n );\r\n }\r\n }\r\n\r\n private buildUrl(path: string, params?: Record<string, string>): string {\r\n const url = new URL(path, this.baseUrl);\r\n if (params) {\r\n Object.entries(params).forEach(([key, value]) => {\r\n // For select parameter, preserve the exact formatting by normalizing whitespace\r\n // This ensures PostgREST relationship queries work correctly\r\n if (key === 'select') {\r\n // Normalize multiline select strings for PostgREST:\r\n // 1. Replace all whitespace (including newlines) with single space\r\n // 2. Remove spaces inside parentheses for proper PostgREST syntax\r\n // 3. Keep spaces after commas at the top level for readability\r\n let normalizedValue = value.replace(/\\s+/g, ' ').trim();\r\n \r\n // Fix spaces around parentheses and inside them\r\n normalizedValue = normalizedValue\r\n .replace(/\\s*\\(\\s*/g, '(') // Remove spaces around opening parens\r\n .replace(/\\s*\\)\\s*/g, ')') // Remove spaces around closing parens\r\n .replace(/\\(\\s+/g, '(') // Remove spaces after opening parens\r\n .replace(/\\s+\\)/g, ')') // Remove spaces before closing parens\r\n .replace(/,\\s+(?=[^()]*\\))/g, ','); // Remove spaces after commas inside parens\r\n \r\n url.searchParams.append(key, normalizedValue);\r\n } else {\r\n url.searchParams.append(key, value);\r\n }\r\n });\r\n }\r\n return url.toString();\r\n }\r\n\r\n async request<T>(\r\n method: string,\r\n path: string,\r\n options: RequestOptions = {}\r\n ): Promise<T> {\r\n const { params, headers = {}, body, ...fetchOptions } = options;\r\n \r\n const url = this.buildUrl(path, params);\r\n \r\n const requestHeaders: Record<string, string> = {\r\n ...this.defaultHeaders,\r\n };\r\n \r\n // Set Authorization header: prefer user token, fallback to anon key\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n requestHeaders['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n // Handle body serialization\r\n let processedBody: any;\r\n if (body !== undefined) {\r\n // Check if body is FormData (for file uploads)\r\n if (typeof FormData !== 'undefined' && body instanceof FormData) {\r\n // Don't set Content-Type for FormData, let browser set it with boundary\r\n processedBody = body;\r\n } else {\r\n // JSON body\r\n if (method !== 'GET') {\r\n requestHeaders['Content-Type'] = 'application/json;charset=UTF-8';\r\n }\r\n processedBody = JSON.stringify(body);\r\n }\r\n }\r\n \r\n Object.assign(requestHeaders, headers);\r\n \r\n const response = await this.fetch(url, {\r\n method,\r\n headers: requestHeaders,\r\n body: processedBody,\r\n ...fetchOptions,\r\n });\r\n\r\n // Handle 204 No Content\r\n if (response.status === 204) {\r\n return undefined as T;\r\n }\r\n\r\n // Try to parse JSON response\r\n let data: any;\r\n const contentType = response.headers.get('content-type');\r\n // Check for any JSON content type (including PostgREST's vnd.pgrst.object+json)\r\n if (contentType?.includes('json')) {\r\n data = await response.json();\r\n } else {\r\n // For non-JSON responses, return text\r\n data = await response.text();\r\n }\r\n\r\n // Handle errors\r\n if (!response.ok) {\r\n if (data && typeof data === 'object' && 'error' in data) {\r\n // Add the HTTP status code if not already in the data\r\n if (!data.statusCode && !data.status) {\r\n data.statusCode = response.status;\r\n }\r\n const error = InsForgeError.fromApiError(data as ApiError);\r\n // Preserve all additional fields from the error response\r\n Object.keys(data).forEach(key => {\r\n if (key !== 'error' && key !== 'message' && key !== 'statusCode') {\r\n (error as any)[key] = data[key];\r\n }\r\n });\r\n throw error;\r\n }\r\n throw new InsForgeError(\r\n `Request failed: ${response.statusText}`,\r\n response.status,\r\n 'REQUEST_FAILED'\r\n );\r\n }\r\n\r\n return data as T;\r\n }\r\n\r\n get<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('GET', path, options);\r\n }\r\n\r\n post<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('POST', path, { ...options, body });\r\n }\r\n\r\n put<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PUT', path, { ...options, body });\r\n }\r\n\r\n patch<T>(path: string, body?: any, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('PATCH', path, { ...options, body });\r\n }\r\n\r\n delete<T>(path: string, options?: RequestOptions): Promise<T> {\r\n return this.request<T>('DELETE', path, options);\r\n }\r\n\r\n setAuthToken(token: string | null) {\r\n this.userToken = token;\r\n }\r\n\r\n getHeaders(): Record<string, string> {\r\n const headers = { ...this.defaultHeaders };\r\n \r\n // Include Authorization header if token is available (same logic as request method)\r\n const authToken = this.userToken || this.anonKey;\r\n if (authToken) {\r\n headers['Authorization'] = `Bearer ${authToken}`;\r\n }\r\n \r\n return headers;\r\n }\r\n}","import { TokenStorage, AuthSession } from '../types';\r\n\r\nconst TOKEN_KEY = 'insforge-auth-token';\r\nconst USER_KEY = 'insforge-auth-user';\r\n\r\nexport class TokenManager {\r\n private storage: TokenStorage;\r\n\r\n constructor(storage?: TokenStorage) {\r\n if (storage) {\r\n // Use provided storage\r\n this.storage = storage;\r\n } else if (typeof window !== 'undefined' && window.localStorage) {\r\n // Browser: use localStorage\r\n this.storage = window.localStorage;\r\n } else {\r\n // Node.js: use in-memory storage\r\n const store = new Map<string, string>();\r\n this.storage = {\r\n getItem: (key: string) => store.get(key) || null,\r\n setItem: (key: string, value: string) => { store.set(key, value); },\r\n removeItem: (key: string) => { store.delete(key); }\r\n };\r\n }\r\n }\r\n\r\n saveSession(session: AuthSession): void {\r\n this.storage.setItem(TOKEN_KEY, session.accessToken);\r\n this.storage.setItem(USER_KEY, JSON.stringify(session.user));\r\n }\r\n\r\n getSession(): AuthSession | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n const userStr = this.storage.getItem(USER_KEY);\r\n\r\n if (!token || !userStr) {\r\n return null;\r\n }\r\n\r\n try {\r\n const user = JSON.parse(userStr as string);\r\n return { accessToken: token as string, user };\r\n } catch {\r\n this.clearSession();\r\n return null;\r\n }\r\n }\r\n\r\n getAccessToken(): string | null {\r\n const token = this.storage.getItem(TOKEN_KEY);\r\n return typeof token === 'string' ? token : null;\r\n }\r\n\r\n clearSession(): void {\r\n this.storage.removeItem(TOKEN_KEY);\r\n this.storage.removeItem(USER_KEY);\r\n }\r\n}","/**\r\n * Database module using @supabase/postgrest-js\r\n * Complete replacement for custom QueryBuilder with full PostgREST features\r\n */\r\n\r\nimport { PostgrestClient } from '@supabase/postgrest-js';\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\n\r\n\r\n/**\r\n * Custom fetch that transforms URLs and adds auth\r\n */\r\nfunction createInsForgePostgrestFetch(\r\n httpClient: HttpClient,\r\n tokenManager: TokenManager\r\n): typeof fetch {\r\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\r\n const url = typeof input === 'string' ? input : input.toString();\r\n const urlObj = new URL(url);\r\n \r\n // Extract table name from pathname\r\n // postgrest-js sends: http://dummy/tablename?params\r\n // We need: http://localhost:7130/api/database/records/tablename?params\r\n const tableName = urlObj.pathname.slice(1); // Remove leading /\r\n \r\n // Build InsForge URL\r\n const insforgeUrl = `${httpClient.baseUrl}/api/database/records/${tableName}${urlObj.search}`;\r\n \r\n // Get auth token from TokenManager or HttpClient\r\n const token = tokenManager.getAccessToken();\r\n const httpHeaders = httpClient.getHeaders();\r\n const authToken = token || httpHeaders['Authorization']?.replace('Bearer ', '');\r\n \r\n // Prepare headers\r\n const headers = new Headers(init?.headers);\r\n if (authToken && !headers.has('Authorization')) {\r\n headers.set('Authorization', `Bearer ${authToken}`);\r\n }\r\n \r\n // Make the actual request using native fetch\r\n const response = await fetch(insforgeUrl, {\r\n ...init,\r\n headers\r\n });\r\n \r\n return response;\r\n };\r\n}\r\n\r\n/**\r\n * Database client using postgrest-js\r\n * Drop-in replacement with FULL PostgREST capabilities\r\n */\r\nexport class Database {\r\n private postgrest: PostgrestClient<any, any, any>;\r\n \r\n constructor(httpClient: HttpClient, tokenManager: TokenManager) {\r\n // Create postgrest client with custom fetch\r\n this.postgrest = new PostgrestClient<any, any, any>('http://dummy', {\r\n fetch: createInsForgePostgrestFetch(httpClient, tokenManager),\r\n headers: {}\r\n });\r\n }\r\n \r\n /**\r\n * Create a query builder for a table\r\n * \r\n * @example\r\n * // Basic query\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', userId);\r\n * \r\n * // With count (Supabase style!)\r\n * const { data, error, count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact' })\r\n * .range(0, 9);\r\n * \r\n * // Just get count, no data\r\n * const { count } = await client.database\r\n * .from('posts')\r\n * .select('*', { count: 'exact', head: true });\r\n * \r\n * // Complex queries with OR\r\n * const { data } = await client.database\r\n * .from('posts')\r\n * .select('*, users!inner(*)')\r\n * .or('status.eq.active,status.eq.pending');\r\n * \r\n * // All features work:\r\n * - Nested selects\r\n * - Foreign key expansion \r\n * - OR/AND/NOT conditions\r\n * - Count with head\r\n * - Range pagination\r\n * - Upserts\r\n */\r\n from(table: string) {\r\n // Return postgrest query builder with all features\r\n return this.postgrest.from(table);\r\n }\r\n}","/**\r\n * Auth module for InsForge SDK\r\n * Uses shared schemas for type safety\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { TokenManager } from '../lib/token-manager';\r\nimport { AuthSession, InsForgeError } from '../types';\r\nimport { Database } from './database-postgrest';\r\n\r\nimport type {\r\n CreateUserRequest,\r\n CreateUserResponse,\r\n CreateSessionRequest,\r\n CreateSessionResponse,\r\n GetCurrentSessionResponse,\r\n GetOauthUrlResponse,\r\n ListPublicOAuthProvidersResponse,\r\n OAuthProvidersSchema,\r\n PublicOAuthProvider,\r\n GetPublicEmailAuthConfigResponse,\r\n UserIdSchema,\r\n EmailSchema,\r\n RoleSchema,\r\n ProfileSchema,\r\n UpdateProfileSchema,\r\n} from '@insforge/shared-schemas';\r\n\r\n/**\r\n * Convert database profile (snake_case) to ProfileSchema (camelCase)\r\n */\r\nfunction convertDbProfileToSchema(dbProfile: any): ProfileSchema {\r\n return {\r\n id: dbProfile.id,\r\n nickname: dbProfile.nickname,\r\n avatarUrl: dbProfile.avatar_url,\r\n bio: dbProfile.bio,\r\n birthday: dbProfile.birthday,\r\n createdAt: dbProfile.created_at,\r\n updatedAt: dbProfile.updated_at,\r\n };\r\n}\r\n\r\n/**\r\n * Convert ProfileSchema (camelCase) to database format (snake_case)\r\n */\r\nfunction convertSchemaToDbProfile(profile: UpdateProfileSchema): any {\r\n const dbProfile: any = {};\r\n \r\n if (profile.nickname !== undefined) dbProfile.nickname = profile.nickname;\r\n if (profile.avatarUrl !== undefined) dbProfile.avatar_url = profile.avatarUrl;\r\n if (profile.bio !== undefined) dbProfile.bio = profile.bio;\r\n if (profile.birthday !== undefined) dbProfile.birthday = profile.birthday;\r\n \r\n return dbProfile;\r\n}\r\n\r\nexport class Auth {\r\n private database: Database;\r\n \r\n constructor(\r\n private http: HttpClient,\r\n private tokenManager: TokenManager\r\n ) {\r\n this.database = new Database(http, tokenManager);\r\n \r\n // Auto-detect OAuth callback parameters in the URL\r\n this.detectOAuthCallback();\r\n }\r\n\r\n /**\r\n * Automatically detect and handle OAuth callback parameters in the URL\r\n * This runs on initialization to seamlessly complete the OAuth flow\r\n * Matches the backend's OAuth callback response (backend/src/api/routes/auth.ts:540-544)\r\n */\r\n private detectOAuthCallback(): void {\r\n // Only run in browser environment\r\n if (typeof window === 'undefined') return;\r\n \r\n try {\r\n const params = new URLSearchParams(window.location.search);\r\n \r\n // Backend returns: access_token, user_id, email, name (optional)\r\n const accessToken = params.get('access_token');\r\n const userId = params.get('user_id');\r\n const email = params.get('email');\r\n const name = params.get('name');\r\n \r\n // Check if we have OAuth callback parameters\r\n if (accessToken && userId && email) {\r\n // Create session with the data from backend\r\n const session: AuthSession = {\r\n accessToken,\r\n user: {\r\n id: userId,\r\n email: email,\r\n name: name || '',\r\n // These fields are not provided by backend OAuth callback\r\n // They'll be populated when calling getCurrentUser()\r\n emailVerified: false,\r\n createdAt: new Date().toISOString(),\r\n updatedAt: new Date().toISOString(),\r\n } as any,\r\n };\r\n \r\n // Save session and set auth token\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(accessToken);\r\n \r\n // Clean up the URL to remove sensitive parameters\r\n const url = new URL(window.location.href);\r\n url.searchParams.delete('access_token');\r\n url.searchParams.delete('user_id');\r\n url.searchParams.delete('email');\r\n url.searchParams.delete('name');\r\n \r\n // Also handle error case from backend (line 581)\r\n if (params.has('error')) {\r\n url.searchParams.delete('error');\r\n }\r\n \r\n // Replace URL without adding to browser history\r\n window.history.replaceState({}, document.title, url.toString());\r\n }\r\n } catch (error) {\r\n // Silently continue - don't break initialization\r\n console.debug('OAuth callback detection skipped:', error);\r\n }\r\n }\r\n\r\n /**\r\n * Sign up a new user\r\n */\r\n async signUp(request: CreateUserRequest): Promise<{\r\n data: CreateUserResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateUserResponse>('/api/auth/users', request);\r\n\r\n // Save session internally only if both accessToken and user exist\r\n if (response.accessToken && response.user) {\r\n const session: AuthSession = {\r\n accessToken: response.accessToken,\r\n user: response.user,\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken);\r\n }\r\n\r\n return {\r\n data: response,\r\n error: null\r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n error instanceof Error ? error.message : 'An unexpected error occurred during sign up',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with email and password\r\n */\r\n async signInWithPassword(request: CreateSessionRequest): Promise<{\r\n data: CreateSessionResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.post<CreateSessionResponse>('/api/auth/sessions', request);\r\n \r\n // Save session internally\r\n const session: AuthSession = {\r\n accessToken: response.accessToken || '',\r\n user: response.user || {\r\n id: '',\r\n email: '',\r\n name: '',\r\n emailVerified: false,\r\n createdAt: '',\r\n updatedAt: '',\r\n },\r\n };\r\n this.tokenManager.saveSession(session);\r\n this.http.setAuthToken(response.accessToken || '');\r\n\r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during sign in',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign in with OAuth provider\r\n */\r\n async signInWithOAuth(options: {\r\n provider: OAuthProvidersSchema;\r\n redirectTo?: string;\r\n skipBrowserRedirect?: boolean;\r\n }): Promise<{\r\n data: { url?: string; provider?: string };\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const { provider, redirectTo, skipBrowserRedirect } = options;\r\n \r\n const params = redirectTo \r\n ? { redirect_uri: redirectTo } \r\n : undefined;\r\n \r\n const endpoint = `/api/auth/oauth/${provider}`;\r\n const response = await this.http.get<GetOauthUrlResponse>(endpoint, { params });\r\n \r\n // Automatically redirect in browser unless told not to\r\n if (typeof window !== 'undefined' && !skipBrowserRedirect) {\r\n window.location.href = response.authUrl;\r\n return { data: {}, error: null };\r\n }\r\n\r\n return { \r\n data: { \r\n url: response.authUrl,\r\n provider \r\n }, \r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: {}, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: {}, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred during OAuth initialization',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Sign out the current user\r\n */\r\n async signOut(): Promise<{ error: InsForgeError | null }> {\r\n try {\r\n this.tokenManager.clearSession();\r\n this.http.setAuthToken(null);\r\n return { error: null };\r\n } catch (error) {\r\n return { \r\n error: new InsForgeError(\r\n 'Failed to sign out',\r\n 500,\r\n 'SIGNOUT_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get list of available OAuth providers\r\n * Returns the list of OAuth providers configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Array of configured OAuth providers with their configuration status\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getOAuthProviders();\r\n * if (data) {\r\n * // data is an array of PublicOAuthProvider: [{ provider: 'google', isConfigured: true }, ...]\r\n * data.forEach(p => console.log(`${p.provider}: ${p.isConfigured ? 'configured' : 'not configured'}`));\r\n * }\r\n * ```\r\n */\r\n async getOAuthProviders(): Promise<{\r\n data: PublicOAuthProvider[] | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<ListPublicOAuthProvidersResponse>('/api/auth/oauth/providers');\r\n \r\n return { \r\n data: response.data,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching OAuth providers',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public email authentication configuration\r\n * Returns email authentication settings configured on the backend\r\n * This is a public endpoint that doesn't require authentication\r\n * \r\n * @returns Email authentication configuration including password requirements and email verification settings\r\n * \r\n * @example\r\n * ```ts\r\n * const { data, error } = await insforge.auth.getEmailAuthConfig();\r\n * if (data) {\r\n * console.log(`Password min length: ${data.passwordMinLength}`);\r\n * console.log(`Requires email verification: ${data.requireEmailVerification}`);\r\n * console.log(`Requires uppercase: ${data.requireUppercase}`);\r\n * }\r\n * ```\r\n */\r\n async getEmailAuthConfig(): Promise<{\r\n data: GetPublicEmailAuthConfigResponse | null;\r\n error: InsForgeError | null;\r\n }> {\r\n try {\r\n const response = await this.http.get<GetPublicEmailAuthConfigResponse>('/api/auth/email/public-config');\r\n \r\n return { \r\n data: response,\r\n error: null \r\n };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching email authentication configuration',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get the current user with full profile information\r\n * Returns both auth info (id, email, role) and profile data (nickname, avatar_url, bio, etc.)\r\n */\r\n async getCurrentUser(): Promise<{\r\n data: {\r\n user: {\r\n id: UserIdSchema;\r\n email: EmailSchema;\r\n role: RoleSchema;\r\n };\r\n profile: ProfileSchema | null;\r\n } | null;\r\n error: any | null;\r\n }> {\r\n try {\r\n // Check if we have a token\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { data: null, error: null };\r\n }\r\n\r\n // Call the API for auth info\r\n this.http.setAuthToken(session.accessToken);\r\n const authResponse = await this.http.get<GetCurrentSessionResponse>('/api/auth/sessions/current');\r\n \r\n // Get the user's profile using query builder\r\n const { data: profile, error: profileError } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', authResponse.user.id)\r\n .single();\r\n \r\n // For database errors, return PostgrestError directly\r\n if (profileError && (profileError as any).code !== 'PGRST116') { // PGRST116 = not found\r\n return { data: null, error: profileError };\r\n }\r\n \r\n return {\r\n data: {\r\n user: authResponse.user,\r\n profile: profile ? convertDbProfileToSchema(profile) : null\r\n },\r\n error: null\r\n };\r\n } catch (error) {\r\n // If unauthorized, clear session\r\n if (error instanceof InsForgeError && error.statusCode === 401) {\r\n await this.signOut();\r\n return { data: null, error: null };\r\n }\r\n \r\n // Pass through all other errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: null, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while fetching user',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get any user's profile by ID\r\n * Returns profile information from the users table (nickname, avatarUrl, bio, etc.)\r\n */\r\n async getProfile(userId: string): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n const { data, error } = await this.database\r\n .from('users')\r\n .select('*')\r\n .eq('id', userId)\r\n .single();\r\n \r\n // Handle not found as null, not error\r\n if (error && (error as any).code === 'PGRST116') {\r\n return { data: null, error: null };\r\n }\r\n \r\n // Convert database format to schema format\r\n if (data) {\r\n return { data: convertDbProfileToSchema(data), error: null };\r\n }\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data: null, error };\r\n }\r\n\r\n /**\r\n * Get the current session (only session data, no API call)\r\n * Returns the stored JWT token and basic user info from local storage\r\n */\r\n getCurrentSession(): {\r\n data: { session: AuthSession | null };\r\n error: InsForgeError | null;\r\n } {\r\n try {\r\n const session = this.tokenManager.getSession();\r\n \r\n if (session?.accessToken) {\r\n this.http.setAuthToken(session.accessToken);\r\n return { data: { session }, error: null };\r\n }\r\n\r\n return { data: { session: null }, error: null };\r\n } catch (error) {\r\n // Pass through API errors unchanged\r\n if (error instanceof InsForgeError) {\r\n return { data: { session: null }, error };\r\n }\r\n \r\n // Generic fallback for unexpected errors\r\n return { \r\n data: { session: null }, \r\n error: new InsForgeError(\r\n 'An unexpected error occurred while getting session',\r\n 500,\r\n 'UNEXPECTED_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Set/Update the current user's profile\r\n * Updates profile information in the users table (nickname, avatarUrl, bio, etc.)\r\n */\r\n async setProfile(profile: UpdateProfileSchema): Promise<{\r\n data: ProfileSchema | null;\r\n error: any | null;\r\n }> {\r\n // Get current session to get user ID\r\n const session = this.tokenManager.getSession();\r\n if (!session?.accessToken) {\r\n return { \r\n data: null, \r\n error: new InsForgeError(\r\n 'No authenticated user found',\r\n 401,\r\n 'UNAUTHENTICATED'\r\n )\r\n };\r\n }\r\n \r\n // If no user ID in session (edge function scenario), fetch it\r\n if (!session.user?.id) {\r\n const { data, error } = await this.getCurrentUser();\r\n if (error) {\r\n return { data: null, error };\r\n }\r\n if (data?.user) {\r\n // Update session with minimal user info\r\n session.user = {\r\n id: data.user.id,\r\n email: data.user.email,\r\n name: data.profile?.nickname || '', // Not available from API, but required by UserSchema\r\n emailVerified: false, // Not available from API, but required by UserSchema\r\n createdAt: new Date().toISOString(), // Fallback\r\n updatedAt: new Date().toISOString(), // Fallback\r\n };\r\n this.tokenManager.saveSession(session);\r\n }\r\n }\r\n\r\n // Convert schema format to database format\r\n const dbProfile = convertSchemaToDbProfile(profile);\r\n\r\n // Update the profile using query builder\r\n const { data, error } = await this.database\r\n .from('users')\r\n .update(dbProfile)\r\n .eq('id', session.user.id)\r\n .select()\r\n .single();\r\n \r\n // Convert database format back to schema format\r\n if (data) {\r\n return { data: convertDbProfileToSchema(data), error: null };\r\n }\r\n \r\n // Return PostgrestError directly for database operations\r\n return { data: null, error };\r\n }\r\n\r\n\r\n}","/**\r\n * Storage module for InsForge SDK\r\n * Handles file uploads, downloads, and bucket management\r\n */\r\n\r\nimport { HttpClient } from '../lib/http-client';\r\nimport { InsForgeError } from '../types';\r\nimport type { \r\n StorageFileSchema,\r\n ListObjectsResponseSchema\r\n} from '@insforge/shared-schemas';\r\n\r\nexport interface StorageResponse<T> {\r\n data: T | null;\r\n error: InsForgeError | null;\r\n}\r\n\r\ninterface UploadStrategy {\r\n method: 'direct' | 'presigned';\r\n uploadUrl: string;\r\n fields?: Record<string, string>;\r\n key: string;\r\n confirmRequired: boolean;\r\n confirmUrl?: string;\r\n expiresAt?: Date;\r\n}\r\n\r\ninterface DownloadStrategy {\r\n method: 'direct' | 'presigned';\r\n url: string;\r\n expiresAt?: Date;\r\n}\r\n\r\n/**\r\n * Storage bucket operations\r\n */\r\nexport class StorageBucket {\r\n constructor(\r\n private bucketName: string,\r\n private http: HttpClient\r\n ) {}\r\n\r\n /**\r\n * Upload a file with a specific key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * @param file - File or Blob to upload\r\n */\r\n async upload(\r\n path: string,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename: path,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'PUT',\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Upload a file with auto-generated key\r\n * Uses the upload strategy from backend (direct or presigned)\r\n * @param file - File or Blob to upload\r\n */\r\n async uploadAuto(\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n const filename = file instanceof File ? file.name : 'file';\r\n \r\n // Get upload strategy from backend - this is required\r\n const strategyResponse = await this.http.post<UploadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/upload-strategy`,\r\n {\r\n filename,\r\n contentType: file.type || 'application/octet-stream',\r\n size: file.size\r\n }\r\n );\r\n\r\n // Use presigned URL if available\r\n if (strategyResponse.method === 'presigned') {\r\n return await this.uploadWithPresignedUrl(strategyResponse, file);\r\n }\r\n\r\n // Use direct upload if strategy says so\r\n if (strategyResponse.method === 'direct') {\r\n const formData = new FormData();\r\n formData.append('file', file);\r\n\r\n const response = await this.http.request<StorageFileSchema>(\r\n 'POST',\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n {\r\n body: formData as any,\r\n headers: {\r\n // Don't set Content-Type, let browser set multipart boundary\r\n }\r\n }\r\n );\r\n\r\n return { data: response, error: null };\r\n }\r\n\r\n throw new InsForgeError(\r\n `Unsupported upload method: ${strategyResponse.method}`,\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Internal method to handle presigned URL uploads\r\n */\r\n private async uploadWithPresignedUrl(\r\n strategy: UploadStrategy,\r\n file: File | Blob\r\n ): Promise<StorageResponse<StorageFileSchema>> {\r\n try {\r\n // Upload to presigned URL (e.g., S3)\r\n const formData = new FormData();\r\n \r\n // Add all fields from the presigned URL\r\n if (strategy.fields) {\r\n Object.entries(strategy.fields).forEach(([key, value]) => {\r\n formData.append(key, value);\r\n });\r\n }\r\n \r\n // File must be the last field for S3\r\n formData.append('file', file);\r\n\r\n const uploadResponse = await fetch(strategy.uploadUrl, {\r\n method: 'POST',\r\n body: formData\r\n });\r\n\r\n if (!uploadResponse.ok) {\r\n throw new InsForgeError(\r\n `Upload to storage failed: ${uploadResponse.statusText}`,\r\n uploadResponse.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n\r\n // Confirm upload with backend if required\r\n if (strategy.confirmRequired && strategy.confirmUrl) {\r\n const confirmResponse = await this.http.post<StorageFileSchema>(\r\n strategy.confirmUrl,\r\n {\r\n size: file.size,\r\n contentType: file.type || 'application/octet-stream'\r\n }\r\n );\r\n\r\n return { data: confirmResponse, error: null };\r\n }\r\n\r\n // If no confirmation required, return basic file info\r\n return {\r\n data: {\r\n key: strategy.key,\r\n bucket: this.bucketName,\r\n size: file.size,\r\n mimeType: file.type || 'application/octet-stream',\r\n uploadedAt: new Date().toISOString(),\r\n url: this.getPublicUrl(strategy.key)\r\n } as StorageFileSchema,\r\n error: null\r\n };\r\n } catch (error) {\r\n throw error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Presigned upload failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n /**\r\n * Download a file\r\n * Uses the download strategy from backend (direct or presigned)\r\n * @param path - The object key/path\r\n * Returns the file as a Blob\r\n */\r\n async download(path: string): Promise<{ data: Blob | null; error: InsForgeError | null }> {\r\n try {\r\n // Get download strategy from backend - this is required\r\n const strategyResponse = await this.http.post<DownloadStrategy>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}/download-strategy`,\r\n { expiresIn: 3600 }\r\n );\r\n\r\n // Use URL from strategy\r\n const downloadUrl = strategyResponse.url;\r\n \r\n // Download from the URL\r\n const headers: HeadersInit = {};\r\n \r\n // Only add auth header for direct downloads (not presigned URLs)\r\n if (strategyResponse.method === 'direct') {\r\n Object.assign(headers, this.http.getHeaders());\r\n }\r\n \r\n const response = await fetch(downloadUrl, {\r\n method: 'GET',\r\n headers\r\n });\r\n\r\n if (!response.ok) {\r\n try {\r\n const error = await response.json();\r\n throw InsForgeError.fromApiError(error);\r\n } catch {\r\n throw new InsForgeError(\r\n `Download failed: ${response.statusText}`,\r\n response.status,\r\n 'STORAGE_ERROR'\r\n );\r\n }\r\n }\r\n\r\n const blob = await response.blob();\r\n return { data: blob, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Download failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Get public URL for a file\r\n * @param path - The object key/path\r\n */\r\n getPublicUrl(path: string): string {\r\n return `${this.http.baseUrl}/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`;\r\n }\r\n\r\n /**\r\n * List objects in the bucket\r\n * @param prefix - Filter by key prefix\r\n * @param search - Search in file names\r\n * @param limit - Maximum number of results (default: 100, max: 1000)\r\n * @param offset - Number of results to skip\r\n */\r\n async list(options?: {\r\n prefix?: string;\r\n search?: string;\r\n limit?: number;\r\n offset?: number;\r\n }): Promise<StorageResponse<ListObjectsResponseSchema>> {\r\n try {\r\n const params: Record<string, string> = {};\r\n \r\n if (options?.prefix) params.prefix = options.prefix;\r\n if (options?.search) params.search = options.search;\r\n if (options?.limit) params.limit = options.limit.toString();\r\n if (options?.offset) params.offset = options.offset.toString();\r\n\r\n const response = await this.http.get<ListObjectsResponseSchema>(\r\n `/api/storage/buckets/${this.bucketName}/objects`,\r\n { params }\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'List failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n\r\n /**\r\n * Delete a file\r\n * @param path - The object key/path\r\n */\r\n async remove(path: string): Promise<StorageResponse<{ message: string }>> {\r\n try {\r\n const response = await this.http.delete<{ message: string }>(\r\n `/api/storage/buckets/${this.bucketName}/objects/${encodeURIComponent(path)}`\r\n );\r\n\r\n return { data: response, error: null };\r\n } catch (error) {\r\n return { \r\n data: null, \r\n error: error instanceof InsForgeError ? error : new InsForgeError(\r\n 'Delete failed',\r\n 500,\r\n 'STORAGE_ERROR'\r\n )\r\n };\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Storage module for file operations\r\n */\r\nexport class Storage {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Get a bucket instance for operations\r\n * @param bucketName - Name of the bucket\r\n */\r\n from(bucketName: string): StorageBucket {\r\n return new StorageBucket(bucketName, this.http);\r\n }\r\n}","/**\r\n * AI Module for Insforge SDK\r\n * Response format roughly matches OpenAI SDK for compatibility\r\n *\r\n * The backend handles all the complexity of different AI providers\r\n * and returns a unified format. This SDK transforms responses to match OpenAI-like format.\r\n */\r\n\r\nimport { HttpClient } from \"../lib/http-client\";\r\nimport {\r\n ChatCompletionRequest,\r\n ChatCompletionResponse,\r\n ImageGenerationRequest,\r\n ImageGenerationResponse,\r\n} from \"@insforge/shared-schemas\";\r\n\r\nexport class AI {\r\n public readonly chat: Chat;\r\n public readonly images: Images;\r\n\r\n constructor(private http: HttpClient) {\r\n this.chat = new Chat(http);\r\n this.images = new Images(http);\r\n }\r\n}\r\n\r\nclass Chat {\r\n public readonly completions: ChatCompletions;\r\n\r\n constructor(http: HttpClient) {\r\n this.completions = new ChatCompletions(http);\r\n }\r\n}\r\n\r\nclass ChatCompletions {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Create a chat completion - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Non-streaming\r\n * const completion = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Hello!' }]\r\n * });\r\n * console.log(completion.choices[0].message.content);\r\n *\r\n * // With images\r\n * const response = await client.ai.chat.completions.create({\r\n * model: 'gpt-4-vision',\r\n * messages: [{\r\n * role: 'user',\r\n * content: 'What is in this image?',\r\n * images: [{ url: 'https://example.com/image.jpg' }]\r\n * }]\r\n * });\r\n *\r\n * // Streaming - returns async iterable\r\n * const stream = await client.ai.chat.completions.create({\r\n * model: 'gpt-4',\r\n * messages: [{ role: 'user', content: 'Tell me a story' }],\r\n * stream: true\r\n * });\r\n *\r\n * for await (const chunk of stream) {\r\n * if (chunk.choices[0]?.delta?.content) {\r\n * process.stdout.write(chunk.choices[0].delta.content);\r\n * }\r\n * }\r\n * ```\r\n */\r\n async create(params: ChatCompletionRequest): Promise<any> {\r\n // Backend already expects camelCase, no transformation needed\r\n const backendParams = {\r\n model: params.model,\r\n messages: params.messages,\r\n temperature: params.temperature,\r\n maxTokens: params.maxTokens,\r\n topP: params.topP,\r\n stream: params.stream,\r\n };\r\n\r\n // For streaming, return an async iterable that yields OpenAI-like chunks\r\n if (params.stream) {\r\n const headers = this.http.getHeaders();\r\n headers[\"Content-Type\"] = \"application/json\";\r\n\r\n const response = await this.http.fetch(\r\n `${this.http.baseUrl}/api/ai/chat/completion`,\r\n {\r\n method: \"POST\",\r\n headers,\r\n body: JSON.stringify(backendParams),\r\n }\r\n );\r\n\r\n if (!response.ok) {\r\n const error = await response.json();\r\n throw new Error(error.error || \"Stream request failed\");\r\n }\r\n\r\n // Return async iterable that parses SSE and transforms to OpenAI-like format\r\n return this.parseSSEStream(response, params.model);\r\n }\r\n\r\n // Non-streaming: transform response to OpenAI-like format\r\n const response: ChatCompletionResponse = await this.http.post(\r\n \"/api/ai/chat/completion\",\r\n backendParams\r\n );\r\n\r\n // Transform to OpenAI-like format\r\n const content = response.text || \"\";\r\n\r\n return {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion\",\r\n created: Math.floor(Date.now() / 1000),\r\n model: response.metadata?.model,\r\n choices: [\r\n {\r\n index: 0,\r\n message: {\r\n role: \"assistant\",\r\n content,\r\n },\r\n finish_reason: \"stop\",\r\n },\r\n ],\r\n usage: response.metadata?.usage || {\r\n prompt_tokens: 0,\r\n completion_tokens: 0,\r\n total_tokens: 0,\r\n },\r\n };\r\n }\r\n\r\n /**\r\n * Parse SSE stream into async iterable of OpenAI-like chunks\r\n */\r\n private async *parseSSEStream(\r\n response: Response,\r\n model: string\r\n ): AsyncIterableIterator<any> {\r\n const reader = response.body!.getReader();\r\n const decoder = new TextDecoder();\r\n let buffer = \"\";\r\n\r\n try {\r\n while (true) {\r\n const { done, value } = await reader.read();\r\n if (done) break;\r\n\r\n buffer += decoder.decode(value, { stream: true });\r\n const lines = buffer.split(\"\\n\");\r\n buffer = lines.pop() || \"\";\r\n\r\n for (const line of lines) {\r\n if (line.startsWith(\"data: \")) {\r\n const dataStr = line.slice(6).trim();\r\n if (dataStr) {\r\n try {\r\n const data = JSON.parse(dataStr);\r\n\r\n // Transform to OpenAI-like streaming format\r\n if (data.chunk || data.content) {\r\n yield {\r\n id: `chatcmpl-${Date.now()}`,\r\n object: \"chat.completion.chunk\",\r\n created: Math.floor(Date.now() / 1000),\r\n model,\r\n choices: [\r\n {\r\n index: 0,\r\n delta: {\r\n content: data.chunk || data.content,\r\n },\r\n finish_reason: data.done ? \"stop\" : null,\r\n },\r\n ],\r\n };\r\n }\r\n\r\n // If we received the done signal, we can stop\r\n if (data.done) {\r\n reader.releaseLock();\r\n return;\r\n }\r\n } catch (e) {\r\n // Skip invalid JSON\r\n console.warn(\"Failed to parse SSE data:\", dataStr);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n } finally {\r\n reader.releaseLock();\r\n }\r\n }\r\n}\r\n\r\nclass Images {\r\n constructor(private http: HttpClient) {}\r\n\r\n /**\r\n * Generate images - OpenAI-like response format\r\n *\r\n * @example\r\n * ```typescript\r\n * // Text-to-image\r\n * const response = await client.ai.images.generate({\r\n * model: 'dall-e-3',\r\n * prompt: 'A sunset over mountains',\r\n * });\r\n * console.log(response.images[0].url);\r\n *\r\n * // Image-to-image (with input images)\r\n * const response = await client.ai.images.generate({\r\n * model: 'stable-diffusion-xl',\r\n * prompt: 'Transform this into a watercolor painting',\r\n * images: [\r\n * { url: 'https://example.com/input.jpg' },\r\n * // or base64-encoded Data URI:\r\n * { url: 'data:image/jpeg;base64,/9j/4AAQ...' }\r\n * ]\r\n * });\r\n * ```\r\n */\r\n async generate(params: ImageGenerationRequest): Promise<any> {\r\n const response: ImageGenerationResponse = await this.http.post(\r\n \"/api/ai/image/generation\",\r\n params\r\n );\r\n \r\n // Build data array based on response content\r\n let data: Array<{ b64_json?: string; content?: string }> = [];\r\n \r\n if (response.images && response.images.length > 0) {\r\n // Has images - extract base64 and include text\r\n data = response.images.map(img => ({\r\n b64_json: img.imageUrl.replace(/^data:image\\/\\w+;base64,/, ''),\r\n content: response.text\r\n }));\r\n } else if (response.text) {\r\n // Text-only response\r\n data = [{ content: response.text }];\r\n }\r\n \r\n // Return OpenAI-compatible format\r\n return {\r\n created: Math.floor(Date.now() / 1000),\r\n data,\r\n ...(response.metadata?.usage && {\r\n usage: {\r\n total_tokens: response.metadata.usage.totalTokens || 0,\r\n input_tokens: response.metadata.usage.promptTokens || 0,\r\n output_tokens: response.metadata.usage.completionTokens || 0,\r\n }\r\n })\r\n };\r\n }\r\n}\r\n","import { HttpClient } from '../lib/http-client';\r\n\r\nexport interface FunctionInvokeOptions {\r\n /**\r\n * The body of the request\r\n */\r\n body?: any;\r\n \r\n /**\r\n * Custom headers to send with the request\r\n */\r\n headers?: Record<string, string>;\r\n \r\n /**\r\n * HTTP method (default: POST)\r\n */\r\n method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\r\n}\r\n\r\n/**\r\n * Edge Functions client for invoking serverless functions\r\n * \r\n * @example\r\n * ```typescript\r\n * // Invoke a function with JSON body\r\n * const { data, error } = await client.functions.invoke('hello-world', {\r\n * body: { name: 'World' }\r\n * });\r\n * \r\n * // GET request\r\n * const { data, error } = await client.functions.invoke('get-data', {\r\n * method: 'GET'\r\n * });\r\n * ```\r\n */\r\nexport class Functions {\r\n private http: HttpClient;\r\n\r\n constructor(http: HttpClient) {\r\n this.http = http;\r\n }\r\n\r\n /**\r\n * Invokes an Edge Function\r\n * @param slug The function slug to invoke\r\n * @param options Request options\r\n */\r\n async invoke<T = any>(\r\n slug: string,\r\n options: FunctionInvokeOptions = {}\r\n ): Promise<{ data: T | null; error: Error | null }> {\r\n try {\r\n const { method = 'POST', body, headers = {} } = options;\r\n \r\n // Simple path: /functions/{slug}\r\n const path = `/functions/${slug}`;\r\n \r\n // Use the HTTP client's request method\r\n const data = await this.http.request<T>(\r\n method,\r\n path,\r\n { body, headers }\r\n );\r\n \r\n return { data, error: null };\r\n } catch (error: any) {\r\n // The HTTP client throws InsForgeError with all properties from the response\r\n // including error, message, details, statusCode, etc.\r\n // We need to preserve all of that information\r\n return { \r\n data: null, \r\n error: error // Pass through the full error object with all properties\r\n };\r\n }\r\n }\r\n}","import { InsForgeConfig } from './types';\r\nimport { HttpClient } from './lib/http-client';\r\nimport { TokenManager } from './lib/token-manager';\r\nimport { Auth } from './modules/auth';\r\nimport { Database } from './modules/database-postgrest';\r\nimport { Storage } from './modules/storage';\r\nimport { AI } from './modules/ai';\r\nimport { Functions } from './modules/functions';\r\n\r\n/**\r\n * Main InsForge SDK Client\r\n * \r\n * @example\r\n * ```typescript\r\n * import { InsForgeClient } from '@insforge/sdk';\r\n * \r\n * const client = new InsForgeClient({\r\n * baseUrl: 'http://localhost:7130'\r\n * });\r\n * \r\n * // Authentication\r\n * const session = await client.auth.register({\r\n * email: 'user@example.com',\r\n * password: 'password123',\r\n * name: 'John Doe'\r\n * });\r\n * \r\n * // Database operations\r\n * const { data, error } = await client.database\r\n * .from('posts')\r\n * .select('*')\r\n * .eq('user_id', session.user.id)\r\n * .order('created_at', { ascending: false })\r\n * .limit(10);\r\n * \r\n * // Insert data\r\n * const { data: newPost } = await client.database\r\n * .from('posts')\r\n * .insert({ title: 'Hello', content: 'World' })\r\n * .single();\r\n * \r\n * // Invoke edge functions\r\n * const { data, error } = await client.functions.invoke('my-function', {\r\n * body: { message: 'Hello from SDK' }\r\n * });\r\n * ```\r\n */\r\nexport class InsForgeClient {\r\n private http: HttpClient;\r\n private tokenManager: TokenManager;\r\n \r\n public readonly auth: Auth;\r\n public readonly database: Database;\r\n public readonly storage: Storage;\r\n public readonly ai: AI;\r\n public readonly functions: Functions;\r\n\r\n constructor(config: InsForgeConfig = {}) {\r\n this.http = new HttpClient(config);\r\n this.tokenManager = new TokenManager(config.storage);\r\n \r\n // Check for edge function token\r\n if (config.edgeFunctionToken) {\r\n this.http.setAuthToken(config.edgeFunctionToken);\r\n // Save to token manager so getCurrentUser() works\r\n this.tokenManager.saveSession({\r\n accessToken: config.edgeFunctionToken,\r\n user: {} as any // Will be populated by getCurrentUser()\r\n });\r\n }\r\n \r\n // Check for existing session in storage\r\n const existingSession = this.tokenManager.getSession();\r\n if (existingSession?.accessToken) {\r\n this.http.setAuthToken(existingSession.accessToken);\r\n }\r\n \r\n this.auth = new Auth(\r\n this.http,\r\n this.tokenManager\r\n );\r\n \r\n this.database = new Database(this.http, this.tokenManager);\r\n this.storage = new Storage(this.http);\r\n this.ai = new AI(this.http);\r\n this.functions = new Functions(this.http);\r\n }\r\n\r\n /**\r\n * Get the underlying HTTP client for custom requests\r\n * \r\n * @example\r\n * ```typescript\r\n * const httpClient = client.getHttpClient();\r\n * const customData = await httpClient.get('/api/custom-endpoint');\r\n * ```\r\n */\r\n getHttpClient(): HttpClient {\r\n return this.http;\r\n }\r\n\r\n /**\r\n * Future modules will be added here:\r\n * - database: Database operations\r\n * - storage: File storage operations\r\n * - functions: Serverless functions\r\n * - tables: Table management\r\n * - metadata: Backend metadata\r\n */\r\n}","/**\r\n * @insforge/sdk - TypeScript SDK for InsForge Backend-as-a-Service\r\n * \r\n * @packageDocumentation\r\n */\r\n\r\n// Main client\r\nexport { InsForgeClient } from './client';\r\n\r\n// Types\r\nexport type {\r\n InsForgeConfig,\r\n InsForgeConfig as ClientOptions, // Alias for compatibility\r\n TokenStorage,\r\n AuthSession,\r\n ApiError,\r\n} from './types';\r\n\r\nexport { InsForgeError } from './types';\r\n\r\n// Re-export shared schemas that SDK users will need\r\nexport type {\r\n UserSchema,\r\n CreateUserRequest,\r\n CreateSessionRequest,\r\n AuthErrorResponse,\r\n} from '@insforge/shared-schemas';\r\n\r\n// Re-export auth module for advanced usage\r\nexport { Auth } from './modules/auth';\r\n\r\n// Re-export database module (using postgrest-js)\r\nexport { Database } from './modules/database-postgrest';\r\n// Note: QueryBuilder is no longer exported as we use postgrest-js QueryBuilder internally\r\n\r\n// Re-export storage module and types\r\nexport { Storage, StorageBucket } from './modules/storage';\r\nexport type { StorageResponse } from './modules/storage';\r\n\r\n// Re-export AI module\r\nexport { AI } from './modules/ai';\r\n\r\n// Re-export Functions module\r\nexport { Functions } from './modules/functions';\r\nexport type { FunctionInvokeOptions } from './modules/functions';\r\n\r\n// Re-export utilities for advanced usage\r\nexport { HttpClient } from './lib/http-client';\r\nexport { TokenManager } from './lib/token-manager';\r\n\r\n// Factory function for creating clients (Supabase-style)\r\nimport { InsForgeClient } from './client';\r\nimport { InsForgeConfig } from './types';\r\n\r\nexport function createClient(config: InsForgeConfig): InsForgeClient {\r\n return new InsForgeClient(config);\r\n}\r\n\r\n// Default export for convenience\r\nexport default InsForgeClient;"],"mappings":";AA0EO,IAAM,gBAAN,MAAM,uBAAsB,MAAM;AAAA,EAKvC,YAAY,SAAiB,YAAoB,OAAe,aAAsB;AACpF,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,QAAQ;AACb,SAAK,cAAc;AAAA,EACrB;AAAA,EAEA,OAAO,aAAa,UAAmC;AACrD,WAAO,IAAI;AAAA,MACT,SAAS;AAAA,MACT,SAAS;A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IAAI,WAAW,MAAM;AACjC,SAAK,eAAe,IAAI,aAAa,OAAO,OAAO;AAGnD,QAAI,OAAO,mBAAmB;AAC5B,WAAK,KAAK,aAAa,OAAO,iBAAiB;AAE/C,WAAK,aAAa,YAAY;AAAA,QAC5B,aAAa,OAAO;AAAA,QACpB,MAAM,CAAC;AAAA;AAAA,MACT,CAAC;AAAA,IACH;AAGA,UAAM,kBAAkB,KAAK,aAAa,WAAW;AACrD,QAAI,iBAAiB,aAAa;AAChC,WAAK,KAAK,aAAa,gBAAgB,WAAW;AAAA,IACpD;AAEA,SAAK,OAAO,IAAI;AAAA,MACd,KAAK;AAAA,MACL,KAAK;AAAA,IACP;AAEA,SAAK,WAAW,IAAI,SAAS,KAAK,MAAM,KAAK,YAAY;AACzD,SAAK,UAAU,IAAI,QAAQ,KAAK,IAAI;AACpC,SAAK,KAAK,IAAI,GAAG,KAAK,IAAI;AAC1B,SAAK,YAAY,IAAI,UAAU,KAAK,IAAI;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,gBAA4B;AAC1B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAUF;;;ACvDO,SAAS,aAAa,QAAwC;AACnE,SAAO,IAAI,eAAe,MAAM;AAClC;AAGA,IAAO,gBAAQ;","names":["data","error","response"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@insforge/sdk",
3
- "version": "0.0.58-dev.3",
3
+ "version": "0.0.58-dev.4",
4
4
  "description": "Official JavaScript/TypeScript client for InsForge Backend-as-a-Service platform",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",