Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

5.0 KB
Raw Blame
import { compareVersions } from 'compare-versions'

import { isReadableStreamLike, isRequestLike } from './is'
import { dynamicImport, toDispatchableStream } from './utils'
import { DEFAULT_HTTP_VERSION, type HttpVersion } from './connectionConfig'

type UndiciRequestInit = RequestInit & {
  dispatcher?: unknown
  duplex?: 'half'
}

export type UndiciModule = {
  Agent: new (options: { allowH2: boolean; connections?: number }) => unknown
  ProxyAgent: new (options: {
    uri: string
    allowH2: boolean
    connections?: number
    proxyTunnel: true
  }) => unknown
  fetch: unknown
}

const UNDICI_MIN_NODE = '22.19.0'

export async function loadUndici(
  nodeVersion = globalThis.process?.versions?.node
): Promise<UndiciModule | undefined> {
  if (!nodeVersion || compareVersions(nodeVersion, UNDICI_MIN_NODE) < 0) {
    return undefined
  }

  try {
    return await dynamicImport<UndiciModule>('undici')
  } catch {
    // Fall back to the global fetch when undici cannot load (e.g. bundled apps).
    return undefined
  }
}

/**
 * Late-bind the global fetch: runtimes and tools (msw, instrumentation) may
 * replace `globalThis.fetch` after the SDK builds a fetcher. A factory rather
 * than a shared const so per-proxy cache entries stay distinct closures.
 */
function lateBoundGlobalFetch(): typeof fetch {
  return ((input, init) => globalThis.fetch(input, init)) as typeof fetch
}

/**
 * Create a fetch for the given runtime. Outside Node it late-binds the global
 * fetch. On Node it lazily runs `build` on the first request and caches the
 * built fetcher; a failed build is not cached, so the next request retries
 * instead of replaying the same stale rejection forever.
 */
export function createRuntimeFetch(
  currentRuntime: string,
  build: () => Promise<typeof fetch>
): typeof fetch {
  if (currentRuntime !== 'node') {
    return lateBoundGlobalFetch()
  }

  let fetcherPromise: Promise<typeof fetch> | undefined

  return (async (input, init) => {
    const promise = (fetcherPromise ??= build())

    let fetcher: typeof fetch
    try {
      fetcher = await promise
    } catch (err) {
      // Clear only our own failed build: a stale awaiter of an already-
      // rejected promise must not clobber a newer in-flight build.
      if (fetcherPromise === promise) {
        fetcherPromise = undefined
      }
      throw err
    }

    return fetcher(input, init)
  }) as typeof fetch
}

/**
 * Build a fetch bound to a bounded undici dispatcher (HTTP/2 enabled unless
 * `httpVersion` is `'1.1'`, `connections` origin connections, optional proxy
 * tunnel). Falls back to the global fetch when undici cannot be loaded.
 */
export async function buildDispatchedFetch(options: {
  connections: number
  proxy?: string
  httpVersion?: HttpVersion
  loadUndici?: () => Promise<UndiciModule | undefined>
}): Promise<typeof fetch> {
  const undici = await (options.loadUndici ?? loadUndici)()

  if (!undici) {
    return lateBoundGlobalFetch()
  }

  const { Agent, ProxyAgent, fetch: undiciFetch } = undici
  const allowH2 = (options.httpVersion ?? DEFAULT_HTTP_VERSION) === '2'
  const dispatcher = options.proxy
    ? new ProxyAgent({
        uri: options.proxy,
        allowH2,
        connections: options.connections,
        proxyTunnel: true,
      })
    : new Agent({
        allowH2,
        connections: options.connections,
      })
  const fetchWithDispatcher = undiciFetch as unknown as (
    input: RequestInfo | URL,
    init?: UndiciRequestInit
  ) => Promise<Response>

  return ((input, init) => {
    const request = toUndiciRequestInput(input, init)

    return fetchWithDispatcher(request.input, {
      ...request.init,
      dispatcher,
    })
  }) as typeof fetch
}

function toUndiciRequestInput(
  input: RequestInfo | URL,
  init?: RequestInit
): { input: RequestInfo | URL; init?: RequestInit & { duplex?: 'half' } } {
  // Every Request has to be taken apart here, including one the current global
  // class disowns: undici brand-checks against its own `Request`, so anything
  // it didn't mint itself — even a native one — is coerced to a URL string and
  // fails with `Failed to parse URL from [object Request]`.
  if (!isRequestLike(input)) {
    return { input, init }
  }

  const requestInit: RequestInit & { duplex?: 'half' } = {
    // A Request from another implementation exposes that implementation's
    // stream as its body, which undici would stringify just like the Request
    // itself. Native bodies pass through untouched.
    body: isReadableStreamLike(input.body)
      ? toDispatchableStream(input.body)
      : input.body,
    cache: input.cache,
    credentials: input.credentials,
    headers: input.headers,
    integrity: input.integrity,
    keepalive: input.keepalive,
    method: input.method,
    mode: input.mode,
    redirect: input.redirect,
    referrer: input.referrer,
    referrerPolicy: input.referrerPolicy,
    signal: input.signal,
    ...init,
  }

  if (requestInit.body) {
    requestInit.duplex = 'half'
  }

  return {
    input: input.url,
    init: requestInit,
  }
}