UNPKG

aiwrapper

Version:

A Universal AI Wrapper for JavaScript & TypeScript

64 lines (63 loc) 1.94 kB
import processLinesFromStream from "./lang/process-lines-from-stream.js"; let _processServerEvents = (response, onData, signal) => { if (response.ok === false) { throw new Error( `Response from server was not ok. Status code: ${response.status}.` ); } const reader = response.body.getReader(); let decoder = new TextDecoder("utf-8"); let rawData = ""; let aborted = false; let abortError = null; let abortHandler; if (signal) { abortHandler = () => { aborted = true; abortError = new Error("The operation was aborted"); abortError.name = "AbortError"; reader.cancel().catch(() => { }); }; if (signal.aborted) { abortHandler(); } else { signal.addEventListener("abort", abortHandler, { once: true }); } } return reader.read().then(function processStream(result) { if (aborted) { return Promise.reject(abortError != null ? abortError : new Error("AbortError")); } if (result.done || result.value === void 0) { if (aborted) { return Promise.reject(abortError != null ? abortError : new Error("AbortError")); } return Promise.resolve(); } rawData += decoder.decode(result.value, { stream: true }); let lastIndex = rawData.lastIndexOf("\n"); if (lastIndex > -1) { processLinesFromStream(rawData.slice(0, lastIndex), onData); rawData = rawData.slice(lastIndex + 1); } return reader.read().then(processStream); }).finally(() => { if (signal && abortHandler) { signal.removeEventListener("abort", abortHandler); } }); }; const setProcessServerEventsImpl = (impl) => { _processServerEvents = impl; }; const processServerEvents = (response, onProgress, signal) => { return _processServerEvents(response, onProgress, signal); }; export { processServerEvents, setProcessServerEventsImpl }; //# sourceMappingURL=process-server-events.js.map