Open History to see the last commit
1import type { ProviderEnvironment } from './types.ts'
2
3/**
4 * What `fetchJson`, `fetchText` and `fetchOptional` call; the global
5 * `fetch` is one.
6 */
7export type Fetcher = (url: string, init?: RequestInit) => Promise<Response>
8
9/**
10 * A fetch that leaves Cloudflare from eastern North America (issue #356).
11 *
12 * Anthropic and Gemini refuse callers in regions they do not serve
13 * (`403 forbidden` / `400 User location is not supported`). Cron
14 * invocations run wherever Cloudflare has spare capacity, and `placement`
15 * only moves fetch handlers, so the models poll has no fixed location.
16 * A Durable Object is created near its `locationHint` on the first `get()`
17 * and does not move afterwards, so routing the keyed listing calls through
18 * one fixes where they egress. Docs loads go the same way: Anthropic's
19 * docs host serves pages with no tables to the regions its API refuses
20 * (#482), and OpenAI's docs host answers 403 from hkg1 (#505). (The `us`
21 * jurisdiction would be a hard guarantee, but workerd does not implement
22 * it, so `pnpm run dev` would throw.)
23 *
24 * Outside the Workers runtime (Node scripts and unit tests) there is no
25 * binding and the global fetch runs from the caller's own machine. Inside
26 * it, a missing binding is a config error and throws.
27 */
28export function usEgressFetch(env: ProviderEnvironment): Fetcher {
29 const ns = env.US_EGRESS
30 if (!ns) {
31 if (navigator.userAgent === 'Cloudflare-Workers')
32 throw new Error('US_EGRESS binding missing (wrangler.jsonc, issue #356)')
33 return fetch
34 }
35 const stub = ns.get(ns.idFromName('provider-egress'), {
36 locationHint: 'enam',
37 })
38 // workers-types' Request/Response and the DOM ones this file is typed
39 // with are the same runtime classes.
40 return async (url, init) =>
41 (await stub.fetch(url, init as never)) as unknown as Response
42}