| 24 | } |
| 25 | |
| 26 | function wrapSSE(res: Response, ms: number, ctl: AbortController) { |
| 27 | if (typeof ms !== "number" || ms <= 0) return res |
| 28 | if (!res.body) return res |
| 29 | if (!res.headers.get("content-type")?.includes("text/event-stream")) return res |
| 30 | |
| 31 | const reader = res.body.getReader() |
| 32 | const body = new ReadableStream<Uint8Array>({ |
| 33 | async pull(ctrl) { |
| 34 | const part = await new Promise<Awaited<ReturnType<typeof reader.read>>>((resolve, reject) => { |
| 35 | const id = setTimeout(() => { |
| 36 | const err = new Error("SSE read timed out") |
| 37 | ctl.abort(err) |
| 38 | void reader.cancel(err) |
| 39 | reject(err) |
| 40 | }, ms) |
| 41 | |
| 42 | reader.read().then( |
| 43 | (part) => { |
| 44 | clearTimeout(id) |
| 45 | resolve(part) |
| 46 | }, |
| 47 | (err) => { |
| 48 | clearTimeout(id) |
| 49 | reject(err) |
| 50 | }, |
| 51 | ) |
| 52 | }) |
| 53 | |
| 54 | if (part.done) { |
| 55 | ctrl.close() |
| 56 | return |
| 57 | } |
| 58 | |
| 59 | ctrl.enqueue(part.value) |
| 60 | }, |
| 61 | async cancel(reason) { |
| 62 | ctl.abort(reason) |
| 63 | await reader.cancel(reason) |
| 64 | }, |
| 65 | }) |
| 66 | |
| 67 | return new Response(body, { |
| 68 | headers: new Headers(res.headers), |
| 69 | status: res.status, |
| 70 | statusText: res.statusText, |
| 71 | }) |
| 72 | } |
| 73 | |
| 74 | function prepareOptions(model: ModelV2.Info, pkg: string) { |
| 75 | const options: Record<string, any> = { |