File size: 1,047 Bytes
e81f4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { upstreamErrorCode, upstreamErrorMessage } from "../../shared/errors";
import type { SSEWrite } from "./sse";

export function streamErrorText(e: unknown, prefix = "upstream error"): string {
	const code = upstreamErrorCode(e);
	return `⚠️ ${prefix}: ${upstreamErrorMessage(e)}${code ? ` [${code}]` : ""}`;
}

export function streamInterruptedWarningText(e: unknown): string {
	return streamErrorText(e, "stream interrupted after partial output");
}

export function streamWarningObject(
	e: unknown,
	message: unknown = undefined,
): { code: string; message: unknown } {
	return {
		code: upstreamErrorCode(e) || "stream_interrupted",
		message: message || streamInterruptedWarningText(e),
	};
}

export async function writeStreamWarningEvent(
	write: SSEWrite,
	e: unknown,
	message: unknown = undefined,
): Promise<void> {
	const result = write(
		`event: warning\ndata: ${JSON.stringify({ warning: streamWarningObject(e, message) })}\n\n`,
	);
	if (result && typeof (result as Promise<void>).then === "function")
		await result;
}