import { ClientConfig, B44Client } from "../types"; import { createHttpClient } from "./http"; import { createEntitiesModule } from "../modules/entities"; import { createAuthModule } from "../modules/auth"; import { getAccessToken } from "../utils/auth-utils"; /** * Create a B44 client instance * @param config Client configuration * @returns B44 client */ export function createClient(config: ClientConfig): B44Client { // Validate required configuration if (!config || !config.appId) { throw new Error("appId is required"); } // Extract configuration with defaults const { serverUrl = "http://localhost:3000", appId, env = "prod", token, apiKey, requiresAuth = false, } = config; // Create HTTP client const httpClient = createHttpClient({ baseURL: `${serverUrl}/api`, headers: { api_key: apiKey ?? "", "X-App-Id": String(appId), "X-Environment": env, }, token, requiresAuth, appId, serverUrl, }); // Create entities module const entities = createEntitiesModule(httpClient, appId); // Create auth module const auth = createAuthModule(httpClient, appId, serverUrl); // Initialize token from storage or URL if in browser environment if (typeof window !== "undefined") { const storedToken = token || getAccessToken(); if (storedToken) { auth.setToken(storedToken); } } // Auto-check authentication if required if (requiresAuth && typeof window !== "undefined") { setTimeout(async () => { try { const isAuthenticated = await auth.isAuthenticated(); if (!isAuthenticated) { auth.login(window.location.href); } } catch (error) { console.error("Authentication check failed:", error); auth.login(window.location.href); } }, 0); } // Create and return the client instance return { entities, auth, setToken(token: string) { auth.setToken(token); }, getConfig() { return { serverUrl, appId, env, requiresAuth, }; }, integrations: { Core: {}, InvokeLLM: {}, SendEmail: {}, SendSMS: {}, UploadFile: {}, GenerateImage: {}, ExtractDataFromUploadedFile: {}, }, }; }