/** A service result. */ export interface IServiceResultBase { /** The error. */ error?: IServiceError; } /** A service result. */ export interface IServiceResult extends IServiceResultBase { /** The value. */ value?: T; } /** An error. */ export interface IServiceError { /** The error code. */ code?: string; /** The error message. (For developers, not end users.) */ message?: string; /** Advanced error details. */ details?: Record; /** The inner error. */ innerError?: IServiceError; } /** Options for an HTTP client. */ export interface IHttpClientOptions { /** The fetch object. */ fetch: HttpClientUtility.IFetch; /** The base URI of the service. */ baseUri?: string; } /** Helpers for HTTP clients. */ // eslint-disable-next-line @typescript-eslint/no-namespace export namespace HttpClientUtility { /** The fetch function. */ export interface IFetch { (uri: string, request: IFetchRequest, context?: unknown): Promise; } /** The minimal fetch request. */ export interface IFetchRequest { method?: string; headers?: Record; body?: string; } /** The minimal fetch response. */ export interface IFetchResponse { status: number; ok?: boolean; headers: { get(name: string): string | null; }; body?: IWebReadableStream | INodeReadableStream | null; json(): Promise; } /** A fetch response with any fetched content. */ export interface IFetchedResponseWithContent { /** The fetch response. */ response: IFetchResponse; /** The fetched JSON, if any. */ json?: unknown; } /** Web Streams API ReadableStream (browser). */ export interface IWebReadableStream { getReader(): { read(): Promise<{ done: boolean; value?: Uint8Array }>; cancel(): Promise; }; } /** Node.js ReadableStream. */ export interface INodeReadableStream { on(event: 'data', listener: (chunk: Uint8Array | ArrayBuffer) => void): void; on(event: 'end', listener: () => void): void; on(event: 'error', listener: (err: Error) => void): void; off?(event: string, listener: (...args: unknown[]) => void): void; removeAllListeners?(): void; } const standardErrorCodes: { [index: number]: string } = { '304': 'NotModified', '400': 'InvalidRequest', '401': 'NotAuthenticated', '403': 'NotAuthorized', '404': 'NotFound', '409': 'Conflict', '413': 'RequestTooLarge', '429': 'TooManyRequests', '500': 'InternalError', '503': 'ServiceUnavailable', }; const jsonContentType = 'application/json'; const createInvalidContentError = (error: unknown) => { const message = error instanceof Error ? error.message : typeof error === 'string' ? error : ''; return { code: 'InvalidResponse', message: message ? `HTTP content is invalid: ${message}` : 'HTTP content is invalid', }; }; /** Fetch JSON using the specified fetch, URI, and request. */ export function fetchResponse( fetch: IFetch, uri: string, request: IFetchRequest, context?: unknown ): Promise { return fetch(uri, request, context).then((response) => { if (!response.headers || !response.status || typeof response.json !== 'function') { throw new TypeError('fetch must resolve Promise with { status, headers, json() }.'); } const contentType = response.headers.get('content-type'); if (!contentType) { return Promise.resolve({ response: response, json: {} }); } if (contentType.toLowerCase().substr(0, jsonContentType.length) === jsonContentType) { const jsonPromise = response.json(); if (!jsonPromise || typeof jsonPromise.then !== 'function') { throw new TypeError('json() of fetch response must return a Promise.'); } return jsonPromise .then((json) => ({ response: response, json: json, })) .catch((error) => response.status >= 400 && response.status <= 599 ? { response: response } : { response: response, json: createInvalidContentError(error) } ); } return Promise.resolve({ response: response }); }); } /** Creates an error result for the specified response. */ export function createResponseError(status: number, json?: unknown): IServiceResultBase { if (isServiceError(json)) { return { error: json }; } const isClientError = status >= 400 && status <= 499; const isServerError = status >= 500 && status <= 599; const errorCode = standardErrorCodes[status] || (isClientError ? 'InvalidRequest' : 'InvalidResponse'); const message = isServerError ? 'HTTP server error' : isClientError ? 'HTTP client error' : 'Unexpected HTTP status code'; return { error: { code: errorCode, message: `${message}: ${status}` } }; } /** Creates an error result for a required request field. */ export function createRequiredRequestFieldError(name: string): IServiceResultBase { return { error: { code: 'InvalidRequest', message: `'${name}' is required.`, }, }; } /** Creates an async iterable stream from a fetch SSE response. */ export function createFetchEventStream( fetchFunc: IFetch, url: string, fetchRequest: IFetchRequest, context?: unknown ): Promise>>> { return new Promise((outerResolve, outerReject) => { fetchFunc(url, fetchRequest, context) .then((response) => { if (!response.ok) { outerReject(new Error(`HTTP error! status: ${response.status}`)); return; } if (!response.body) { outerReject(new Error('Response body is null')); return; } const body = response.body; if (!isWebReadableStream(body) && !isNodeReadableStream(body)) { outerReject(new Error('Response body is not a readable stream')); return; } const asyncIterable: AsyncIterable> = { [Symbol.asyncIterator]() { const queue: Array> = []; let resolveNext: ((value: IteratorResult>) => void) | null = null; let isDone = false; let buffer = ''; const decoder = new TextDecoder(); const processLine = (line: string) => { if (line.startsWith('data: ')) { const data = line.slice(6); try { const parsed = JSON.parse(data) as T; const result: IServiceResult = { value: parsed }; if (resolveNext) { resolveNext({ value: result, done: false }); resolveNext = null; } else { queue.push(result); } } catch (parseError) { const errorResult: IServiceResult = { error: { code: 'InvalidResponse', message: 'Failed to parse SSE data' }, }; if (resolveNext) { resolveNext({ value: errorResult, done: false }); resolveNext = null; } else { queue.push(errorResult); } } } }; const processChunk = (chunk: Uint8Array) => { buffer += decoder.decode(chunk, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop() || ''; for (const line of lines) { processLine(line); } }; const handleError = () => { isDone = true; if (resolveNext) { resolveNext({ value: { error: { code: 'InternalError', message: 'Stream read error' }, }, done: false, }); } }; const handleEnd = () => { isDone = true; if (resolveNext) { resolveNext({ value: undefined, done: true }); } }; if (isWebReadableStream(body)) { // Handle Web Streams (browser) const reader = body.getReader(); const readStream = (): void => { reader .read() .then(({ done, value }) => { if (done) { handleEnd(); return; } if (value) processChunk(value); readStream(); }) .catch(handleError); }; readStream(); } else if (isNodeReadableStream(body)) { // Handle Node.js Streams body.on('data', (chunk) => { const uint8Array = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk); processChunk(uint8Array); }); body.on('end', handleEnd); body.on('error', handleError); } return { async next() { if (queue.length > 0) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return { value: queue.shift()!, done: false }; } if (isDone) { return { value: undefined, done: true }; } return new Promise((res) => { resolveNext = res; }); }, async return() { isDone = true; if (isWebReadableStream(body)) { const reader = body.getReader(); reader.cancel(); } else if (isNodeReadableStream(body)) { if (body.removeAllListeners) { body.removeAllListeners(); } } return { value: undefined, done: true }; }, }; }, }; outerResolve({ value: asyncIterable }); }) .catch((err) => { outerReject(err); }); }); } } /** Type guard to check if a stream is a Web ReadableStream. */ function isWebReadableStream(stream: unknown): stream is HttpClientUtility.IWebReadableStream { return typeof (stream as HttpClientUtility.IWebReadableStream).getReader === 'function'; } /** Type guard to check if a stream is a Node.js ReadableStream. */ function isNodeReadableStream(stream: unknown): stream is HttpClientUtility.INodeReadableStream { return typeof (stream as HttpClientUtility.INodeReadableStream).on === 'function'; } function isServiceError(json: unknown): json is IServiceError { return typeof json === 'object' && json != null && typeof (json as Record).code === 'string'; }