~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
27 lines · 1.2 KB Raw History
// A server named by an https origin it is not reached at in the run, as
// one behind a TLS front is (spec/COMPAT.md, "Its own address"): every
// request the harness makes for that origin goes to the URL it is reached
// at, and is otherwise as it was. Nothing is set for Monolith, or for any
// server reached at the address it names: then every URL is as given.

let front = null

/// From now on, requests for `origin`'s URLs go to `url` instead.
export function setFront(origin, url) {
  front = { origin: new URL(origin).origin, url }
  const sent = globalThis.fetch
  globalThis.fetch = (input, init) => {
    if (typeof input === 'string' || input instanceof URL) return sent(reach(input), init)
    // A Request, as the OAuth client library's fetch makes them: the same
    // request, for the reached URL.
    const to = reach(input.url)
    return sent(to === input.url ? input : new Request(to, input), init)
  }
}

/// Where a request for `u` is sent: `u` itself, unless it is the front's.
export function reach(u) {
  if (!front) return u
  const s = String(u)
  return s === front.origin || s.startsWith(`${front.origin}/`) || s.startsWith(`${front.origin}?`) ? front.url + s.slice(front.origin.length) : u
}