import { GHLError } from './errors'; export interface GHLClientConfig { accessToken: string; locationId: string; version?: string; } export class GHLClient { // v2 API endpoint for OAuth/Private Integration tokens private baseUrl = 'https://services.leadconnectorhq.com'; private accessToken: string; private locationId: string; private version: string; constructor(config: GHLClientConfig) { this.accessToken = config.accessToken; this.locationId = config.locationId; // v2 API version - use latest stable version this.version = config.version || '2021-07-28'; } get locationID() { return this.locationId; } async request( endpoint: string, options: RequestInit = {} ): Promise { const url = `${this.baseUrl}${endpoint}`; const response = await fetch(url, { ...options, headers: { 'Authorization': `Bearer ${this.accessToken}`, 'Version': this.version, 'Content-Type': 'application/json', 'Accept': 'application/json', ...options.headers, }, }); if (!response.ok) { const errorBody = await response.text(); throw new GHLError( response.status, `GHL API Error: ${response.statusText}`, errorBody ); } // Handle empty responses const text = await response.text(); if (!text) return {} as T; return JSON.parse(text) as T; } async get(endpoint: string, params?: Record): Promise { const searchParams = new URLSearchParams(params); const url = params ? `${endpoint}?${searchParams}` : endpoint; return this.request(url, { method: 'GET' }); } async post(endpoint: string, body?: unknown): Promise { return this.request(endpoint, { method: 'POST', body: body ? JSON.stringify(body) : undefined, }); } async put(endpoint: string, body?: unknown): Promise { return this.request(endpoint, { method: 'PUT', body: body ? JSON.stringify(body) : undefined, }); } async delete(endpoint: string): Promise { return this.request(endpoint, { method: 'DELETE' }); } }