UNPKG

@yoyo-org/progressive-json

Version:

Stream and render JSON data as it arrives - perfect for AI responses, large datasets, and real-time updates

56 lines (55 loc) 1.9 kB
/** * Default HTTP adapter using the built-in fetch API */ export class FetchAdapter { async stream(url, options = {}) { const response = await this.request(url, options); return response.stream; } async request(url, options = {}) { const fetchOptions = { method: options.method || 'GET', headers: options.headers, body: options.body, signal: options.signal, }; // Handle timeout if specified if (options.timeout) { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), options.timeout); // Combine timeout signal with existing signal if (options.signal) { if (options.signal.aborted) { clearTimeout(timeoutId); throw new Error('Request was aborted'); } options.signal.addEventListener('abort', () => { clearTimeout(timeoutId); controller.abort(); }); } fetchOptions.signal = controller.signal; } const response = await fetch(url, fetchOptions); if (!response.ok) { throw new Error(`HTTP Error: ${response.status} ${response.statusText}`); } if (!response.body) { throw new Error('No response body received'); } // Convert Headers to plain object const headers = {}; response.headers.forEach((value, key) => { headers[key] = value; }); return { stream: response.body, status: response.status, statusText: response.statusText, headers, ok: response.ok, }; } } // Export a default instance export const fetchAdapter = new FetchAdapter();