1*4a8c0978SEvan Bacon/**
2*4a8c0978SEvan Bacon * Copyright © 2022 650 Industries.
3*4a8c0978SEvan Bacon *
4*4a8c0978SEvan Bacon * This source code is licensed under the MIT license found in the
5*4a8c0978SEvan Bacon * LICENSE file in the root directory of this source tree.
6*4a8c0978SEvan Bacon */
7*4a8c0978SEvan Baconimport { fetchAsync } from './fetchAsync';
8*4a8c0978SEvan Bacon
9*4a8c0978SEvan Bacondeclare let global: {
10*4a8c0978SEvan Bacon  globalEvalWithSourceUrl?: any;
11*4a8c0978SEvan Bacon};
12*4a8c0978SEvan Bacon
13*4a8c0978SEvan Bacon/**
14*4a8c0978SEvan Bacon * Load a bundle for a URL using fetch + eval on native and script tag injection on web.
15*4a8c0978SEvan Bacon *
16*4a8c0978SEvan Bacon * @param bundlePath Given a statement like `import('./Bacon')` `bundlePath` would be `Bacon`.
17*4a8c0978SEvan Bacon */
18*4a8c0978SEvan Baconexport function fetchThenEvalAsync(url: string): Promise<void> {
19*4a8c0978SEvan Bacon  return fetchAsync(url).then(({ body, headers }) => {
20*4a8c0978SEvan Bacon    if (
21*4a8c0978SEvan Bacon      headers?.has?.('Content-Type') != null &&
22*4a8c0978SEvan Bacon      headers.get('Content-Type')!.includes('application/json')
23*4a8c0978SEvan Bacon    ) {
24*4a8c0978SEvan Bacon      // Errors are returned as JSON.
25*4a8c0978SEvan Bacon      throw new Error(JSON.parse(body).message || `Unknown error fetching '${url}'`);
26*4a8c0978SEvan Bacon    }
27*4a8c0978SEvan Bacon
28*4a8c0978SEvan Bacon    // NOTE(EvanBacon): All of this code is ignored in development mode at the root.
29*4a8c0978SEvan Bacon
30*4a8c0978SEvan Bacon    // Some engines do not support `sourceURL` as a comment. We expose a
31*4a8c0978SEvan Bacon    // `globalEvalWithSourceUrl` function to handle updates in that case.
32*4a8c0978SEvan Bacon    if (global.globalEvalWithSourceUrl) {
33*4a8c0978SEvan Bacon      global.globalEvalWithSourceUrl(body, url);
34*4a8c0978SEvan Bacon    } else {
35*4a8c0978SEvan Bacon      // eslint-disable-next-line no-eval
36*4a8c0978SEvan Bacon      eval(body);
37*4a8c0978SEvan Bacon    }
38*4a8c0978SEvan Bacon  });
39*4a8c0978SEvan Bacon}
40