fetch.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. import platform from '../platform/index.js';
  2. import utils from '../utils.js';
  3. import AxiosError from '../core/AxiosError.js';
  4. import composeSignals from '../helpers/composeSignals.js';
  5. import { trackStream } from '../helpers/trackStream.js';
  6. import createMultipartBody from '../core/createMultipartBody.js';
  7. import AxiosHeaders from '../core/AxiosHeaders.js';
  8. import {
  9. progressEventReducer,
  10. progressEventDecorator,
  11. asyncDecorator,
  12. } from '../helpers/progressEventReducer.js';
  13. import resolveConfig from '../helpers/resolveConfig.js';
  14. import settle from '../core/settle.js';
  15. import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js';
  16. import { VERSION } from '../env/data.js';
  17. import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';
  18. const DEFAULT_CHUNK_SIZE = 64 * 1024;
  19. const DEFAULT_REQUEST_OPTIONS = {
  20. cache: 'default',
  21. redirect: 'follow',
  22. referrer: 'about:client',
  23. referrerPolicy: '',
  24. mode: 'cors',
  25. integrity: '',
  26. keepalive: false,
  27. priority: 'auto',
  28. window: null,
  29. };
  30. const { isFunction } = utils;
  31. /**
  32. * Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
  33. * This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
  34. *
  35. * @param {string} str The string to encode
  36. *
  37. * @returns {string} UTF-8 bytes as a Latin-1 string
  38. */
  39. const encodeUTF8 = (str) =>
  40. encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
  41. String.fromCharCode(parseInt(hex, 16))
  42. );
  43. // Node's WHATWG URL parser returns `username` and `password` percent-encoded.
  44. // Decode before composing the `auth` option so credentials such as
  45. // `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
  46. // original value for malformed input so a bad encoding never throws.
  47. const decodeURIComponentSafe = (value) => {
  48. if (!utils.isString(value)) {
  49. return value;
  50. }
  51. try {
  52. return decodeURIComponent(value);
  53. } catch (error) {
  54. return value;
  55. }
  56. };
  57. const test = (fn, ...args) => {
  58. try {
  59. return !!fn(...args);
  60. } catch (e) {
  61. return false;
  62. }
  63. };
  64. const maybeWithAuthCredentials = (url) => {
  65. const protocolIndex = url.indexOf('://');
  66. let urlToCheck = url;
  67. if (protocolIndex !== -1) {
  68. urlToCheck = urlToCheck.slice(protocolIndex + 3);
  69. }
  70. return urlToCheck.includes('@') || urlToCheck.includes(':');
  71. };
  72. const factory = (env) => {
  73. const globalObject =
  74. utils.global !== undefined && utils.global !== null ? utils.global : globalThis;
  75. const { ReadableStream, TextEncoder } = globalObject;
  76. env = utils.merge.call(
  77. {
  78. skipUndefined: true,
  79. },
  80. {
  81. Request: globalObject.Request,
  82. Response: globalObject.Response,
  83. Blob: globalObject.Blob,
  84. },
  85. env
  86. );
  87. const envFetch = utils.hasOwnProp(env, 'fetch') ? env.fetch : undefined;
  88. const { Request, Response, Blob } = env;
  89. const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
  90. const isRequestSupported = isFunction(Request);
  91. const isResponseSupported = isFunction(Response);
  92. if (!isFetchSupported) {
  93. return false;
  94. }
  95. const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
  96. const encodeText =
  97. isFetchSupported &&
  98. (typeof TextEncoder === 'function'
  99. ? (
  100. (encoder) => (str) =>
  101. encoder.encode(str)
  102. )(new TextEncoder())
  103. : async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
  104. const supportsRequestStream =
  105. isRequestSupported &&
  106. isReadableStreamSupported &&
  107. test(() => {
  108. let duplexAccessed = false;
  109. const request = new Request(platform.origin, {
  110. body: new ReadableStream(),
  111. method: 'POST',
  112. get duplex() {
  113. duplexAccessed = true;
  114. return 'half';
  115. },
  116. });
  117. const hasContentType = request.headers.has('Content-Type');
  118. if (request.body != null) {
  119. request.body.cancel();
  120. }
  121. return duplexAccessed && !hasContentType;
  122. });
  123. const supportsResponseStream =
  124. isResponseSupported &&
  125. isReadableStreamSupported &&
  126. test(() => utils.isReadableStream(new Response('').body));
  127. // Some runtimes reject every explicit cache mode. Use own defaults for both
  128. // probes so unrelated polluted options cannot affect cache-mode detection.
  129. const requestDefaults = Object.assign(Object.create(null), DEFAULT_REQUEST_OPTIONS);
  130. if (isRequestSupported && !test(() => new Request(platform.origin, requestDefaults))) {
  131. delete requestDefaults.cache;
  132. // Only omit cache when that makes Request construction succeed. Otherwise
  133. // retain the explicit default that protects supporting runtimes from pollution.
  134. if (!test(() => new Request(platform.origin, requestDefaults))) {
  135. requestDefaults.cache = DEFAULT_REQUEST_OPTIONS.cache;
  136. }
  137. }
  138. const resolvers = {
  139. stream: supportsResponseStream && ((res) => res.body),
  140. };
  141. isFetchSupported &&
  142. (() => {
  143. ['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {
  144. !resolvers[type] &&
  145. (resolvers[type] = (res, config) => {
  146. let method = res && res[type];
  147. if (method) {
  148. return method.call(res);
  149. }
  150. throw new AxiosError(
  151. `Response type '${type}' is not supported`,
  152. AxiosError.ERR_NOT_SUPPORT,
  153. config
  154. );
  155. });
  156. });
  157. })();
  158. const getBodyLength = async (body) => {
  159. if (body == null) {
  160. return 0;
  161. }
  162. if (utils.isBlob(body)) {
  163. return body.size;
  164. }
  165. if (utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {
  166. return body.byteLength;
  167. }
  168. if (utils.isURLSearchParams(body)) {
  169. body = body + '';
  170. }
  171. if (utils.isString(body)) {
  172. return (await encodeText(body)).byteLength;
  173. }
  174. };
  175. const resolveBodyLength = async (headers, body) => {
  176. const length = utils.toFiniteNumber(headers.getContentLength());
  177. return length == null ? getBodyLength(body) : length;
  178. };
  179. return async (config) => {
  180. let {
  181. url,
  182. method,
  183. data,
  184. signal,
  185. cancelToken,
  186. timeout,
  187. onDownloadProgress,
  188. onUploadProgress,
  189. responseType,
  190. headers,
  191. withCredentials = 'same-origin',
  192. fetchOptions,
  193. maxContentLength,
  194. maxBodyLength,
  195. maxRedirects,
  196. } = resolveConfig(config);
  197. const hasMaxContentLength = utils.isNumber(maxContentLength) && maxContentLength > -1;
  198. const hasMaxBodyLength = utils.isNumber(maxBodyLength) && maxBodyLength > -1;
  199. const own = (key) => (utils.hasOwnProp(config, key) ? config[key] : undefined);
  200. let _fetch = envFetch || fetch;
  201. responseType = responseType ? (responseType + '').toLowerCase() : 'text';
  202. let composedSignal = composeSignals(
  203. [signal, cancelToken && cancelToken.toAbortSignal()],
  204. timeout
  205. );
  206. let request = null;
  207. const unsubscribe =
  208. composedSignal &&
  209. composedSignal.unsubscribe &&
  210. (() => {
  211. composedSignal.unsubscribe();
  212. });
  213. let requestContentLength;
  214. // AxiosErrors we raise while request or response bodies are being streamed. Captured
  215. // by identity so the catch block can surface it directly, regardless of
  216. // how the runtime wraps the resulting fetch rejection (undici exposes it
  217. // as `err.cause`; some browsers drop the original error entirely).
  218. let pendingBodyError = null;
  219. let pendingResponseError = null;
  220. const maxBodyLengthError = () =>
  221. new AxiosError(
  222. 'Request body larger than maxBodyLength limit',
  223. AxiosError.ERR_BAD_REQUEST,
  224. config,
  225. request
  226. );
  227. try {
  228. // HTTP basic authentication
  229. let auth = undefined;
  230. const configAuth = own('auth');
  231. if (configAuth) {
  232. const username = utils.getSafeProp(configAuth, 'username') || '';
  233. const password = utils.getSafeProp(configAuth, 'password') || '';
  234. auth = {
  235. username,
  236. password,
  237. };
  238. }
  239. let parsedURL;
  240. if (maybeWithAuthCredentials(url)) {
  241. parsedURL = new URL(url, platform.origin);
  242. if (!auth && (parsedURL.username || parsedURL.password)) {
  243. const urlUsername = decodeURIComponentSafe(parsedURL.username);
  244. const urlPassword = decodeURIComponentSafe(parsedURL.password);
  245. auth = {
  246. username: urlUsername,
  247. password: urlPassword,
  248. };
  249. }
  250. if (parsedURL.username || parsedURL.password) {
  251. parsedURL.username = '';
  252. parsedURL.password = '';
  253. url = parsedURL.href;
  254. }
  255. }
  256. if (auth) {
  257. headers.delete('authorization');
  258. headers.set(
  259. 'Authorization',
  260. 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || '')))
  261. );
  262. }
  263. // Enforce maxContentLength for data: URLs up-front so we never materialize
  264. // an oversized payload. The HTTP adapter applies the same check (see http.js
  265. // "if (protocol === 'data:')" branch).
  266. if (hasMaxContentLength && parsedURL && parsedURL.protocol === 'data:') {
  267. const estimated = estimateDataURLDecodedBytes(parsedURL.href);
  268. if (estimated > maxContentLength) {
  269. throw new AxiosError(
  270. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  271. AxiosError.ERR_BAD_RESPONSE,
  272. config,
  273. request
  274. );
  275. }
  276. }
  277. const formContentType =
  278. utils.isSpecCompliantForm(data) && AxiosHeaders.from(own('headers')).getContentType();
  279. let formBoundary;
  280. if (
  281. utils.isString(formContentType) &&
  282. /^multipart\/form-data(?:\s*;|$)/i.test(formContentType.trim())
  283. ) {
  284. const parameters = AxiosHeaders.parseParameters(formContentType);
  285. if (utils.hasOwnProp(parameters, 'boundary')) formBoundary = parameters.boundary;
  286. }
  287. if (
  288. utils.isSpecCompliantForm(data) &&
  289. method !== 'get' &&
  290. method !== 'head' &&
  291. (hasMaxBodyLength ||
  292. (onUploadProgress && supportsRequestStream) ||
  293. formBoundary !== undefined)
  294. ) {
  295. data = createMultipartBody(
  296. data,
  297. Blob,
  298. hasMaxBodyLength ? maxBodyLength : Infinity,
  299. maxBodyLengthError,
  300. formBoundary
  301. );
  302. // Blob.type lowercases its value, including a case-sensitive boundary.
  303. // Retain the caller's header when an explicit boundary was serialized.
  304. headers.setContentType(formBoundary === undefined ? data.type : formContentType);
  305. requestContentLength = data.size;
  306. }
  307. // Enforce maxBodyLength against known-size bodies before dispatch using
  308. // the body's *actual* size — never a caller-declared Content-Length,
  309. // which could under-report to slip an oversized body past the check.
  310. // Unknown-size streams return undefined here and are counted per-chunk
  311. // below as fetch consumes them.
  312. if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
  313. const outboundLength = await getBodyLength(data);
  314. if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
  315. requestContentLength = outboundLength;
  316. if (outboundLength > maxBodyLength) {
  317. throw maxBodyLengthError();
  318. }
  319. }
  320. }
  321. // A streamed body under maxBodyLength must be counted as fetch consumes
  322. // it; its size is never trusted from a caller-declared Content-Length.
  323. const mustEnforceStreamBody =
  324. hasMaxBodyLength && (utils.isReadableStream(data) || utils.isStream(data));
  325. const trackRequestStream = (stream, onProgress, flush) =>
  326. trackStream(
  327. stream,
  328. DEFAULT_CHUNK_SIZE,
  329. (loadedBytes) => {
  330. if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
  331. throw (pendingBodyError = maxBodyLengthError());
  332. }
  333. onProgress && onProgress(loadedBytes);
  334. },
  335. flush
  336. );
  337. if (
  338. supportsRequestStream &&
  339. method !== 'get' &&
  340. method !== 'head' &&
  341. (onUploadProgress || mustEnforceStreamBody)
  342. ) {
  343. requestContentLength =
  344. requestContentLength == null
  345. ? await resolveBodyLength(headers, data)
  346. : requestContentLength;
  347. // A declared length of 0 is only trusted to skip the wrap when we are
  348. // not enforcing a stream limit (which must not rely on that header).
  349. if (requestContentLength !== 0 || mustEnforceStreamBody) {
  350. let _request = new Request(url, {
  351. method: 'POST',
  352. body: data,
  353. duplex: 'half',
  354. });
  355. let contentTypeHeader;
  356. if (
  357. utils.isFormData(data) &&
  358. (contentTypeHeader = _request.headers.get('content-type'))
  359. ) {
  360. headers.setContentType(contentTypeHeader);
  361. }
  362. if (_request.body) {
  363. const [onProgress, flush] =
  364. (onUploadProgress &&
  365. progressEventDecorator(
  366. requestContentLength,
  367. progressEventReducer(asyncDecorator(onUploadProgress))
  368. )) ||
  369. [];
  370. data = trackRequestStream(_request.body, onProgress, flush);
  371. }
  372. }
  373. } else if (
  374. mustEnforceStreamBody &&
  375. !isRequestSupported &&
  376. isReadableStreamSupported &&
  377. method !== 'get' &&
  378. method !== 'head'
  379. ) {
  380. data = trackRequestStream(data);
  381. } else if (
  382. mustEnforceStreamBody &&
  383. isRequestSupported &&
  384. !supportsRequestStream &&
  385. method !== 'get' &&
  386. method !== 'head'
  387. ) {
  388. throw new AxiosError(
  389. 'Stream request bodies are not supported by the current fetch implementation',
  390. AxiosError.ERR_NOT_SUPPORT,
  391. config,
  392. request
  393. );
  394. }
  395. if (!utils.isString(withCredentials)) {
  396. withCredentials = withCredentials ? 'include' : 'omit';
  397. }
  398. // Cloudflare Workers throws when credentials are defined
  399. // see https://github.com/cloudflare/workerd/issues/902
  400. const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
  401. // If data is FormData and Content-Type is multipart/form-data without boundary,
  402. // delete it so fetch can set it correctly with the boundary
  403. if (utils.isFormData(data)) {
  404. const contentType = headers.getContentType();
  405. if (
  406. contentType &&
  407. /^multipart\/form-data/i.test(contentType) &&
  408. !/boundary=/i.test(contentType)
  409. ) {
  410. headers.delete('content-type');
  411. }
  412. }
  413. // Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
  414. headers.set('User-Agent', 'axios/' + VERSION, false);
  415. const safeFetchOptions =
  416. fetchOptions == null ? fetchOptions : Object.assign(Object.create(null), fetchOptions);
  417. if (safeFetchOptions) {
  418. // These options are owned by Axios and are already reflected in the
  419. // resolved Request passed to fetch.
  420. delete safeFetchOptions.body;
  421. delete safeFetchOptions.headers;
  422. delete safeFetchOptions.method;
  423. delete safeFetchOptions.signal;
  424. delete safeFetchOptions.duplex;
  425. delete safeFetchOptions.credentials;
  426. }
  427. const resolvedOptions = Object.assign(Object.create(null), safeFetchOptions, {
  428. signal: composedSignal,
  429. method: method.toUpperCase(),
  430. headers: toByteStringHeaderObject(headers.normalize()),
  431. body: data,
  432. duplex: 'half',
  433. credentials: isCredentialsSupported ? withCredentials : undefined,
  434. });
  435. if (isRequestSupported) {
  436. utils.forEach(requestDefaults, (value, key) => {
  437. if (resolvedOptions[key] === undefined) {
  438. resolvedOptions[key] = value;
  439. }
  440. });
  441. if (resolvedOptions.signal === undefined) {
  442. resolvedOptions.signal = null;
  443. }
  444. if (resolvedOptions.body === undefined) {
  445. resolvedOptions.body = null;
  446. }
  447. }
  448. if (maxRedirects === 0) {
  449. resolvedOptions.redirect = 'manual';
  450. if (safeFetchOptions) {
  451. safeFetchOptions.redirect = 'manual';
  452. }
  453. }
  454. request = isRequestSupported && new Request(url, resolvedOptions);
  455. let response = await (isRequestSupported
  456. ? _fetch(request, safeFetchOptions)
  457. : _fetch(url, resolvedOptions));
  458. const responseHeaders = AxiosHeaders.from(response.headers);
  459. // Cheap pre-check: if the server honestly declares a content-length that
  460. // already exceeds the cap, reject before we start streaming.
  461. if (hasMaxContentLength) {
  462. const declaredLength = utils.toFiniteNumber(responseHeaders.getContentLength());
  463. if (declaredLength != null && declaredLength > maxContentLength) {
  464. throw new AxiosError(
  465. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  466. AxiosError.ERR_BAD_RESPONSE,
  467. config,
  468. request
  469. );
  470. }
  471. }
  472. const isStreamResponse =
  473. supportsResponseStream && (responseType === 'stream' || responseType === 'response');
  474. if (
  475. supportsResponseStream &&
  476. response.body &&
  477. (onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe))
  478. ) {
  479. const options = {};
  480. ['status', 'statusText', 'headers'].forEach((prop) => {
  481. options[prop] = response[prop];
  482. });
  483. const responseContentLength = utils.toFiniteNumber(responseHeaders.getContentLength());
  484. const [onProgress, flush] =
  485. (onDownloadProgress &&
  486. progressEventDecorator(
  487. responseContentLength,
  488. progressEventReducer(asyncDecorator(onDownloadProgress), true)
  489. )) ||
  490. [];
  491. let bytesRead = 0;
  492. const onChunkProgress = (loadedBytes) => {
  493. if (hasMaxContentLength) {
  494. bytesRead = loadedBytes;
  495. if (bytesRead > maxContentLength) {
  496. throw (pendingResponseError = new AxiosError(
  497. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  498. AxiosError.ERR_BAD_RESPONSE,
  499. config,
  500. request
  501. ));
  502. }
  503. }
  504. onProgress && onProgress(loadedBytes);
  505. };
  506. response = new Response(
  507. trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
  508. flush && flush();
  509. unsubscribe && unsubscribe();
  510. }),
  511. options
  512. );
  513. }
  514. responseType = responseType || 'text';
  515. let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](
  516. response,
  517. config
  518. );
  519. // Fallback enforcement for environments without ReadableStream support
  520. // (legacy runtimes). Detect materialized size from typed output; skip
  521. // streams/Response passthrough since the user will read those themselves.
  522. if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
  523. let materializedSize;
  524. if (responseData != null) {
  525. if (typeof responseData.byteLength === 'number') {
  526. materializedSize = responseData.byteLength;
  527. } else if (typeof responseData.size === 'number') {
  528. materializedSize = responseData.size;
  529. } else if (typeof responseData === 'string') {
  530. materializedSize =
  531. typeof TextEncoder === 'function'
  532. ? new TextEncoder().encode(responseData).byteLength
  533. : responseData.length;
  534. }
  535. }
  536. if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
  537. throw new AxiosError(
  538. 'maxContentLength size of ' + maxContentLength + ' exceeded',
  539. AxiosError.ERR_BAD_RESPONSE,
  540. config,
  541. request
  542. );
  543. }
  544. }
  545. !isStreamResponse && unsubscribe && unsubscribe();
  546. return await new Promise((resolve, reject) => {
  547. settle(resolve, reject, {
  548. data: responseData,
  549. headers: AxiosHeaders.from(response.headers),
  550. status: response.status,
  551. statusText: response.statusText,
  552. config,
  553. request,
  554. });
  555. });
  556. } catch (err) {
  557. unsubscribe && unsubscribe();
  558. // Safari can surface fetch aborts as a DOMException-like object whose
  559. // branded getters throw. Prefer our composed signal reason before reading
  560. // the caught error, preserving timeout vs cancellation semantics.
  561. if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
  562. const canceledError = composedSignal.reason;
  563. canceledError.config = config;
  564. request && (canceledError.request = request);
  565. if (err !== canceledError) {
  566. // Non-enumerable to match native Error `cause` semantics so loggers
  567. // don't recurse into circular fetch internals (see #7205).
  568. Object.defineProperty(canceledError, 'cause', {
  569. __proto__: null,
  570. value: err,
  571. writable: true,
  572. enumerable: false,
  573. configurable: true,
  574. });
  575. }
  576. throw canceledError;
  577. }
  578. // Surface a maxBodyLength violation we raised while the request body was
  579. // being streamed. Keeping the original error (rather than reading
  580. // `err.cause.isAxiosError`) keeps the error deterministic across runtimes
  581. // and avoids both prototype-pollution reads and mis-attributing a foreign
  582. // AxiosError that merely happened to land in `err.cause`.
  583. if (pendingBodyError) {
  584. request && !pendingBodyError.request && (pendingBodyError.request = request);
  585. throw pendingBodyError;
  586. }
  587. if (pendingResponseError) {
  588. throw pendingResponseError;
  589. }
  590. // Re-throw AxiosErrors we raised synchronously (data: URL / content-length
  591. // pre-checks, response size enforcement) without re-wrapping them.
  592. if (err instanceof AxiosError) {
  593. request && !err.request && (err.request = request);
  594. throw err;
  595. }
  596. if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
  597. const networkError = new AxiosError(
  598. 'Network Error',
  599. AxiosError.ERR_NETWORK,
  600. config,
  601. request,
  602. err && err.response
  603. );
  604. // Non-enumerable to match native Error `cause` semantics so loggers
  605. // don't recurse into circular fetch internals (see #7205).
  606. Object.defineProperty(networkError, 'cause', {
  607. __proto__: null,
  608. value: err.cause || err,
  609. writable: true,
  610. enumerable: false,
  611. configurable: true,
  612. });
  613. throw networkError;
  614. }
  615. throw AxiosError.from(err, err && err.code, config, request, err && err.response);
  616. }
  617. };
  618. };
  619. const seedCache = new Map();
  620. export const getFetch = (config) => {
  621. const env = Object.create(null);
  622. const configuredEnv = config && utils.hasOwnProp(config, 'env') && config.env;
  623. ['fetch', 'Request', 'Response', 'Blob'].forEach((key) => {
  624. if (configuredEnv && utils.hasOwnProp(configuredEnv, key)) {
  625. env[key] = configuredEnv[key];
  626. }
  627. });
  628. const { fetch, Request, Response, Blob } = env;
  629. const seeds = [Request, Response, fetch, Blob];
  630. let len = seeds.length,
  631. i = len,
  632. seed,
  633. target,
  634. map = seedCache;
  635. while (i--) {
  636. seed = seeds[i];
  637. target = map.get(seed);
  638. target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));
  639. map = target;
  640. }
  641. return target;
  642. };
  643. const adapter = getFetch();
  644. export default adapter;