import { Client } from './client'; const APPCONDA_DEFAULT_PATH = '/api/appconda/v1'; const APPCONDA_NODE_DEFAULT_ENDPOINT = 'http://localhost:3000/api/appconda/v1'; export type AppcondaClientOptions = { endpoint?: string; project?: string; mode?: string; key?: string; jwt?: string; session?: string; locale?: string; forwardedUserAgent?: string; headers?: Record; } function normalizeEndpoint(endpoint: string): string { return endpoint.replace(/\/+$/, ''); } function resolveEndpoint(overrideEndpoint?: string): string { if (overrideEndpoint) { return normalizeEndpoint(overrideEndpoint); } const envEndpoint = (typeof process !== 'undefined' && process?.env?.APPCONDA_ENDPOINT) || (typeof process !== 'undefined' && process?.env?.NEXT_PUBLIC_APPCONDA_ENDPOINT) || ''; if (envEndpoint) { return normalizeEndpoint(envEndpoint); } if (typeof window !== 'undefined' && window?.location?.origin) { return normalizeEndpoint(new URL(APPCONDA_DEFAULT_PATH, window.location.origin).toString()); } return APPCONDA_NODE_DEFAULT_ENDPOINT; } function applyClientOptions(client: Client, options: AppcondaClientOptions): Client { if (options.project) { client.setProject(options.project); } if (options.mode) { client.setMode(options.mode); } if (options.key) { client.setKey(options.key); } if (options.jwt) { client.setJWT(options.jwt); } if (options.session) { client.setSession(options.session); } if (options.locale) { client.setLocale(options.locale); } if (options.forwardedUserAgent) { client.setForwardedUserAgent(options.forwardedUserAgent); } if (options.headers) { for (const [headerName, headerValue] of Object.entries(options.headers)) { client.addHeader(headerName, headerValue); } } return client; } export function getAppcondaClient(options: AppcondaClientOptions = {}): Client { const client = new Client() .setEndpoint(resolveEndpoint(options.endpoint)) .setProject(options.project ?? 'console'); return applyClientOptions(client, options); } export function getAppcondaClientSync(options: AppcondaClientOptions = {}): Client { return getAppcondaClient(options); }