(
url: string | (() => string),
options: XhrConnectionOptionsResolver = {},
)
| 823 | * Create an XMLHttpRequest-backed Server-Sent Events connection adapter. |
| 824 | */ |
| 825 | export function xhrServerSentEvents( |
| 826 | url: string | (() => string), |
| 827 | options: XhrConnectionOptionsResolver = {}, |
| 828 | ): ConnectConnectionAdapter { |
| 829 | return { |
| 830 | async *connect(messages, data, abortSignal, runContext) { |
| 831 | const resolvedUrl = typeof url === 'function' ? url() : url |
| 832 | const resolvedOptions = await resolveXhrConnectionOptions(options) |
| 833 | const signal = abortSignal || resolvedOptions.signal |
| 834 | const request = createConfiguredXhrRequest( |
| 835 | resolvedUrl, |
| 836 | resolvedOptions, |
| 837 | messages, |
| 838 | data, |
| 839 | runContext, |
| 840 | ) |
| 841 | const lines = readXhrLines(request.xhr, signal) |
| 842 | if (signal?.aborted) { |
| 843 | await lines.next() |
| 844 | return |
| 845 | } |
| 846 | request.xhr.send(request.body) |
| 847 | let lastThreadId: string | undefined |
| 848 | let lastRunId: string | undefined |
| 849 | let lastModel: string | undefined |
| 850 | |
| 851 | for await (const line of lines) { |
| 852 | if ( |
| 853 | line.startsWith(':') || |
| 854 | line.startsWith('event:') || |
| 855 | line.startsWith('id:') || |
| 856 | line.startsWith('retry:') |
| 857 | ) { |
| 858 | continue |
| 859 | } |
| 860 | |
| 861 | const chunkData = parseSseDataLine(line) |
| 862 | if (chunkData === '[DONE]') { |
| 863 | const synthetic: RunFinishedEvent = { |
| 864 | type: EventType.RUN_FINISHED, |
| 865 | threadId: lastThreadId ?? runContext?.threadId ?? '', |
| 866 | runId: lastRunId ?? runContext?.runId ?? '', |
| 867 | model: lastModel ?? '', |
| 868 | timestamp: Date.now(), |
| 869 | finishReason: 'stop', |
| 870 | } |
| 871 | request.xhr.abort() |
| 872 | yield synthetic |
| 873 | return |
| 874 | } |
| 875 | |
| 876 | const chunk = JSON.parse(chunkData) as StreamChunk |
| 877 | if ('threadId' in chunk && typeof chunk.threadId === 'string') { |
| 878 | lastThreadId = chunk.threadId |
| 879 | } |
| 880 | if ('runId' in chunk && typeof chunk.runId === 'string') { |
| 881 | lastRunId = chunk.runId |
| 882 | } |
no outgoing calls
no test coverage detected