 function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
import { asyncWaterfall } from '../../util/asyncWaterfall'
import { shuffle } from '../../util/shuffle'

// Hard-coded CORS proxy server
const PROXY_SERVER_URLS = [
  'https://cors1.edge.app',
  'https://cors2.edge.app',
  'https://cors3.edge.app',
  'https://cors4.edge.app'
]

export const fetchCorsProxy = async (
  uri,
  opts
) => {
  const shuffledUrls = shuffle([...PROXY_SERVER_URLS])
  const tasks = shuffledUrls.map(
    proxyServerUrl => async () =>
      await window.fetch(proxyServerUrl, {
        ...opts,
        headers: {
          ..._optionalChain([opts, 'optionalAccess', _ => _.headers]),
          'x-proxy-url': uri
        }
      })
  )
  return await asyncWaterfall(tasks)
}
