()
| 462 | // ============================================================================ |
| 463 | |
| 464 | export function createChatGptBackendFetch(): FetchFunction { |
| 465 | const fetchFn: FetchLike = async ( |
| 466 | input: RequestInfo | URL, |
| 467 | init?: RequestInit, |
| 468 | ): Promise<Response> => { |
| 469 | let transformedInit = init |
| 470 | |
| 471 | if (init?.body && typeof init.body === 'string') { |
| 472 | try { |
| 473 | const body = JSON.parse(init.body) as Record<string, unknown> |
| 474 | const transformedBody = transformRequestBody(body) |
| 475 | transformedInit = { ...init, body: JSON.stringify(transformedBody) } |
| 476 | } catch { |
| 477 | // If body can't be parsed, pass through unchanged |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | const response = await globalThis.fetch(input, transformedInit) |
| 482 | |
| 483 | if (!response.ok) { |
| 484 | // Map 404 usage-limit errors to 429 (same as opencode plugin) |
| 485 | if (response.status === 404) { |
| 486 | try { |
| 487 | const text = await response.clone().text() |
| 488 | if (/usage_limit|rate_limit/i.test(text)) { |
| 489 | return new Response(text, { |
| 490 | status: 429, |
| 491 | statusText: 'Too Many Requests', |
| 492 | headers: response.headers, |
| 493 | }) |
| 494 | } |
| 495 | } catch { |
| 496 | // Fall through to return original response |
| 497 | } |
| 498 | } |
| 499 | return response |
| 500 | } |
| 501 | |
| 502 | if (!response.body) return response |
| 503 | |
| 504 | const transformedStream = transformResponseStream(response.body) |
| 505 | |
| 506 | return new Response(transformedStream, { |
| 507 | status: response.status, |
| 508 | statusText: response.statusText, |
| 509 | headers: new Headers({ |
| 510 | 'content-type': 'text/event-stream; charset=utf-8', |
| 511 | }), |
| 512 | }) |
| 513 | } |
| 514 | |
| 515 | return fetchFn as FetchFunction |
| 516 | } |
no outgoing calls
no test coverage detected