UNPKG

@anthropic-ai/sdk

Version:
284 lines • 11.6 kB
"use strict"; var _Stream_client; Object.defineProperty(exports, "__esModule", { value: true }); exports.Stream = void 0; exports._iterSSEMessages = _iterSSEMessages; const tslib_1 = require("../internal/tslib.js"); const error_1 = require("./error.js"); const shims_1 = require("../internal/shims.js"); const line_1 = require("../internal/decoders/line.js"); const shims_2 = require("../internal/shims.js"); const errors_1 = require("../internal/errors.js"); const values_1 = require("../internal/utils/values.js"); const bytes_1 = require("../internal/utils/bytes.js"); const log_1 = require("../internal/utils/log.js"); const error_2 = require("./error.js"); const request_signal_1 = require("../internal/request-signal.js"); var Stream = /* @__PURE__ */ (() => { class Stream { constructor(iterator, controller, client) { this.iterator = iterator; _Stream_client.set(this, void 0); this.controller = controller; tslib_1.__classPrivateFieldSet(this, _Stream_client, client, "f"); } /** * Iterate the raw Server-Sent Events from `response` — `{event, data, raw}` * objects, before any JSON parsing or event-name filtering. * * This reads `response.body` directly (not a clone), so the response is * consumed. Use this in middleware that fully replaces the stream body; for * read-only observation of parsed events, use `ctx.parse()` instead. */ static rawEvents(response, controller = new AbortController()) { return _iterSSEMessages(response, controller); } static fromSSEResponse(response, controller, client) { let consumed = false; const logger = client ? (0, log_1.loggerFor)(client) : console; async function* iterator() { if (consumed) { throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); } consumed = true; let done = false; try { for await (const sse of _iterSSEMessages(response, controller)) { if (sse.event === 'ping') { continue; } if (sse.event === null) { continue; } if (sse.event === 'error') { const body = (0, values_1.safeJSON)(sse.data) ?? sse.data; const type = body?.error?.type; throw new error_2.APIError(undefined, body, undefined, response.headers, type); } else { if (!sse.data) continue; try { yield JSON.parse(sse.data); } catch (e) { logger.error(`Could not parse message into JSON:`, sse.data); logger.error(`From chunk:`, sse.raw); throw e; } } } done = true; } catch (e) { // If the user calls `stream.controller.abort()`, we should exit without throwing. if ((0, errors_1.isAbortError)(e)) return; throw e; } finally { // If the user `break`s, abort the ongoing request. if (!done) controller.abort(); (0, request_signal_1.releaseRequestSignal)(controller); } } return new Stream(iterator, controller, client); } /** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */ static fromReadableStream(readableStream, controller, client) { let consumed = false; async function* iterLines() { const lineDecoder = new line_1.LineDecoder(); const iter = (0, shims_2.ReadableStreamToAsyncIterable)(readableStream); for await (const chunk of iter) { for (const line of lineDecoder.decode(chunk)) { yield line; } } for (const line of lineDecoder.flush()) { yield line; } } async function* iterator() { if (consumed) { throw new error_1.AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); } consumed = true; let done = false; try { for await (const line of iterLines()) { if (done) continue; if (line) yield JSON.parse(line); } done = true; } catch (e) { // If the user calls `stream.controller.abort()`, we should exit without throwing. if ((0, errors_1.isAbortError)(e)) return; throw e; } finally { // If the user `break`s, abort the ongoing request. if (!done) controller.abort(); (0, request_signal_1.releaseRequestSignal)(controller); } } return new Stream(iterator, controller, client); } [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { return this.iterator(); } /** * Splits the stream into two streams which can be * independently read from at different speeds. */ tee() { const left = []; const right = []; const iterator = this[Symbol.asyncIterator](); const teeIterator = (queue) => { return { next: () => { if (queue.length === 0) { const result = iterator.next(); left.push(result); right.push(result); } return queue.shift(); }, }; }; return [ new Stream(() => teeIterator(left), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")), new Stream(() => teeIterator(right), this.controller, tslib_1.__classPrivateFieldGet(this, _Stream_client, "f")), ]; } /** * Converts this stream to a newline-separated ReadableStream of * JSON stringified values in the stream * which can be turned back into a Stream with `Stream.fromReadableStream()`. */ toReadableStream() { const self = this; let iter; return (0, shims_1.makeReadableStream)({ async start() { iter = self[Symbol.asyncIterator](); }, async pull(ctrl) { try { const { value, done } = await iter.next(); if (done) return ctrl.close(); const bytes = (0, bytes_1.encodeUTF8)(JSON.stringify(value) + '\n'); ctrl.enqueue(bytes); } catch (err) { ctrl.error(err); } }, async cancel() { await iter.return?.(); }, }); } } return Stream; })(); exports.Stream = Stream; async function* _iterSSEMessages(response, controller) { if (!response.body) { controller.abort(); if (typeof globalThis.navigator !== 'undefined' && globalThis.navigator.product === 'ReactNative') { throw new error_1.AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); } throw new error_1.AnthropicError(`Attempted to iterate over a response with no body`); } const decoder = new TextDecoder('utf-8', { ignoreBOM: true }); let text = ''; let endsWithCR = false; let event = null; let data = []; let raw = []; const takeLine = (line) => { if (line.charCodeAt(0) === 0xfeff) line = line.slice(1); if (!line) { // empty line and we didn't previously encounter any messages if (!event && !data.length) return null; const sse = { event, data: data.join('\n'), raw }; event = null; data = []; raw = []; return sse; } raw.push(line); const colon = line.indexOf(':'); if (colon === 0) return null; const fieldname = colon === -1 ? line : line.slice(0, colon); if (fieldname !== 'event' && fieldname !== 'data') return null; const value = colon === -1 ? '' : line.slice(line.charCodeAt(colon + 1) === 0x20 ? colon + 2 : colon + 1); if (fieldname === 'event') event = value; else data.push(value); return null; }; for await (const chunk of (0, shims_2.ReadableStreamToAsyncIterable)(response.body)) { if (chunk == null) continue; const decoded = decoder.decode(typeof chunk === 'string' ? (0, bytes_1.encodeUTF8)(chunk) : chunk, { stream: true }); text += decoded; // Searching `text` after `+=` copies the whole pending line, so wait for a chunk with a line ending. if (!endsWithCR && !decoded.includes('\n') && !decoded.includes('\r')) continue; let start = 0; if (!text.includes('\r')) { let end; while ((end = text.indexOf('\n', start)) !== -1) { const sse = takeLine(text.slice(start, end)); start = end + 1; if (sse) yield sse; } } else { for (let i = 0; i < text.length; i++) { const char = text[i]; if (char !== '\n' && char !== '\r') continue; if (char === '\r' && i + 1 === text.length) break; const sse = takeLine(text.slice(start, i)); if (char === '\r' && text[i + 1] === '\n') i++; start = i + 1; if (sse) yield sse; } } text = text.slice(start); endsWithCR = text.endsWith('\r'); } text += decoder.decode(); if (text) { for (const line of text.replace(/\r$/, '').split(/\r\n|[\n\r]/)) { const sse = takeLine(line); if (sse) yield sse; } } } //# sourceMappingURL=streaming.js.map