feat(boc): Complete Business Operations Center v1.0

- Go backend API with full CRUD for all modules (CRM, Sales, Finance, HR, Legal, Marketing, Support, Purchase, Inventory, Projects, Automation, Analytics)
- Rust analytics service with parallel report generation
- C runtime with POSIX shared memory IPC
- PostgreSQL schema with 30+ tables, full migrations
- Redis cache, sessions, pub/sub
- Kafka event streaming with Zookeeper
- WebSocket hub for real-time updates
- Automation engine with cron jobs, workflows, event triggers
- JWT authentication, multi-tenant from start
- Docker Compose with all services
- Nginx reverse proxy with rate limiting
- Integration tests passing
- Feature gap analysis against Fortnox/Odoo/Visma

Refs: BOC-001
This commit is contained in:
Bernt
2026-07-12 12:41:35 +00:00
parent 4789a7fb48
commit 58ca4e68db
26666 changed files with 575891 additions and 2074516 deletions
+1872
View File
@@ -0,0 +1,1872 @@
# Changelog
## v1.18.0 — June 13, 2026
This release hardens redirect and URL handling, improves the validateStatus configuration semantics, and includes updates to documentation, dependencies, and release metadata.
## 🔒 Security Fixes
* **Redirect Header Safety:** Added Node HTTP adapter support for stripping caller-specified sensitive headers on cross-origin redirects, helping prevent custom auth headers such as API keys from leaking to another origin. (__#10892__)
* **URL And Request Hardening:** Rejects malformed `http:` and `https:` URLs that omit `//` with `ERR_INVALID_URL`, while tightening prototype-pollution-safe config reads, stream size limits, FormData depth handling, data URL sizing, and local `NO_PROXY` matching. (__#11000__)
## 🐛 Bug Fixes
* **Status Validation:** Added `transitional.validateStatusUndefinedResolves` so applications can opt in to treating `validateStatus: undefined` like the option was omitted, while `validateStatus: null` remains the explicit way to accept every status. (__#10899__)
## 🔧 Maintenance & Chores
* **Documentation:** Published the v1.17.0 release notes, fixed a changelog typo, clarified the package update PR policy, and marked the `proxy` request config as Node.js-only in the advanced docs. (__#10984__, __#10988__, __#10992__, __#10995__)
* **Dependencies:** Bumped `@babel/core`, `@babel/preset-env`, `@commitlint/cli`, `@commitlint/config-conventional`, `@rollup/plugin-babel`, `@rollup/plugin-commonjs`, `@vitest/browser`, `@vitest/browser-playwright`, `eslint`, `lint-staged`, `rollup`, `vitest`, and `actions/checkout`. (__#10989__, __#10996__, __#10997__)
* **Release Metadata:** Prepared the 1.18.0 release by updating package metadata and the runtime `VERSION` value. (__#11003__)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
* __@drori12__ (__#10984__)
* __@eyupcanakman__ (__#10899__)
* __@Adi-Beker__ (__#10995__)
[Full Changelog](https://github.com/axios/axios/compare/v1.17.0...v1.18.0)
## v1.17.0 — June 1, 2026
This release adds Node HTTP zstd decompression, hardens config and release workflows, and fixes authentication, header, proxy, and type-handling regressions.
## 🔒 Security Fixes
* **Config Hardening:** Guarded `socketPath`, `params`, and `paramsSerializer` reads with own-property checks to prevent inherited prototype values from affecting request behavior, including SSRF-sensitive paths. (__#10901__, __#10922__)
* **Release Publishing:** Switched the publish workflow to npm staged publishing for safer, auditable package releases with provenance. (__#10926__)
## 🚀 New Features
* **HTTP Compression:** Added Node HTTP adapter support for zstd response decompression, with `transitional.advertiseZstdAcceptEncoding` controlling whether `zstd` is advertised in `Accept-Encoding`. (__#6792__, __#10920__)
## 🐛 Bug Fixes
* **Authentication Handling:** Restored Basic auth on same-origin Node redirects while continuing to strip credentials cross-origin, and aligned the fetch adapter with HTTP adapter behavior for URL-embedded Basic auth. (__#10929__, __#10896__)
* **Proxy TLS:** Preserved user `httpsAgent` TLS options when tunneling HTTPS requests through HTTP CONNECT proxies. (__#10957__)
* **React Native FormData:** Cleared default `Content-Type` for React Native `FormData` so multipart boundaries can be generated correctly. (__#10898__)
* **Headers:** Silently skipped empty or whitespace-only header names instead of throwing, matching parsed-header behavior and avoiding React Native response crashes. (__#10875__)
* **Request Data Merging:** Preserved enumerable symbol keys when cloning plain request data through axios merge logic. (__#10812__)
* **Bundler Compatibility:** Converted `resolveConfig` from an arrow default export to a named function export to avoid webpack and Babel transform interop failures. (__#10891__)
* **Types:** Corrected `AxiosHeaders.toJSON()` return types and updated CommonJS `isCancel` typings to narrow to `CanceledError<T>`. (__#10956__, __#10952__)
* **Build Tooling:** Avoided emitting a null `Authorization` header from the GitHub build helper when `GITHUB_TOKEN` is unset. (__#10931__)
## 🔧 Maintenance & Chores
* **HTTP/2 Internals:** Extracted `Http2Sessions` into its own helper module and added direct unit coverage for session pooling, timeout, and cleanup behavior. (__#10861__)
* **Package Publishing:** Reduced published package size by switching to a `files` allowlist and dropping unneeded unminified bundle source maps. (__#10939__)
* **CI and Release Automation:** Added bundle-size reporting, moved reports to the job summary, fixed bundle-size comparison coverage, added Node 26 to the matrix, pinned npm for staged publishing, and prepared the 1.17.0 release. (__#10907__, __#10911__, __#10916__, __#10927__, __#10935__, __#10983__)
* **Developer Workflow:** Added a dev container and iterated on OpenSpec workflow files before removing them from the release branch. (__#10925__, __#10914__, __#10958__)
* **Documentation and Policy:** Updated disclosure, contributor, collaboration, threat-model, advanced docs, README badges, release notes, moderator configuration, and project metadata. (__#10890__, __#10889__, __#10921__, __#10945__, __#10905__, __#10933__, __#10915__, __#10887__, __#10955__)
* **Dependencies:** Bumped Babel tooling, Commitlint, ESLint, Rollup, Globals, Vitest, Playwright, `fs-extra`, `qs`, docs dependencies, and GitHub Actions dependencies including `actions/dependency-review-action` and `zizmorcore/zizmor-action`. (__#10871__, __#10879__, __#10918__, __#10919__, __#10934__, __#10947__, __#10954__, __#10960__)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
* __@BasixKOR__ (__#6792__)
* __@carladams1299-lab__ (__#10861__)
* __@LaplaceYoung__ (__#10812__)
* __@JamieMagee__ (__#10939__)
* __@RonGamzu__ (__#10905__)
* __@sapirbaruch__ (__#10891__)
* __@nezukoagent__ (__#10901__)
* __@devareddy05__ (__#10929__)
* __@Mohammad-Faiz-Cloud-Engineer__ (__#10922__)
* __@azandabot__ (__#10931__)
* __@niksy__ (__#10896__)
[Full Changelog](https://github.com/axios/axios/compare/v1.16.1...v1.17.0)
## v1.16.1 — May 13, 2026
This release ships a defence-in-depth fix for prototype pollution in `formDataToJSON`, hardens proxy and CI workflows, restores Webpack 4 compatibility for the fetch adapter, and includes several small bug fixes and maintenance improvements.
## 🔒 Security Fixes
* **Prototype Pollution Defence-in-Depth:** Hardened `formDataToJSON` against already-polluted `Object.prototype` by walking own properties only, so attacker-controlled keys inherited from a poisoned prototype cannot propagate through deserialization. (__#7413__)
* **Proxy Cleartext Leak:** Fixed an issue where HTTPS request data could be transmitted in cleartext to an HTTP proxy under certain configurations. (__#10858__)
* **CI Cache Removal:** Removed all GitHub Actions caches as a defence-in-depth measure against cache poisoning vectors in the build pipeline. (__#10882__)
## 🐛 Bug Fixes
* **Data URI Parsing:** Updated the `fromDataURI` regex to match RFC 2397 more strictly, fixing edge cases in `data:` URL handling. (__#10829__)
* **Unicode Headers:** Preserved Unicode header values when running through request interceptors, so non-ASCII header content is no longer corrupted before dispatch. (__#10850__)
* **XHR Upload Progress:** Guarded against malformed `ProgressEvent` payloads emitted by some environments during XHR upload, preventing crashes when `loaded` / `total` are missing or invalid. (__#10868__)
* **Webpack 4 Fetch Adapter:** Fixed an "unexpected token" error caused by syntax in the fetch adapter that Webpack 4 could not parse, restoring compatibility for legacy bundler users. (__#10864__)
* **Type Definitions:** Made `parseReviver` `context.source` optional in the type definitions to align with the ES2023 specification. (__#10837__)
* **URL Object Support Reverted:** Reverted the change that allowed passing a `URL` object as `config.url` (originally __#10866__) due to regressions; this support will be reintroduced in a later release once the underlying issues are addressed. (__#10874__)
## 🔧 Maintenance & Chores
* **Cycle Detection Refactor:** Replaced the array-based cycle tracker in `toJSONObject` with a `WeakSet`, improving performance and memory behaviour on large nested structures. (__#10832__)
* **composeSignals Cleanup:** Refactored `composeSignals` to use a clearer early-return structure, simplifying the cancellation/abort composition path. (__#10844__)
* **AI Readiness & Repo Docs:** Added `AGENTS.md` and related contributor-guide updates for both human and AI agents, plus post-release documentation improvements. (__#10835__, __#10841__)
* **Docs Improvements:** Clarified the GET request example, fixed the interceptor `eject` example to reference the correct instance, and corrected the Buzzoid sponsor description in the README. (__#10836__, __#10853__, __#10856__)
* **Sponsorship Tooling:** Fixed empty sponsor arrays in the sponsor processing script, added the ability to inject additional sponsors, updated the sponsorship link, and added a Twicsy advertisement entry. (__#10843__, __#10859__, __#10869__)
* **Dependencies:** Bumped `@commitlint/cli` from 20.5.0 to 20.5.2. (__#10846__)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
* __@hpinmetaverse__ (__#10836__)
* __@tommyhgunz14__ (__#7413__)
* __@abhu85__ (__#10829__)
* __@divyanshuraj1095__ (__#10853__)
* __@sagodi97__ (__#10856__)
* __@rkdfx__ (__#10868__)
* __@Liuwei1125__ (__#10866__)
[Full Changelog](https://github.com/axios/axios/compare/v1.16.0...v1.16.1)
## v1.16.0 — May 2, 2026
This release adds support for the QUERY HTTP method and a new `ECONNREFUSED` error constant, lands a substantial wave of HTTP, fetch, and XHR adapter bug fixes around redirects, aborts, headers, and timeouts, and welcomes 23 new contributors.
## ⚠️ Notable Changes
A handful of fixes in this release are either security-adjacent or change observable behaviour. Please review before upgrading:
- **Fetch adapter now enforces `maxBodyLength` and `maxContentLength`.** These limits were silently ignored on the fetch adapter prior to 1.16.0 — anyone relying on them as a safety net (DoS protection, accidental large uploads) had no protection. (**#10795**)
- **Proxy requests now preserve user-supplied `Host` headers.** Previously, the proxy path could overwrite a custom `Host`. Virtual-host-style routing through a proxy will now behave correctly. (**#10822**)
- **Basic auth credentials embedded in URLs are now URL-decoded.** If you have percent-encoded credentials in a URL (e.g. `https://user:p%40ss@host`), the decoded value is what now goes on the wire. (**#10825**)
- **`parseProtocol` now strictly requires a colon in the protocol separator.** Strings that loosely parsed as protocols before may no longer match. (**#10729**)
- **Deprecated `unescape()` replaced with modern UTF-8 encoding.** Non-ASCII URL handling is now spec-correct; consumers depending on legacy `unescape()` quirks may see different output bytes. (**#7378**)
- **`transformRequest` input typing change was reverted.** The typing change introduced in #10745 was reverted in #10810 after follow-up review — net behavior is unchanged from 1.15.2. (**#10745**, **#10810**)
## 🚀 New Features
- **QUERY HTTP Method:** Added support for the QUERY HTTP method across adapters and type definitions. (**#10802**)
- **ECONNREFUSED Error Constant:** Exposed `ECONNREFUSED` as a constant on `AxiosError` so callers can match connection-refused failures without comparing string literals (closes #6485). (**#10680**)
- **Encode Helper Export:** Exported the internal `encode` helper from `buildURL` so userland param serializers can reuse the same encoding logic that axios uses internally. (**#6897**)
## 🐛 Bug Fixes
- **HTTP Adapter — Redirects & Headers:** Cleared stale headers when a redirect targets a no-proxy host, fixed the redirect listener chain so listeners no longer stack across hops, restored the missing `requestDetails` argument on `beforeRedirect`, preserved user-supplied `Host` headers when forwarding through a proxy, and properly URL-decoded basic auth credentials. (**#10794**, **#10800**, **#6241**, **#10822**, **#10825**)
- **HTTP Adapter — Streams & Timeouts:** Preserved the partial response object on `AxiosError` when a stream is aborted after headers arrive, honoured the `timeout` option during the connect phase when redirects are disabled, and resolved an unsettled-promise hang when an aborted request was combined with compression and `maxRedirects: 0`. (**#10708**, **#10819**, **#7149**)
- **Fetch Adapter:** Enforced `maxBodyLength` / `maxContentLength` in the fetch adapter, set the `User-Agent` header to match the HTTP adapter, preserved the original abort reason instead of replacing it with a generic error, and deferred global access so importing the module no longer throws a `TypeError` in restricted environments. (**#10795**, **#10772**, **#10806**, **#7260**)
- **XHR Adapter:** Unsubscribed the `cancelToken` and `AbortSignal` listeners on the error, timeout, and abort code paths to prevent leaked subscriptions. (**#10787**)
- **Error Handling:** Attached the parsed response to `AxiosError` when `JSON.parse` fails inside `dispatchRequest`, prevented `settle` from emitting `undefined` error codes, and tightened the `parseProtocol` regex to require a colon in the protocol separator. (**#10724**, **#7276**, **#10729**)
- **Types & Exports:** Aligned the CommonJS `CancelToken` typings with the ESM build, fixed a compiler error caused by `RawAxiosHeaders`, and re-exported `create` from the package index. (**#7414**, **#6389**, **#6460**)
- **UTF-8 Encoding:** Replaced the deprecated `unescape()` call with a modern UTF-8 encoding implementation. (**#7378**)
- **Misc Cleanup:** Resolved a batch of small inconsistencies and gadget-level issues across the codebase. (**#10833**)
## 🔧 Maintenance & Chores
- **Refactor — ES6 Modernisation:** Modernised the `utils` module and XHR adapter to use ES6 features, and tidied the multipart boundary error message. (**#10588**, **#7419**)
- **Tests:** Hardened the HTTP test server lifecycle to fix flaky `FormData` EPIPE failures, fixed Win32 platform support for the pipe tests, and corrected an incorrect test assumption. (**#10820**, **#10791**, **#10796**)
- **Docs:** Documented `paramsSerializer.encode` for strict RFC 3986 query encoding, updated the `parseReviver` TypeScript definitions and configuration docs for ES2023, added timeout guidance to the README's first async example, and expanded notes around the recent type changes. (**#10821**, **#10782**, **#10759**, **#10804**)
- **Reverted:** Reverted the `transformRequest` input typing change from #10745 after follow-up review. (**#10745**, **#10810**)
- **Dependencies:** Bumped `actions/setup-node`, the `github-actions` group, and `postcss` (in `/docs`) to their latest versions. (**#10785**, **#10813**, **#10814**)
- **Release:** Updated changelog and packages, and prepared the 1.16.0 release. (**#10790**, **#10834**)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
- **@singhankit001** (**#10588**)
- **@cuiweixie** (**#7419**)
- **@iruizsalinas** (**#10787**)
- **@MarcosNocetti** (**#10680**)
- **@deepview-autofix** (**#10729**)
- **@atharvasingh7007** (**#10745**)
- **@OfekDanny** (**#10772**)
- **@mnahkies** (**#7414**)
- **@tboyila** (**#10759**)
- **@Kingo64** (**#6897**)
- **@ramram1048** (**#6389**)
- **@FLNacif** (**#6460**)
- **@zozo123** (**#10806**)
- **@pierluigilenoci** (**#10802**)
- **@afurm** (**#10708**)
- **@karan-lrn** (**#7378**)
- **@ebeigarts** (**#7149**)
- **@Raymondo97** (**#10782**)
- **@mixelburg** (**#10821**)
- **@ashishkr96** (**#10822**)
- **@cyphercodes** (**#10819**)
- **@Jye10032** (**#7260**)
- **@VeerShah41** (**#7276**)
[Full Changelog](https://github.com/axios/axios/compare/v1.15.2...v1.16.0)
## v1.15.2 - April 21, 2026
This release delivers prototype-pollution hardening for the Node HTTP adapter, adds an opt-in `allowedSocketPaths` allowlist to mitigate SSRF via Unix domain sockets, fixes a keep-alive socket memory leak, and ships supply-chain hardening across CI and security docs.
## 🔒 Security Fixes
- **Prototype Pollution Hardening (HTTP Adapter):** Hardened the Node HTTP adapter and `resolveConfig`/`mergeConfig`/validator paths to read only own properties and use null-prototype config objects, preventing polluted `auth`, `baseURL`, `socketPath`, `beforeRedirect`, and `insecureHTTPParser` from influencing requests. (**#10779**)
- **SSRF via `socketPath`:** Rejects non-string `socketPath` values and adds an opt-in `allowedSocketPaths` config option to restrict permitted Unix domain socket paths, returning `AxiosError` `ERR_BAD_OPTION_VALUE` on mismatch. (**#10777**)
- **Supply-chain Hardening:** Added `.npmrc` with `ignore-scripts=true`, lockfile lint CI, non-blocking reproducible build diff, scoped CODEOWNERS, expanded `SECURITY.md`/`THREATMODEL.md` with provenance verification (`npm audit signatures`), 60-day resolution policy, and maintainer incident-response runbook. (**#10776**)
## 🚀 New Features
- **`allowedSocketPaths` Config Option:** New request config option (and TypeScript types) to allowlist Unix domain socket paths used by the Node http adapter; backwards compatible when unset. (**#10777**)
## 🐛 Bug Fixes
- **Keep-alive Socket Memory Leak:** Installs a single per-socket `error` listener tracking the active request via `kAxiosSocketListener`/`kAxiosCurrentReq`, eliminating per-request listener accumulation, `MaxListenersExceededWarning`, and linear heap growth under concurrent or long-running keep-alive workloads (fixes #10780). (**#10788**)
## 🔧 Maintenance & Chores
- **Changelog:** Updated `CHANGELOG.md` with v1.15.1 release notes. (**#10781**)
[Full Changelog](https://github.com/axios/axios/compare/v1.15.1...v1.15.2)
---
## v1.15.1 - April 19, 2026
This release ships a coordinated set of security hardening fixes across headers, body/redirect limits, multipart handling, and XSRF/prototype-pollution vectors, alongside a broad sweep of bug fixes, test migrations, and threat-model documentation updates.
## 🔒 Security Fixes
- **Header Injection Hardening:** Tightened validation and sanitisation across request header construction to close the header-injection attack surface. (**#10749**)
- **CRLF Stripping in Multipart Headers:** Correctly strips CR/LF from multipart header values to prevent injection via field names and filenames. (**#10758**)
- **Prototype Pollution / Auth Bypass:** Replaced unsafe `in` checks with `hasOwnProperty` to prevent authentication bypass via prototype pollution on config objects, with additional regression tests. (**#10761**, **#10760**)
- **`withXSRFToken` Truthy Bypass:** Short-circuits on any truthy non-boolean value, so an ambiguous config no longer silently leaks the XSRF token cross-origin. (**#10762**)
- **`maxBodyLength` With Zero Redirects:** Enforces `maxBodyLength` even when `maxRedirects` is set to `0`, closing a bypass path for oversized request bodies. (**#10753**)
- **Streamed Response `maxContentLength` Bypass:** Applies `maxContentLength` to streamed responses that previously bypassed the cap. (**#10754**)
- **Follow-up CVE Completion:** Completes an earlier incomplete CVE fix to fully close the regression window. (**#10755**)
## 🚀 New Features
- **AI-Based Docs Translations:** Initial scaffold for AI-assisted translations of the documentation site. (**#10705**)
- **`Location` Request Header Type:** Adds `Location` to `CommonRequestHeadersList` for accurate typing of redirect-aware requests. (**#7528**)
## 🐛 Bug Fixes
- **FormData Handling:** Removes `Content-Type` when no boundary is present on `FormData` fetch requests, supports multi-select fields, cancels `request.body` instead of the source stream on fetch abort, and fixes a recursion bug in form-data serialisation. (**#7314**, **#10676**, **#10702**, **#10726**)
- **HTTP Adapter:** Handles socket-only request errors without leaking keep-alive listeners. (**#10576**)
- **Progress Events:** Clamps `loaded` to `total` for computable upload/download progress events. (**#7458**)
- **Types:** Aligns `runWhen` type with the runtime behaviour in `InterceptorManager` and makes response header keys case-insensitive. (**#7529**, **#10677**)
- **`buildFullPath`:** Uses strict equality in the base/relative URL check. (**#7252**)
- **`AxiosURLSearchParams` Regex:** Improves the regex used for param serialisation to avoid edge-case mismatches. (**#10736**)
- **Resilient Value Parsing:** Parses out header/config values instead of throwing on malformed input. (**#10687**)
- **Docs Artefact Cleanup:** Removes the docs content that was incorrectly committed. (**#10727**)
## 🔧 Maintenance & Chores
- **Threat Model & Security Docs:** Ongoing refinement of `THREATMODEL.md`, including Hopper security update, TLS and tag-replay wording, mitigation descriptions, decompression-bomb guidance, and further cleanup. (**#10672**, **#10715**, **#10718**, **#10722**, **#10763**, **#10765**)
- **Test Coverage & Migration:** Expanded `shouldBypassProxy` coverage for wildcard/IPv6/edge cases, documented and tested `AxiosError.status`, and migrated `progressEventReducer` tests to Vitest. (**#10723**, **#10725**, **#10741**)
- **Type Refactor:** Uses TypeScript utility types to deduplicate literal unions. (**#7520**)
- **Repo & CI:** Adds `CODEOWNERS`, switches v1.x releases to an ephemeral release branch, and removes orphaned Bower support. (**#10739**, **#10738**, **#10746**)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
- **@curiouscoder-cmd** (**#7252**)
- **@tryonelove** (**#7520**)
- **@darwin808** (**#7314**)
- **@zoontek** (**#10702**)
- **@AKIB473** (**#10725**)
[Full Changelog](https://github.com/axios/axios/compare/v1.15.0...v1.15.1)
---
## v1.15.0 - April 7, 2026
This release delivers two critical security patches targeting header injection and SSRF via proxy bypass, adds official runtime support for Deno and Bun, and includes significant CI security hardening.
## 🔒 Security Fixes
- **Header Injection (CRLF):** Rejects any header value containing `\r` or `\n` characters to block CRLF injection chains that could be used to exfiltrate cloud metadata (IMDS). Behavior change: headers with CR/LF now throw `"Invalid character in header content"`. (**#10660**)
- **SSRF via `no_proxy` Bypass:** Introduces a `shouldBypassProxy` helper that normalises hostnames (strips trailing dots, handles bracketed IPv6) before evaluating `no_proxy`/`NO_PROXY` rules, closing a gap that could cause loopback or internal hosts to be inadvertently proxied. (**#10661**)
## 🚀 New Features
- **Deno & Bun Runtime Support:** Added full smoke test suites for Deno and Bun, with CI workflows that run both runtimes before any release is cut. (**#10652**)
## 🐛 Bug Fixes
- **Node.js v22 Compatibility:** Replaced deprecated `url.parse()` calls with the WHATWG `URL`/`URLSearchParams` API across examples, sandbox, and tests, eliminating `DEP0169` deprecation warnings on Node.js v22+. (**#10625**)
## 🔧 Maintenance & Chores
- **CI Security Hardening:** Added [zizmor](https://github.com/zizmorcore/zizmor) GitHub Actions security scanner; switched npm publish to OIDC Trusted Publishing (removing the long-lived `NODE_AUTH_TOKEN`); pinned all action references to full commit SHAs; narrowed workflow permissions to least privilege; gated the publish step behind a dedicated `npm-publish` environment; and blocked the sponsor-block workflow from running on forks. (**#10618**, **#10619**, **#10627**, **#10637**, **#10641**, **#10666**)
- **Docs:** Clarified HTTP/2 support and the unsupported `httpVersion` option; added documentation for header case preservation; improved the `beforeRedirect` example to prevent accidental credential leakage. (**#10644**, **#10654**, **#10624**)
- **Dependencies:** Bumped `picomatch`, `handlebars`, `serialize-javascript`, `vite` (×3), `denoland/setup-deno`, and 4 additional dev dependencies to latest versions. (**#10564**, **#10565**, **#10567**, **#10568**, **#10572**, **#10574**, **#10663**, **#10664**, **#10665**, **#10669**, **#10670**)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
- **@Kilros0817** (**#10625**)
- **@shaanmajid** (**#10616**, **#10617**, **#10618**, **#10619**, **#10637**, **#10641**, **#10666**)
- **@ashstrc** (**#10624**, **#10644**)
- **@Abhi3975** (**#10589**)
- **@raashish1601** (**#10573**)
[Full Changelog](https://github.com/axios/axios/compare/v1.14.0...v1.15.0)
---
## v1.14.0 - March 27, 2026
This release fixes a security vulnerability in the `formidable` dependency, resolves a CommonJS compatibility regression, hardens proxy and HTTP/2 handling, and modernises the build and test toolchain.
## 🔒 Security Fixes
- **Formidable Vulnerability:** Upgraded `formidable` from v2 to v3 to address a reported arbitrary-file vulnerability. Updated test server and assertions to align with the v3 API. (**#7533**)
## 🐛 Bug Fixes
- **CommonJS Compatibility:** Restored `require('axios')` in Node.js by correcting the `main` field in `package.json` to point to the built CJS bundle. (**#7532**)
- **Fetch Adapter:** Cancel the `ReadableStream` body after the request stream capability probe to prevent resource leaks. (**#7515**)
- **Proxy:** Upgraded `proxy-from-env` to v2 and switched to the named `getProxyForUrl` export, fixing proxy detection from environment variables and resolving CJS bundling errors. (**#7499**)
- **HTTP/2:** Close detached HTTP/2 sessions on timeout to free resources when no new requests arrive. (**#7457**)
- **Headers:** Trim trailing CRLF characters from normalised header values. (**#7456**)
## 🔧 Maintenance & Chores
- **Toolchain Modernisation:** Migrated test suite to Vitest, updated ESLint to v10, upgraded Rollup and `@rollup/plugin-babel`, migrated to Husky 9, upgraded TypeScript to latest, and modernised the Express test harness. (**#7484**, **#7489**, **#7498**, **#7505**, **#7506**, **#7507**, **#7508**, **#7509**, **#7510**, **#7516**, **#7522**)
- **Dependencies:** Bumped `multer` to v2, `minimatch`, `tar`, `pacote`, `@babel/preset-env`, and additional dev dependencies. (**#7453**, **#7480**, **#7491**, **#7504**, **#7517**, **#7531**)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
- **@penkzhou** (**#7515**)
- **@aviu16** (**#7456**)
- **@fedotov** (**#7457**)
[Full Changelog](https://github.com/axios/axios/compare/v1.13.6...v1.14.0)
---
## v1.13.6 - February 27, 2026
This release adds React Native Blob support, fixes several enumeration and export regressions, and patches FormData detection for WeChat Mini Program environments.
## 🚀 New Features
- **React Native Blob Support:** Axios now correctly handles native Blob objects in React Native environments. (**#5764**)
## 🐛 Bug Fixes
- **AxiosError:** Fixed `AxiosError.from` not copying the `status` field from the source error. (**#7403**)
- **AxiosError:** Made the `message` property enumerable so it appears in `JSON.stringify` output and `Object.keys`. (**#7392**)
- **FormData Detection:** Corrected safe FormData detection for WeChat Mini Program environments. (**#7324**)
- **React Native / Browserify Export:** Fixed broken module export that caused import failures in React Native and Browserify. (**#7386**)
## 🔧 Maintenance & Chores
- **Dependencies:** Migrated `@rollup/plugin-babel` from v5 to v6 and bumped the development dependencies group. (**#7424**, **#7432**)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
- **@moh3n9595** (**#5764**)
- **@skrtheboss** (**#7403**)
- **@ybbus** (**#7392**)
- **@Shiwaangee** (**#7324**)
- **@Gudahtt** (**#7386**)
[Full Changelog](https://github.com/axios/axios/compare/v1.13.5...v1.13.6)
---
## v1.13.5 - February 8, 2026
This release patches a prototype pollution denial-of-service vulnerability, fixes a missing `status` field regression in `AxiosError`, adds interceptor ordering control, and introduces URL validation for `isAbsoluteURL`.
## 🔒 Security Fixes
- **Prototype Pollution (DoS):** Hardened `mergeConfig` to ignore `__proto__`, `constructor`, and `prototype` keys, preventing denial-of-service via prototype pollution when merging user-supplied config. (**#7369**)
## 🚀 New Features
- **`isAbsoluteURL` Validation:** Added input validation to `isAbsoluteURL` to handle malformed or unexpected input gracefully. (**#7326**)
## 🐛 Bug Fixes
- **AxiosError `status`:** Restored the `status` field on `AxiosError` instances, which was missing in v1.13.3 and later. (**#7368**)
- **Interceptor Ordering:** Added a `useLegacyInterceptorOrder` option to restore pre-v1.13 interceptor execution order for applications relying on the previous behaviour. ([569f028](https://github.com/axios/axios/commit/569f028a5878faaec8d7d138ba686aac407bda4c))
## 🔧 Maintenance & Chores
- **CI:** Fixed run conditions and updated workflow YAMLs. (**#7372**, **#7373**)
- **Dependencies:** Bumped `karma-sourcemap-loader` and minor package versions. (**#7356**, **#7360**)
## 🌟 New Contributors
We are thrilled to welcome our new contributors. Thank you for helping improve axios:
- **@asmitha-16** (**#7326**)
[Full Changelog](https://github.com/axios/axios/compare/v1.13.4...v1.13.5)
---
## v1.13.4 - January 27, 2026
Patch release fixing regressions introduced in v1.13.3, including TypeScript export compatibility and CI/build stability.
## 🐛 Bug Fixes
- **v1.13.3 Regressions:** Fixed multiple issues introduced by the v1.13.3 release, including broken merge configs. (**#7352**)
- **TypeScript Exports:** Corrected TypeScript export declarations to restore proper type resolution. (**#4884**)
## 🔧 Maintenance & Chores
- **CI & Build:** Refactored CI pipeline and build configuration for stability. (**#7340**)
[Full Changelog](https://github.com/axios/axios/compare/v1.13.3...v1.13.4)
---
## [1.13.3](https://github.com/axios/axios/compare/v1.13.2...v1.13.3) (2026-01-20)
### Bug Fixes
- **http2:** Use port 443 for HTTPS connections by default. ([#7256](https://github.com/axios/axios/issues/7256)) ([d7e6065](https://github.com/axios/axios/commit/d7e60653460480ffacecf85383012ca1baa6263e))
- **interceptor:** handle the error in the same interceptor ([#6269](https://github.com/axios/axios/issues/6269)) ([5945e40](https://github.com/axios/axios/commit/5945e40bb171d4ac4fc195df276cf952244f0f89))
- main field in package.json should correspond to cjs artifacts ([#5756](https://github.com/axios/axios/issues/5756)) ([7373fbf](https://github.com/axios/axios/commit/7373fbff24cd92ce650d99ff6f7fe08c2e2a0a04))
- **package.json:** add 'bun' package.json 'exports' condition. Load the Node.js build in Bun instead of the browser build ([#5754](https://github.com/axios/axios/issues/5754)) ([b89217e](https://github.com/axios/axios/commit/b89217e3e91de17a3d55e2b8f39ceb0e9d8aeda8))
- silentJSONParsing=false should throw on invalid JSON ([#7253](https://github.com/axios/axios/issues/7253)) ([#7257](https://github.com/axios/axios/issues/7257)) ([7d19335](https://github.com/axios/axios/commit/7d19335e43d6754a1a9a66e424f7f7da259895bf))
- turn AxiosError into a native error ([#5394](https://github.com/axios/axios/issues/5394)) ([#5558](https://github.com/axios/axios/issues/5558)) ([1c6a86d](https://github.com/axios/axios/commit/1c6a86dd2c0623ee1af043a8491dbc96d40e883b))
- **types:** add handlers to AxiosInterceptorManager interface ([#5551](https://github.com/axios/axios/issues/5551)) ([8d1271b](https://github.com/axios/axios/commit/8d1271b49fc226ed7defd07cd577bd69a55bb13a))
- **types:** restore AxiosError.cause type from unknown to Error ([#7327](https://github.com/axios/axios/issues/7327)) ([d8233d9](https://github.com/axios/axios/commit/d8233d9e8e9a64bfba9bbe01d475ba417510b82b))
- unclear error message is thrown when specifying an empty proxy authorization ([#6314](https://github.com/axios/axios/issues/6314)) ([6ef867e](https://github.com/axios/axios/commit/6ef867e684adf7fb2343e3b29a79078a3c76dc29))
### Features
- add `undefined` as a value in AxiosRequestConfig ([#5560](https://github.com/axios/axios/issues/5560)) ([095033c](https://github.com/axios/axios/commit/095033c626895ecdcda2288050b63dcf948db3bd))
- add automatic minor and patch upgrades to dependabot ([#6053](https://github.com/axios/axios/issues/6053)) ([65a7584](https://github.com/axios/axios/commit/65a7584eda6164980ddb8cf5372f0afa2a04c1ed))
- add Node.js coverage script using c8 (closes [#7289](https://github.com/axios/axios/issues/7289)) ([#7294](https://github.com/axios/axios/issues/7294)) ([ec9d94e](https://github.com/axios/axios/commit/ec9d94e9f88da13e9219acadf65061fb38ce080a))
- added copilot instructions ([3f83143](https://github.com/axios/axios/commit/3f83143bfe617eec17f9d7dcf8bafafeeae74c26))
- compatibility with frozen prototypes ([#6265](https://github.com/axios/axios/issues/6265)) ([860e033](https://github.com/axios/axios/commit/860e03396a536e9b926dacb6570732489c9d7012))
- enhance pipeFileToResponse with error handling ([#7169](https://github.com/axios/axios/issues/7169)) ([88d7884](https://github.com/axios/axios/commit/88d78842541610692a04282233933d078a8a2552))
- **types:** Intellisense for string literals in a widened union ([#6134](https://github.com/axios/axios/issues/6134)) ([f73474d](https://github.com/axios/axios/commit/f73474d02c5aa957b2daeecee65508557fd3c6e5)), closes [/github.com/microsoft/TypeScript/issues/33471#issuecomment-1376364329](https://github.com//github.com/microsoft/TypeScript/issues/33471/issues/issuecomment-1376364329)
### Reverts
- Revert "fix: silentJSONParsing=false should throw on invalid JSON (#7253) (#7…" (#7298) ([a4230f5](https://github.com/axios/axios/commit/a4230f5581b3f58b6ff531b6dbac377a4fd7942a)), closes [#7253](https://github.com/axios/axios/issues/7253) [#7](https://github.com/axios/axios/issues/7) [#7298](https://github.com/axios/axios/issues/7298)
- **deps:** bump peter-evans/create-pull-request from 7 to 8 in the github-actions group ([#7334](https://github.com/axios/axios/issues/7334)) ([2d6ad5e](https://github.com/axios/axios/commit/2d6ad5e48bd29b0b2b5e7e95fb473df98301543a))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/175160345?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ashvin Tiwari](https://github.com/ashvin2005 '+1752/-4 (#7218 #7218 )')
- <img src="https://avatars.githubusercontent.com/u/71729144?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Nikunj Mochi](https://github.com/mochinikunj '+940/-12 (#7294 #7294 )')
- <img src="https://avatars.githubusercontent.com/u/128113546?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Anchal Singh](https://github.com/imanchalsingh '+544/-102 (#7169 #7185 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [jasonsaayman](https://github.com/jasonsaayman '+317/-73 (#7334 #7298 )')
- <img src="https://avatars.githubusercontent.com/u/377911?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Julian Dax](https://github.com/brodo '+99/-120 (#5558 )')
- <img src="https://avatars.githubusercontent.com/u/184285082?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Akash Dhar Dubey](https://github.com/AKASHDHARDUBEY '+167/-0 (#7287 #7288 )')
- <img src="https://avatars.githubusercontent.com/u/145687605?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Madhumita](https://github.com/madhumitaaa '+20/-68 (#7198 )')
- <img src="https://avatars.githubusercontent.com/u/24915252?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Tackoil](https://github.com/Tackoil '+80/-2 (#6269 )')
- <img src="https://avatars.githubusercontent.com/u/145078271?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Justin Dhillon](https://github.com/justindhillon '+41/-41 (#6324 #6315 )')
- <img src="https://avatars.githubusercontent.com/u/184138832?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Rudransh](https://github.com/Rudrxxx '+71/-2 (#7257 )')
- <img src="https://avatars.githubusercontent.com/u/146366930?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [WuMingDao](https://github.com/WuMingDao '+36/-36 (#7215 )')
- <img src="https://avatars.githubusercontent.com/u/46827243?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [codenomnom](https://github.com/codenomnom '+70/-0 (#7201 #7201 )')
- <img src="https://avatars.githubusercontent.com/u/189698992?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Nandan Acharya](https://github.com/Nandann018-ux '+60/-10 (#7272 )')
- <img src="https://avatars.githubusercontent.com/u/7225168?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Eric Dubé](https://github.com/KernelDeimos '+22/-40 (#7042 )')
- <img src="https://avatars.githubusercontent.com/u/915045?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Tibor Pilz](https://github.com/tiborpilz '+40/-4 (#5551 )')
- <img src="https://avatars.githubusercontent.com/u/23138717?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Gabriel Quaresma](https://github.com/joaoGabriel55 '+31/-4 (#6314 )')
- <img src="https://avatars.githubusercontent.com/u/21505?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Turadg Aleahmad](https://github.com/turadg '+23/-6 (#6265 )')
- <img src="https://avatars.githubusercontent.com/u/4273631?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [JohnTitor](https://github.com/kiritosan '+14/-14 (#6155 )')
- <img src="https://avatars.githubusercontent.com/u/39668736?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [rohit miryala](https://github.com/rohitmiryala '+22/-0 (#7250 )')
- <img src="https://avatars.githubusercontent.com/u/30316250?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Wilson Mun](https://github.com/wmundev '+20/-0 (#6053 )')
- <img src="https://avatars.githubusercontent.com/u/184506226?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [techcodie](https://github.com/techcodie '+7/-7 (#7236 )')
- <img src="https://avatars.githubusercontent.com/u/187598667?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ved Vadnere](https://github.com/Archis009 '+5/-6 (#7283 )')
- <img src="https://avatars.githubusercontent.com/u/115612815?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [svihpinc](https://github.com/svihpinc '+5/-3 (#6134 )')
- <img src="https://avatars.githubusercontent.com/u/123884782?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [SANDESH LENDVE](https://github.com/mrsandy1965 '+3/-3 (#7246 )')
- <img src="https://avatars.githubusercontent.com/u/12529395?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Lubos](https://github.com/mrlubos '+5/-1 (#7312 )')
- <img src="https://avatars.githubusercontent.com/u/709451?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jarred Sumner](https://github.com/Jarred-Sumner '+5/-1 (#5754 )')
- <img src="https://avatars.githubusercontent.com/u/17907922?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Adam Hines](https://github.com/thebanjomatic '+2/-1 (#5756 )')
- <img src="https://avatars.githubusercontent.com/u/177472603?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Subhan Kumar Rai](https://github.com/Subhan030 '+2/-1 (#7256 )')
- <img src="https://avatars.githubusercontent.com/u/6473925?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Joseph Frazier](https://github.com/josephfrazier '+1/-1 (#7311 )')
- <img src="https://avatars.githubusercontent.com/u/184906930?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [KT0803](https://github.com/KT0803 '+0/-2 (#7229 )')
- <img src="https://avatars.githubusercontent.com/u/6703955?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Albie](https://github.com/AlbertoSadoc '+1/-1 (#5560 )')
- <img src="https://avatars.githubusercontent.com/u/9452325?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jake Hayes](https://github.com/thejayhaykid '+1/-0 (#5999 )')
## [1.13.2](https://github.com/axios/axios/compare/v1.13.1...v1.13.2) (2025-11-04)
### Bug Fixes
- **http:** fix 'socket hang up' bug for keep-alive requests when using timeouts; ([#7206](https://github.com/axios/axios/issues/7206)) ([8d37233](https://github.com/axios/axios/commit/8d372335f5c50ecd01e8615f2468a9eb19703117))
- **http:** use default export for http2 module to support stubs; ([#7196](https://github.com/axios/axios/issues/7196)) ([0588880](https://github.com/axios/axios/commit/0588880ac7ddba7594ef179930493884b7e90bf5))
### Performance Improvements
- **http:** fix early loop exit; ([#7202](https://github.com/axios/axios/issues/7202)) ([12c314b](https://github.com/axios/axios/commit/12c314b603e7852a157e93e47edb626a471ba6c5))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+28/-9 (#7206 #7202 )')
- <img src="https://avatars.githubusercontent.com/u/1174718?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Kasper Isager Dalsgarð](https://github.com/kasperisager '+9/-9 (#7196 )')
## [1.13.1](https://github.com/axios/axios/compare/v1.13.0...v1.13.1) (2025-10-28)
### Bug Fixes
- **http:** fixed a regression that caused the data stream to be interrupted for responses with non-OK HTTP statuses; ([#7193](https://github.com/axios/axios/issues/7193)) ([bcd5581](https://github.com/axios/axios/commit/bcd5581d208cd372055afdcb2fd10b68ca40613c))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/128113546?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Anchal Singh](https://github.com/imanchalsingh '+220/-111 (#7173 )')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+18/-1 (#7193 )')
# [1.13.0](https://github.com/axios/axios/compare/v1.12.2...v1.13.0) (2025-10-27)
### Bug Fixes
- **fetch:** prevent TypeError when config.env is undefined ([#7155](https://github.com/axios/axios/issues/7155)) ([015faec](https://github.com/axios/axios/commit/015faeca9f26db76f9562760f04bb9f8229f4db1))
- resolve issue [#7131](https://github.com/axios/axios/issues/7131) (added spacing in mergeConfig.js) ([#7133](https://github.com/axios/axios/issues/7133)) ([9b9ec98](https://github.com/axios/axios/commit/9b9ec98548d93e9f2204deea10a5f1528bf3ce62))
### Features
- **http:** add HTTP2 support; ([#7150](https://github.com/axios/axios/issues/7150)) ([d676df7](https://github.com/axios/axios/commit/d676df772244726533ca320f42e967f5af056bac))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+794/-180 (#7186 #7150 #7039 )')
- <img src="https://avatars.githubusercontent.com/u/189505037?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Noritaka Kobayashi](https://github.com/noritaka1166 '+24/-509 (#7032 )')
- <img src="https://avatars.githubusercontent.com/u/195581631?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Aviraj2929](https://github.com/Aviraj2929 '+211/-93 (#7136 #7135 #7134 #7112 )')
- <img src="https://avatars.githubusercontent.com/u/181717941?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [prasoon patel](https://github.com/Prasoon52 '+167/-6 (#7099 )')
- <img src="https://avatars.githubusercontent.com/u/141911040?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Samyak Dandge](https://github.com/Samy-in '+134/-0 (#7171 )')
- <img src="https://avatars.githubusercontent.com/u/128113546?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Anchal Singh](https://github.com/imanchalsingh '+53/-56 (#7170 )')
- <img src="https://avatars.githubusercontent.com/u/146073621?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Rahul Kumar](https://github.com/jaiyankargupta '+28/-28 (#7073 )')
- <img src="https://avatars.githubusercontent.com/u/148716794?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Amit Verma](https://github.com/Amitverma0509 '+24/-13 (#7129 )')
- <img src="https://avatars.githubusercontent.com/u/141427581?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Abhishek3880](https://github.com/abhishekmaniy '+23/-4 (#7119 #7117 #7116 #7115 )')
- <img src="https://avatars.githubusercontent.com/u/91522146?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dhvani Maktuporia](https://github.com/Dhvani365 '+14/-5 (#7175 )')
- <img src="https://avatars.githubusercontent.com/u/41838423?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Usama Ayoub](https://github.com/sam3690 '+4/-4 (#7133 )')
- <img src="https://avatars.githubusercontent.com/u/79366821?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [ikuy1203](https://github.com/ikuy1203 '+3/-3 (#7166 )')
- <img src="https://avatars.githubusercontent.com/u/74639234?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Nikhil Simon Toppo](https://github.com/Kirito-Excalibur '+1/-1 (#7172 )')
- <img src="https://avatars.githubusercontent.com/u/200562195?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jane Wangari](https://github.com/Wangarijane '+1/-1 (#7155 )')
- <img src="https://avatars.githubusercontent.com/u/78318848?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Supakorn Ieamgomol](https://github.com/Supakornn '+1/-1 (#7065 )')
- <img src="https://avatars.githubusercontent.com/u/134518?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Kian-Meng Ang](https://github.com/kianmeng '+1/-1 (#7046 )')
- <img src="https://avatars.githubusercontent.com/u/13148112?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [UTSUMI Keiji](https://github.com/k-utsumi '+1/-1 (#7037 )')
## [1.12.2](https://github.com/axios/axios/compare/v1.12.1...v1.12.2) (2025-09-14)
### Bug Fixes
- **fetch:** use current global fetch instead of cached one when env fetch is not specified to keep MSW support; ([#7030](https://github.com/axios/axios/issues/7030)) ([cf78825](https://github.com/axios/axios/commit/cf78825e1229b60d1629ad0bbc8a752ff43c3f53))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+247/-16 (#7030 #7022 #7024 )')
- <img src="https://avatars.githubusercontent.com/u/189505037?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Noritaka Kobayashi](https://github.com/noritaka1166 '+2/-6 (#7028 #7029 )')
## [1.12.1](https://github.com/axios/axios/compare/v1.12.0...v1.12.1) (2025-09-12)
### Bug Fixes
- **types:** fixed env config types; ([#7020](https://github.com/axios/axios/issues/7020)) ([b5f26b7](https://github.com/axios/axios/commit/b5f26b75bdd9afa95016fb67d0cab15fc74cbf05))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+10/-4 (#7020 )')
# [1.12.0](https://github.com/axios/axios/compare/v1.11.0...v1.12.0) (2025-09-11)
### Bug Fixes
- adding build artifacts ([9ec86de](https://github.com/axios/axios/commit/9ec86de257bfa33856571036279169f385ed92bd))
- dont add dist on release ([a2edc36](https://github.com/axios/axios/commit/a2edc3606a4f775d868a67bb3461ff18ce7ecd11))
- **fetch-adapter:** set correct Content-Type for Node FormData ([#6998](https://github.com/axios/axios/issues/6998)) ([a9f47af](https://github.com/axios/axios/commit/a9f47afbf3224d2ca987dbd8188789c7ea853c5d))
- **node:** enforce maxContentLength for data: URLs ([#7011](https://github.com/axios/axios/issues/7011)) ([945435f](https://github.com/axios/axios/commit/945435fc51467303768202250debb8d4ae892593))
- package exports ([#5627](https://github.com/axios/axios/issues/5627)) ([aa78ac2](https://github.com/axios/axios/commit/aa78ac23fc9036163308c0f6bd2bb885e7af3f36))
- **params:** removing '[' and ']' from URL encode exclude characters ([#3316](https://github.com/axios/axios/issues/3316)) ([#5715](https://github.com/axios/axios/issues/5715)) ([6d84189](https://github.com/axios/axios/commit/6d84189349c43b1dcdd977b522610660cc4c7042))
- release pr run ([fd7f404](https://github.com/axios/axios/commit/fd7f404488b2c4f238c2fbe635b58026a634bfd2))
- **types:** change the type guard on isCancel ([#5595](https://github.com/axios/axios/issues/5595)) ([0dbb7fd](https://github.com/axios/axios/commit/0dbb7fd4f61dc568498cd13a681fa7f907d6ec7e))
### Features
- **adapter:** surface lowlevel network error details; attach original error via cause ([#6982](https://github.com/axios/axios/issues/6982)) ([78b290c](https://github.com/axios/axios/commit/78b290c57c978ed2ab420b90d97350231c9e5d74))
- **fetch:** add fetch, Request, Response env config variables for the adapter; ([#7003](https://github.com/axios/axios/issues/7003)) ([c959ff2](https://github.com/axios/axios/commit/c959ff29013a3bc90cde3ac7ea2d9a3f9c08974b))
- support reviver on JSON.parse ([#5926](https://github.com/axios/axios/issues/5926)) ([2a97634](https://github.com/axios/axios/commit/2a9763426e43d996fd60d01afe63fa6e1f5b4fca)), closes [#5924](https://github.com/axios/axios/issues/5924)
- **types:** extend AxiosResponse interface to include custom headers type ([#6782](https://github.com/axios/axios/issues/6782)) ([7960d34](https://github.com/axios/axios/commit/7960d34eded2de66ffd30b4687f8da0e46c4903e))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/22686401?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Willian Agostini](https://github.com/WillianAgostini '+132/-16760 (#7002 #5926 #6782 )')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+4263/-293 (#7006 #7003 )')
- <img src="https://avatars.githubusercontent.com/u/53833811?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [khani](https://github.com/mkhani01 '+111/-15 (#6982 )')
- <img src="https://avatars.githubusercontent.com/u/7712804?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ameer Assadi](https://github.com/AmeerAssadi '+123/-0 (#7011 )')
- <img src="https://avatars.githubusercontent.com/u/70265727?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Emiedonmokumo Dick-Boro](https://github.com/emiedonmokumo '+55/-35 (#6998 )')
- <img src="https://avatars.githubusercontent.com/u/47859767?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Zeroday BYTE](https://github.com/opsysdebug '+8/-8 (#6980 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jason Saayman](https://github.com/jasonsaayman '+7/-7 (#6985 #6985 )')
- <img src="https://avatars.githubusercontent.com/u/13010755?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [최예찬](https://github.com/HealGaren '+5/-7 (#5715 )')
- <img src="https://avatars.githubusercontent.com/u/7002604?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Gligor Kotushevski](https://github.com/gligorkot '+3/-1 (#5627 )')
- <img src="https://avatars.githubusercontent.com/u/15893?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Aleksandar Dimitrov](https://github.com/adimit '+2/-1 (#5595 )')
# [1.11.0](https://github.com/axios/axios/compare/v1.10.0...v1.11.0) (2025-07-22)
### Bug Fixes
- form-data npm package ([#6970](https://github.com/axios/axios/issues/6970)) ([e72c193](https://github.com/axios/axios/commit/e72c193722530db538b19e5ddaaa4544d226b253))
- prevent RangeError when using large Buffers ([#6961](https://github.com/axios/axios/issues/6961)) ([a2214ca](https://github.com/axios/axios/commit/a2214ca1bc60540baf2c80573cea3a0ff91ba9d1))
- **types:** resolve type discrepancies between ESM and CJS TypeScript declaration files ([#6956](https://github.com/axios/axios/issues/6956)) ([8517aa1](https://github.com/axios/axios/commit/8517aa16f8d082fc1d5309c642220fa736159110))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12534341?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [izzy goldman](https://github.com/izzygld '+186/-93 (#6970 )')
- <img src="https://avatars.githubusercontent.com/u/142807367?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Manish Sahani](https://github.com/manishsahanidev '+70/-0 (#6961 )')
- <img src="https://avatars.githubusercontent.com/u/189505037?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Noritaka Kobayashi](https://github.com/noritaka1166 '+12/-10 (#6938 #6939 )')
- <img src="https://avatars.githubusercontent.com/u/392612?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [James Nail](https://github.com/jrnail23 '+13/-2 (#6956 )')
- <img src="https://avatars.githubusercontent.com/u/163745239?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Tejaswi1305](https://github.com/Tejaswi1305 '+1/-1 (#6894 )')
# [1.10.0](https://github.com/axios/axios/compare/v1.9.0...v1.10.0) (2025-06-14)
### Bug Fixes
- **adapter:** pass fetchOptions to fetch function ([#6883](https://github.com/axios/axios/issues/6883)) ([0f50af8](https://github.com/axios/axios/commit/0f50af8e076b7fb403844789bd5e812dedcaf4ed))
- **form-data:** convert boolean values to strings in FormData serialization ([#6917](https://github.com/axios/axios/issues/6917)) ([5064b10](https://github.com/axios/axios/commit/5064b108de336ff34862650709761b8a96d26be0))
- **package:** add module entry point for React Native; ([#6933](https://github.com/axios/axios/issues/6933)) ([3d343b8](https://github.com/axios/axios/commit/3d343b86dc4fd0eea0987059c5af04327c7ae304))
### Features
- **types:** improved fetchOptions interface ([#6867](https://github.com/axios/axios/issues/6867)) ([63f1fce](https://github.com/axios/axios/commit/63f1fce233009f5db1abf2586c145825ac98c3d7))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+30/-19 (#6933 #6920 #6893 #6892 )')
- <img src="https://avatars.githubusercontent.com/u/189505037?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Noritaka Kobayashi](https://github.com/noritaka1166 '+2/-6 (#6922 #6923 )')
- <img src="https://avatars.githubusercontent.com/u/48370490?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dimitrios Lazanas](https://github.com/dimitry-lzs '+4/-0 (#6917 )')
- <img src="https://avatars.githubusercontent.com/u/71047946?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Adrian Knapp](https://github.com/AdrianKnapp '+2/-2 (#6867 )')
- <img src="https://avatars.githubusercontent.com/u/16129206?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Howie Zhao](https://github.com/howiezhao '+3/-1 (#6872 )')
- <img src="https://avatars.githubusercontent.com/u/6788611?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Uhyeon Park](https://github.com/warpdev '+1/-1 (#6883 )')
- <img src="https://avatars.githubusercontent.com/u/20028934?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Sampo Silvennoinen](https://github.com/stscoundrel '+1/-1 (#6913 )')
# [1.9.0](https://github.com/axios/axios/compare/v1.8.4...v1.9.0) (2025-04-24)
### Bug Fixes
- **core:** fix the Axios constructor implementation to treat the config argument as optional; ([#6881](https://github.com/axios/axios/issues/6881)) ([6c5d4cd](https://github.com/axios/axios/commit/6c5d4cd69286868059c5e52d45085cb9a894a983))
- **fetch:** fixed ERR_NETWORK mapping for Safari browsers; ([#6767](https://github.com/axios/axios/issues/6767)) ([dfe8411](https://github.com/axios/axios/commit/dfe8411c9a082c3d068bdd1f8d6e73054f387f45))
- **headers:** allow iterable objects to be a data source for the set method; ([#6873](https://github.com/axios/axios/issues/6873)) ([1b1f9cc](https://github.com/axios/axios/commit/1b1f9ccdc15f1ea745160ec9a5223de9db4673bc))
- **headers:** fix `getSetCookie` by using 'get' method for caseless access; ([#6874](https://github.com/axios/axios/issues/6874)) ([d4f7df4](https://github.com/axios/axios/commit/d4f7df4b304af8b373488fdf8e830793ff843eb9))
- **headers:** fixed support for setting multiple header values from an iterated source; ([#6885](https://github.com/axios/axios/issues/6885)) ([f7a3b5e](https://github.com/axios/axios/commit/f7a3b5e0f7e5e127b97defa92a132fbf1b55cf15))
- **http:** send minimal end multipart boundary ([#6661](https://github.com/axios/axios/issues/6661)) ([987d2e2](https://github.com/axios/axios/commit/987d2e2dd3b362757550f36eab875e60640b6ddc))
- **types:** fix autocomplete for adapter config ([#6855](https://github.com/axios/axios/issues/6855)) ([e61a893](https://github.com/axios/axios/commit/e61a8934d8f94dd429a2f309b48c67307c700df0))
### Features
- **AxiosHeaders:** add getSetCookie method to retrieve set-cookie headers values ([#5707](https://github.com/axios/axios/issues/5707)) ([80ea756](https://github.com/axios/axios/commit/80ea756e72bcf53110fa792f5d7ab76e8b11c996))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+200/-34 (#6890 #6889 #6888 #6885 #6881 #6767 #6874 #6873 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+26/-1 ()')
- <img src="https://avatars.githubusercontent.com/u/22686401?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Willian Agostini](https://github.com/WillianAgostini '+21/-0 (#5707 )')
- <img src="https://avatars.githubusercontent.com/u/2500247?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [George Cheng](https://github.com/Gerhut '+3/-3 (#5096 )')
- <img src="https://avatars.githubusercontent.com/u/30260221?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [FatahChan](https://github.com/FatahChan '+2/-2 (#6855 )')
- <img src="https://avatars.githubusercontent.com/u/49002?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ionuț G. Stan](https://github.com/igstan '+1/-1 (#6661 )')
## [1.8.4](https://github.com/axios/axios/compare/v1.8.3...v1.8.4) (2025-03-19)
### Bug Fixes
- **buildFullPath:** handle `allowAbsoluteUrls: false` without `baseURL` ([#6833](https://github.com/axios/axios/issues/6833)) ([f10c2e0](https://github.com/axios/axios/commit/f10c2e0de7fde0051f848609a29c2906d0caa1d9))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/8029107?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Marc Hassan](https://github.com/mhassan1 '+5/-1 (#6833 )')
## [1.8.3](https://github.com/axios/axios/compare/v1.8.2...v1.8.3) (2025-03-10)
### Bug Fixes
- add missing type for allowAbsoluteUrls ([#6818](https://github.com/axios/axios/issues/6818)) ([10fa70e](https://github.com/axios/axios/commit/10fa70ef14fe39558b15a179f0e82f5f5e5d11b2))
- **xhr/fetch:** pass `allowAbsoluteUrls` to `buildFullPath` in `xhr` and `fetch` adapters ([#6814](https://github.com/axios/axios/issues/6814)) ([ec159e5](https://github.com/axios/axios/commit/ec159e507bdf08c04ba1a10fe7710094e9e50ec9))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/3238291?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ashcon Partovi](https://github.com/Electroid '+6/-0 (#6811 )')
- <img src="https://avatars.githubusercontent.com/u/28559054?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [StefanBRas](https://github.com/StefanBRas '+4/-0 (#6818 )')
- <img src="https://avatars.githubusercontent.com/u/8029107?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Marc Hassan](https://github.com/mhassan1 '+2/-2 (#6814 )')
## [1.8.2](https://github.com/axios/axios/compare/v1.8.1...v1.8.2) (2025-03-07)
### Bug Fixes
- **http-adapter:** add allowAbsoluteUrls to path building ([#6810](https://github.com/axios/axios/issues/6810)) ([fb8eec2](https://github.com/axios/axios/commit/fb8eec214ce7744b5ca787f2c3b8339b2f54b00f))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/14166260?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Fasoro-Joseph Alexander](https://github.com/lexcorp16 '+1/-1 (#6810 )')
## [1.8.1](https://github.com/axios/axios/compare/v1.8.0...v1.8.1) (2025-02-26)
### Bug Fixes
- **utils:** move `generateString` to platform utils to avoid importing crypto module into client builds; ([#6789](https://github.com/axios/axios/issues/6789)) ([36a5a62](https://github.com/axios/axios/commit/36a5a620bec0b181451927f13ac85b9888b86cec))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+51/-47 (#6789 )')
# [1.8.0](https://github.com/axios/axios/compare/v1.7.9...v1.8.0) (2025-02-25)
### Bug Fixes
- **examples:** application crashed when navigating examples in browser ([#5938](https://github.com/axios/axios/issues/5938)) ([1260ded](https://github.com/axios/axios/commit/1260ded634ec101dd5ed05d3b70f8e8f899dba6c))
- missing word in SUPPORT_QUESTION.yml ([#6757](https://github.com/axios/axios/issues/6757)) ([1f890b1](https://github.com/axios/axios/commit/1f890b13f2c25a016f3c84ae78efb769f244133e))
- **utils:** replace getRandomValues with crypto module ([#6788](https://github.com/axios/axios/issues/6788)) ([23a25af](https://github.com/axios/axios/commit/23a25af0688d1db2c396deb09229d2271cc24f6c))
### Features
- Add config for ignoring absolute URLs ([#5902](https://github.com/axios/axios/issues/5902)) ([#6192](https://github.com/axios/axios/issues/6192)) ([32c7bcc](https://github.com/axios/axios/commit/32c7bcc0f233285ba27dec73a4b1e81fb7a219b3))
### Reverts
- Revert "chore: expose fromDataToStream to be consumable (#6731)" (#6732) ([1317261](https://github.com/axios/axios/commit/1317261125e9c419fe9f126867f64d28f9c1efda)), closes [#6731](https://github.com/axios/axios/issues/6731) [#6732](https://github.com/axios/axios/issues/6732)
### BREAKING CHANGES
- code relying on the above will now combine the URLs instead of prefer request URL
- feat: add config option for allowing absolute URLs
- fix: add default value for allowAbsoluteUrls in buildFullPath
- fix: typo in flow control when setting allowAbsoluteUrls
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/7661715?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Michael Toscano](https://github.com/GethosTheWalrus '+42/-8 (#6192 )')
- <img src="https://avatars.githubusercontent.com/u/22686401?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Willian Agostini](https://github.com/WillianAgostini '+26/-3 (#6788 #6777 )')
- <img src="https://avatars.githubusercontent.com/u/72578270?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Naron](https://github.com/naronchen '+27/-0 (#5901 )')
- <img src="https://avatars.githubusercontent.com/u/47430686?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [shravan || श्रvan](https://github.com/shravan20 '+7/-3 (#6116 )')
- <img src="https://avatars.githubusercontent.com/u/145078271?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Justin Dhillon](https://github.com/justindhillon '+0/-7 (#6312 )')
- <img src="https://avatars.githubusercontent.com/u/30925732?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [yionr](https://github.com/yionr '+5/-1 (#6129 )')
- <img src="https://avatars.githubusercontent.com/u/534166?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Shin&#x27;ya Ueoka](https://github.com/ueokande '+3/-3 (#5935 )')
- <img src="https://avatars.githubusercontent.com/u/33569?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dan Dascalescu](https://github.com/dandv '+3/-3 (#5908 #6757 )')
- <img src="https://avatars.githubusercontent.com/u/16476523?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Nitin Ramnani](https://github.com/NitinRamnani '+2/-2 (#5938 )')
- <img src="https://avatars.githubusercontent.com/u/152275799?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Shay Molcho](https://github.com/shaymolcho '+2/-2 (#6770 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+0/-3 (#6732 )')
- fancy45daddy
- <img src="https://avatars.githubusercontent.com/u/127725897?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Habip Akyol](https://github.com/habipakyol '+1/-1 (#6030 )')
- <img src="https://avatars.githubusercontent.com/u/54869395?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Bailey Lissington](https://github.com/llamington '+1/-1 (#6771 )')
- <img src="https://avatars.githubusercontent.com/u/14969290?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Bernardo da Eira Duarte](https://github.com/bernardoduarte '+1/-1 (#6480 )')
- <img src="https://avatars.githubusercontent.com/u/117800149?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Shivam Batham](https://github.com/Shivam-Batham '+1/-1 (#5949 )')
- <img src="https://avatars.githubusercontent.com/u/67861627?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Lipin Kariappa](https://github.com/lipinnnnn '+1/-1 (#5936 )')
## [1.7.9](https://github.com/axios/axios/compare/v1.7.8...v1.7.9) (2024-12-04)
### Reverts
- Revert "fix(types): export CJS types from ESM (#6218)" (#6729) ([c44d2f2](https://github.com/axios/axios/commit/c44d2f2316ad289b38997657248ba10de11deb6c)), closes [#6218](https://github.com/axios/axios/issues/6218) [#6729](https://github.com/axios/axios/issues/6729)
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+596/-108 (#6729 )')
## [1.7.8](https://github.com/axios/axios/compare/v1.7.7...v1.7.8) (2024-11-25)
### Bug Fixes
- allow passing a callback as paramsSerializer to buildURL ([#6680](https://github.com/axios/axios/issues/6680)) ([eac4619](https://github.com/axios/axios/commit/eac4619fe2e0926e876cd260ee21e3690381dbb5))
- **core:** fixed config merging bug ([#6668](https://github.com/axios/axios/issues/6668)) ([5d99fe4](https://github.com/axios/axios/commit/5d99fe4491202a6268c71e5dcc09192359d73cea))
- fixed width form to not shrink after 'Send Request' button is clicked ([#6644](https://github.com/axios/axios/issues/6644)) ([7ccd5fd](https://github.com/axios/axios/commit/7ccd5fd42402102d38712c32707bf055be72ab54))
- **http:** add support for File objects as payload in http adapter ([#6588](https://github.com/axios/axios/issues/6588)) ([#6605](https://github.com/axios/axios/issues/6605)) ([6841d8d](https://github.com/axios/axios/commit/6841d8d18ddc71cc1bd202ffcfddb3f95622eef3))
- **http:** fixed proxy-from-env module import ([#5222](https://github.com/axios/axios/issues/5222)) ([12b3295](https://github.com/axios/axios/commit/12b32957f1258aee94ef859809ed39f8f88f9dfa))
- **http:** use `globalThis.TextEncoder` when available ([#6634](https://github.com/axios/axios/issues/6634)) ([df956d1](https://github.com/axios/axios/commit/df956d18febc9100a563298dfdf0f102c3d15410))
- ios11 breaks when build ([#6608](https://github.com/axios/axios/issues/6608)) ([7638952](https://github.com/axios/axios/commit/763895270f7b50c7c780c3c9807ae8635de952cd))
- **types:** add missing types for mergeConfig function ([#6590](https://github.com/axios/axios/issues/6590)) ([00de614](https://github.com/axios/axios/commit/00de614cd07b7149af335e202aef0e076c254f49))
- **types:** export CJS types from ESM ([#6218](https://github.com/axios/axios/issues/6218)) ([c71811b](https://github.com/axios/axios/commit/c71811b00f2fcff558e4382ba913bdac4ad7200e))
- updated stream aborted error message to be more clear ([#6615](https://github.com/axios/axios/issues/6615)) ([cc3217a](https://github.com/axios/axios/commit/cc3217a612024d83a663722a56d7a98d8759c6d5))
- use URL API instead of DOM to fix a potential vulnerability warning; ([#6714](https://github.com/axios/axios/issues/6714)) ([0a8d6e1](https://github.com/axios/axios/commit/0a8d6e19da5b9899a2abafaaa06a75ee548597db))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/779047?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Remco Haszing](https://github.com/remcohaszing '+108/-596 (#6218 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+281/-19 (#6640 #6619 )')
- <img src="https://avatars.githubusercontent.com/u/140250471?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Aayush Yadav](https://github.com/aayushyadav020 '+124/-111 (#6617 )')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+12/-65 (#6714 )')
- <img src="https://avatars.githubusercontent.com/u/479715?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ell Bradshaw](https://github.com/cincodenada '+29/-0 (#6489 )')
- <img src="https://avatars.githubusercontent.com/u/60218780?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Amit Saini](https://github.com/amitsainii '+13/-3 (#5237 )')
- <img src="https://avatars.githubusercontent.com/u/19817867?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Tommaso Paulon](https://github.com/guuido '+14/-1 (#6680 )')
- <img src="https://avatars.githubusercontent.com/u/63336443?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Akki](https://github.com/Aakash-Rana '+5/-5 (#6668 )')
- <img src="https://avatars.githubusercontent.com/u/20028934?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Sampo Silvennoinen](https://github.com/stscoundrel '+3/-3 (#6633 )')
- <img src="https://avatars.githubusercontent.com/u/1174718?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Kasper Isager Dalsgarð](https://github.com/kasperisager '+2/-2 (#6634 )')
- <img src="https://avatars.githubusercontent.com/u/3709715?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Christian Clauss](https://github.com/cclauss '+4/-0 (#6683 )')
- <img src="https://avatars.githubusercontent.com/u/1639119?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Pavan Welihinda](https://github.com/pavan168 '+2/-2 (#5222 )')
- <img src="https://avatars.githubusercontent.com/u/5742900?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Taylor Flatt](https://github.com/taylorflatt '+2/-2 (#6615 )')
- <img src="https://avatars.githubusercontent.com/u/79452224?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Kenzo Wada](https://github.com/Kenzo-Wada '+2/-2 (#6608 )')
- <img src="https://avatars.githubusercontent.com/u/50064240?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ngole Lawson](https://github.com/echelonnought '+3/-0 (#6644 )')
- <img src="https://avatars.githubusercontent.com/u/1262198?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Haven](https://github.com/Baoyx007 '+3/-0 (#6590 )')
- <img src="https://avatars.githubusercontent.com/u/149003676?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Shrivali Dutt](https://github.com/shrivalidutt '+1/-1 (#6637 )')
- <img src="https://avatars.githubusercontent.com/u/1304290?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Henco Appel](https://github.com/hencoappel '+1/-1 (#6605 )')
## [1.7.7](https://github.com/axios/axios/compare/v1.7.6...v1.7.7) (2024-08-31)
### Bug Fixes
- **fetch:** fix stream handling in Safari by fallback to using a stream reader instead of an async iterator; ([#6584](https://github.com/axios/axios/issues/6584)) ([d198085](https://github.com/axios/axios/commit/d1980854fee1765cd02fa0787adf5d6e34dd9dcf))
- **http:** fixed support for IPv6 literal strings in url ([#5731](https://github.com/axios/axios/issues/5731)) ([364993f](https://github.com/axios/axios/commit/364993f0d8bc6e0e06f76b8a35d2d0a35cab054c))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/10539109?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Rishi556](https://github.com/Rishi556 '+39/-1 (#5731 )')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+27/-7 (#6584 )')
## [1.7.6](https://github.com/axios/axios/compare/v1.7.5...v1.7.6) (2024-08-30)
### Bug Fixes
- **fetch:** fix content length calculation for FormData payload; ([#6524](https://github.com/axios/axios/issues/6524)) ([085f568](https://github.com/axios/axios/commit/085f56861a83e9ac02c140ad9d68dac540dfeeaa))
- **fetch:** optimize signals composing logic; ([#6582](https://github.com/axios/axios/issues/6582)) ([df9889b](https://github.com/axios/axios/commit/df9889b83c2cc37e9e6189675a73ab70c60f031f))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+98/-46 (#6582 )')
- <img src="https://avatars.githubusercontent.com/u/3534453?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jacques Germishuys](https://github.com/jacquesg '+5/-1 (#6524 )')
- <img src="https://avatars.githubusercontent.com/u/53894505?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [kuroino721](https://github.com/kuroino721 '+3/-1 (#6575 )')
## [1.7.5](https://github.com/axios/axios/compare/v1.7.4...v1.7.5) (2024-08-23)
### Bug Fixes
- **adapter:** fix undefined reference to hasBrowserEnv ([#6572](https://github.com/axios/axios/issues/6572)) ([7004707](https://github.com/axios/axios/commit/7004707c4180b416341863bd86913fe4fc2f1df1))
- **core:** add the missed implementation of AxiosError#status property; ([#6573](https://github.com/axios/axios/issues/6573)) ([6700a8a](https://github.com/axios/axios/commit/6700a8adac06942205f6a7a21421ecb36c4e0852))
- **core:** fix `ReferenceError: navigator is not defined` for custom environments; ([#6567](https://github.com/axios/axios/issues/6567)) ([fed1a4b](https://github.com/axios/axios/commit/fed1a4b2d78ed4a588c84e09d32749ed01dc2794))
- **fetch:** fix credentials handling in Cloudflare workers ([#6533](https://github.com/axios/axios/issues/6533)) ([550d885](https://github.com/axios/axios/commit/550d885eb90fd156add7b93bbdc54d30d2f9a98d))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+187/-83 (#6573 #6567 #6566 #6564 #6563 #6557 #6556 #6555 #6554 #6552 )')
- <img src="https://avatars.githubusercontent.com/u/2495809?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Antonin Bas](https://github.com/antoninbas '+6/-6 (#6572 )')
- <img src="https://avatars.githubusercontent.com/u/5406212?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Hans Otto Wirtz](https://github.com/hansottowirtz '+4/-1 (#6533 )')
## [1.7.4](https://github.com/axios/axios/compare/v1.7.3...v1.7.4) (2024-08-13)
### Bug Fixes
- **sec:** CVE-2024-39338 ([#6539](https://github.com/axios/axios/issues/6539)) ([#6543](https://github.com/axios/axios/issues/6543)) ([6b6b605](https://github.com/axios/axios/commit/6b6b605eaf73852fb2dae033f1e786155959de3a))
- **sec:** disregard protocol-relative URL to remediate SSRF ([#6539](https://github.com/axios/axios/issues/6539)) ([07a661a](https://github.com/axios/axios/commit/07a661a2a6b9092c4aa640dcc7f724ec5e65bdda))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/31389480?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Lev Pachmanov](https://github.com/levpachmanov '+47/-11 (#6543 )')
- <img src="https://avatars.githubusercontent.com/u/41283691?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Đỗ Trọng Hải](https://github.com/hainenber '+49/-4 (#6539 )')
## [1.7.3](https://github.com/axios/axios/compare/v1.7.2...v1.7.3) (2024-08-01)
### Bug Fixes
- **adapter:** fix progress event emitting; ([#6518](https://github.com/axios/axios/issues/6518)) ([e3c76fc](https://github.com/axios/axios/commit/e3c76fc9bdd03aa4d98afaf211df943e2031453f))
- **fetch:** fix withCredentials request config ([#6505](https://github.com/axios/axios/issues/6505)) ([85d4d0e](https://github.com/axios/axios/commit/85d4d0ea0aae91082f04e303dec46510d1b4e787))
- **xhr:** return original config on errors from XHR adapter ([#6515](https://github.com/axios/axios/issues/6515)) ([8966ee7](https://github.com/axios/axios/commit/8966ee7ea62ecbd6cfb39a905939bcdab5cf6388))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+211/-159 (#6518 #6519 )')
- <img src="https://avatars.githubusercontent.com/u/10867286?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Valerii Sidorenko](https://github.com/ValeraS '+3/-3 (#6515 )')
- <img src="https://avatars.githubusercontent.com/u/8599535?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [prianYu](https://github.com/prianyu '+2/-2 (#6505 )')
## [1.7.2](https://github.com/axios/axios/compare/v1.7.1...v1.7.2) (2024-05-21)
### Bug Fixes
- **fetch:** enhance fetch API detection; ([#6413](https://github.com/axios/axios/issues/6413)) ([4f79aef](https://github.com/axios/axios/commit/4f79aef81b7c4644328365bfc33acf0a9ef595bc))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+3/-3 (#6413 )')
## [1.7.1](https://github.com/axios/axios/compare/v1.7.0...v1.7.1) (2024-05-20)
### Bug Fixes
- **fetch:** fixed ReferenceError issue when TextEncoder is not available in the environment; ([#6410](https://github.com/axios/axios/issues/6410)) ([733f15f](https://github.com/axios/axios/commit/733f15fe5bd2d67e1fadaee82e7913b70d45dc5e))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+14/-9 (#6410 )')
# [1.7.0](https://github.com/axios/axios/compare/v1.7.0-beta.2...v1.7.0) (2024-05-19)
### Features
- **adapter:** add fetch adapter; ([#6371](https://github.com/axios/axios/issues/6371)) ([a3ff99b](https://github.com/axios/axios/commit/a3ff99b59d8ec2ab5dd049e68c043617a4072e42))
### Bug Fixes
- **core/axios:** handle un-writable error stack ([#6362](https://github.com/axios/axios/issues/6362)) ([81e0455](https://github.com/axios/axios/commit/81e0455b7b57fbaf2be16a73ebe0e6591cc6d8f9))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+1015/-127 (#6371 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+30/-14 ()')
- <img src="https://avatars.githubusercontent.com/u/16711696?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Alexandre ABRIOUX](https://github.com/alexandre-abrioux '+56/-6 (#6362 )')
# [1.7.0-beta.2](https://github.com/axios/axios/compare/v1.7.0-beta.1...v1.7.0-beta.2) (2024-05-19)
### Bug Fixes
- **fetch:** capitalize HTTP method names; ([#6395](https://github.com/axios/axios/issues/6395)) ([ad3174a](https://github.com/axios/axios/commit/ad3174a3515c3c2573f4bcb94818d582826f3914))
- **fetch:** fix & optimize progress capturing for cases when the request data has a nullish value or zero data length ([#6400](https://github.com/axios/axios/issues/6400)) ([95a3e8e](https://github.com/axios/axios/commit/95a3e8e346cfd6a5548e171f2341df3235d0e26b))
- **fetch:** fix headers getting from a stream response; ([#6401](https://github.com/axios/axios/issues/6401)) ([870e0a7](https://github.com/axios/axios/commit/870e0a76f60d0094774a6a63fa606eec52a381af))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+99/-46 (#6405 #6404 #6401 #6400 #6395 )')
# [1.7.0-beta.1](https://github.com/axios/axios/compare/v1.7.0-beta.0...v1.7.0-beta.1) (2024-05-07)
### Bug Fixes
- **core/axios:** handle un-writable error stack ([#6362](https://github.com/axios/axios/issues/6362)) ([81e0455](https://github.com/axios/axios/commit/81e0455b7b57fbaf2be16a73ebe0e6591cc6d8f9))
- **fetch:** fix cases when ReadableStream or Response.body are not available; ([#6377](https://github.com/axios/axios/issues/6377)) ([d1d359d](https://github.com/axios/axios/commit/d1d359da347704e8b28d768e61515a3e96c5b072))
- **fetch:** treat fetch-related TypeError as an AxiosError.ERR_NETWORK error; ([#6380](https://github.com/axios/axios/issues/6380)) ([bb5f9a5](https://github.com/axios/axios/commit/bb5f9a5ab768452de9e166dc28d0ffc234245ef1))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/16711696?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Alexandre ABRIOUX](https://github.com/alexandre-abrioux '+56/-6 (#6362 )')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+42/-17 (#6380 #6377 )')
# [1.7.0-beta.0](https://github.com/axios/axios/compare/v1.6.8...v1.7.0-beta.0) (2024-04-28)
### Features
- **adapter:** add fetch adapter; ([#6371](https://github.com/axios/axios/issues/6371)) ([a3ff99b](https://github.com/axios/axios/commit/a3ff99b59d8ec2ab5dd049e68c043617a4072e42))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+1015/-127 (#6371 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+30/-14 ()')
## [1.6.8](https://github.com/axios/axios/compare/v1.6.7...v1.6.8) (2024-03-15)
### Bug Fixes
- **AxiosHeaders:** fix AxiosHeaders conversion to an object during config merging ([#6243](https://github.com/axios/axios/issues/6243)) ([2656612](https://github.com/axios/axios/commit/2656612bc10fe2757e9832b708ed773ab340b5cb))
- **import:** use named export for EventEmitter; ([7320430](https://github.com/axios/axios/commit/7320430aef2e1ba2b89488a0eaf42681165498b1))
- **vulnerability:** update follow-redirects to 1.15.6 ([#6300](https://github.com/axios/axios/issues/6300)) ([8786e0f](https://github.com/axios/axios/commit/8786e0ff55a8c68d4ca989801ad26df924042e27))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+4572/-3446 (#6238 )')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+30/-0 (#6231 )')
- <img src="https://avatars.githubusercontent.com/u/68230846?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Mitchell](https://github.com/Creaous '+9/-9 (#6300 )')
- <img src="https://avatars.githubusercontent.com/u/53797821?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Emmanuel](https://github.com/mannoeu '+2/-2 (#6196 )')
- <img src="https://avatars.githubusercontent.com/u/44109284?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Lucas Keller](https://github.com/ljkeller '+3/-0 (#6194 )')
- <img src="https://avatars.githubusercontent.com/u/72791488?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Aditya Mogili](https://github.com/ADITYA-176 '+1/-1 ()')
- <img src="https://avatars.githubusercontent.com/u/46135319?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Miroslav Petrov](https://github.com/petrovmiroslav '+1/-1 (#6243 )')
## [1.6.7](https://github.com/axios/axios/compare/v1.6.6...v1.6.7) (2024-01-25)
### Bug Fixes
- capture async stack only for rejections with native error objects; ([#6203](https://github.com/axios/axios/issues/6203)) ([1a08f90](https://github.com/axios/axios/commit/1a08f90f402336e4d00e9ee82f211c6adb1640b0))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+30/-26 (#6203 )')
- <img src="https://avatars.githubusercontent.com/u/73059627?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [zhoulixiang](https://github.com/zh-lx '+0/-3 (#6186 )')
## [1.6.6](https://github.com/axios/axios/compare/v1.6.5...v1.6.6) (2024-01-24)
### Bug Fixes
- fixed missed dispatchBeforeRedirect argument ([#5778](https://github.com/axios/axios/issues/5778)) ([a1938ff](https://github.com/axios/axios/commit/a1938ff073fcb0f89011f001dfbc1fa1dc995e39))
- wrap errors to improve async stack trace ([#5987](https://github.com/axios/axios/issues/5987)) ([123f354](https://github.com/axios/axios/commit/123f354b920f154a209ea99f76b7b2ef3d9ebbab))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/1186084?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ilya Priven](https://github.com/ikonst '+91/-8 (#5987 )')
- <img src="https://avatars.githubusercontent.com/u/1884246?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Zao Soula](https://github.com/zaosoula '+6/-6 (#5778 )')
## [1.6.5](https://github.com/axios/axios/compare/v1.6.4...v1.6.5) (2024-01-05)
### Bug Fixes
- **ci:** refactor notify action as a job of publish action; ([#6176](https://github.com/axios/axios/issues/6176)) ([0736f95](https://github.com/axios/axios/commit/0736f95ce8776366dc9ca569f49ba505feb6373c))
- **dns:** fixed lookup error handling; ([#6175](https://github.com/axios/axios/issues/6175)) ([f4f2b03](https://github.com/axios/axios/commit/f4f2b039dd38eb4829e8583caede4ed6d2dd59be))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+41/-6 (#6176 #6175 )')
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+6/-1 ()')
## [1.6.4](https://github.com/axios/axios/compare/v1.6.3...v1.6.4) (2024-01-03)
### Bug Fixes
- **security:** fixed formToJSON prototype pollution vulnerability; ([#6167](https://github.com/axios/axios/issues/6167)) ([3c0c11c](https://github.com/axios/axios/commit/3c0c11cade045c4412c242b5727308cff9897a0e))
- **security:** fixed security vulnerability in follow-redirects ([#6163](https://github.com/axios/axios/issues/6163)) ([75af1cd](https://github.com/axios/axios/commit/75af1cdff5b3a6ca3766d3d3afbc3115bb0811b8))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+34/-6 ()')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+34/-3 (#6172 #6167 )')
- <img src="https://avatars.githubusercontent.com/u/1402060?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Guy Nesher](https://github.com/gnesher '+10/-10 (#6163 )')
## [1.6.3](https://github.com/axios/axios/compare/v1.6.2...v1.6.3) (2023-12-26)
### Bug Fixes
- Regular Expression Denial of Service (ReDoS) ([#6132](https://github.com/axios/axios/issues/6132)) ([5e7ad38](https://github.com/axios/axios/commit/5e7ad38fb0f819fceb19fb2ee5d5d38f56aa837d))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/4814473?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jay](https://github.com/jasonsaayman '+15/-6 (#6145 )')
- <img src="https://avatars.githubusercontent.com/u/22686401?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Willian Agostini](https://github.com/WillianAgostini '+17/-2 (#6132 )')
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+3/-0 (#6084 )')
## [1.6.2](https://github.com/axios/axios/compare/v1.6.1...v1.6.2) (2023-11-14)
### Features
- **withXSRFToken:** added withXSRFToken option as a workaround to achieve the old `withCredentials` behavior; ([#6046](https://github.com/axios/axios/issues/6046)) ([cff9967](https://github.com/axios/axios/commit/cff996779b272a5e94c2b52f5503ccf668bc42dc))
### PRs
- feat(withXSRFToken): added withXSRFToken option as a workaround to achieve the old &#x60;withCredentials&#x60; behavior; ( [#6046](https://api.github.com/repos/axios/axios/pulls/6046) )
```
📢 This PR added &#x27;withXSRFToken&#x27; option as a replacement for old withCredentials behaviour.
You should now use withXSRFToken along with withCredential to get the old behavior.
This functionality is considered as a fix.
```
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+271/-146 (#6081 #6080 #6079 #6078 #6046 #6064 #6063 )')
- <img src="https://avatars.githubusercontent.com/u/79681367?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Ng Choon Khon (CK)](https://github.com/ckng0221 '+4/-4 (#6073 )')
- <img src="https://avatars.githubusercontent.com/u/9162827?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Muhammad Noman](https://github.com/mnomanmemon '+2/-2 (#6048 )')
## [1.6.1](https://github.com/axios/axios/compare/v1.6.0...v1.6.1) (2023-11-08)
### Bug Fixes
- **formdata:** fixed content-type header normalization for non-standard browser environments; ([#6056](https://github.com/axios/axios/issues/6056)) ([dd465ab](https://github.com/axios/axios/commit/dd465ab22bbfa262c6567be6574bf46a057d5288))
- **platform:** fixed emulated browser detection in node.js environment; ([#6055](https://github.com/axios/axios/issues/6055)) ([3dc8369](https://github.com/axios/axios/commit/3dc8369e505e32a4e12c22f154c55fd63ac67fbb))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+432/-65 (#6059 #6056 #6055 )')
- <img src="https://avatars.githubusercontent.com/u/3982806?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Fabian Meyer](https://github.com/meyfa '+5/-2 (#5835 )')
### PRs
- feat(withXSRFToken): added withXSRFToken option as a workaround to achieve the old &#x60;withCredentials&#x60; behavior; ( [#6046](https://api.github.com/repos/axios/axios/pulls/6046) )
```
📢 This PR added &#x27;withXSRFToken&#x27; option as a replacement for old withCredentials behaviour.
You should now use withXSRFToken along with withCredential to get the old behavior.
This functionality is considered as a fix.
```
# [1.6.0](https://github.com/axios/axios/compare/v1.5.1...v1.6.0) (2023-10-26)
### Bug Fixes
- **CSRF:** fixed CSRF vulnerability CVE-2023-45857 ([#6028](https://github.com/axios/axios/issues/6028)) ([96ee232](https://github.com/axios/axios/commit/96ee232bd3ee4de2e657333d4d2191cd389e14d0))
- **dns:** fixed lookup function decorator to work properly in node v20; ([#6011](https://github.com/axios/axios/issues/6011)) ([5aaff53](https://github.com/axios/axios/commit/5aaff532a6b820bb9ab6a8cd0f77131b47e2adb8))
- **types:** fix AxiosHeaders types; ([#5931](https://github.com/axios/axios/issues/5931)) ([a1c8ad0](https://github.com/axios/axios/commit/a1c8ad008b3c13d53e135bbd0862587fb9d3fc09))
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+449/-114 (#6032 #6021 #6011 #5932 #5931 )')
- <img src="https://avatars.githubusercontent.com/u/63700910?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Valentin Panov](https://github.com/valentin-panov '+4/-4 (#6028 )')
- <img src="https://avatars.githubusercontent.com/u/76877078?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Rinku Chaudhari](https://github.com/therealrinku '+1/-1 (#5889 )')
## [1.5.1](https://github.com/axios/axios/compare/v1.5.0...v1.5.1) (2023-09-26)
### Bug Fixes
- **adapters:** improved adapters loading logic to have clear error messages; ([#5919](https://github.com/axios/axios/issues/5919)) ([e410779](https://github.com/axios/axios/commit/e4107797a7a1376f6209fbecfbbce73d3faa7859))
- **formdata:** fixed automatic addition of the `Content-Type` header for FormData in non-browser environments; ([#5917](https://github.com/axios/axios/issues/5917)) ([bc9af51](https://github.com/axios/axios/commit/bc9af51b1886d1b3529617702f2a21a6c0ed5d92))
- **headers:** allow `content-encoding` header to handle case-insensitive values ([#5890](https://github.com/axios/axios/issues/5890)) ([#5892](https://github.com/axios/axios/issues/5892)) ([4c89f25](https://github.com/axios/axios/commit/4c89f25196525e90a6e75eda9cb31ae0a2e18acd))
- **types:** removed duplicated code ([9e62056](https://github.com/axios/axios/commit/9e6205630e1c9cf863adf141c0edb9e6d8d4b149))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+89/-18 (#5919 #5917 )')
- <img src="https://avatars.githubusercontent.com/u/110460234?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [David Dallas](https://github.com/DavidJDallas '+11/-5 ()')
- <img src="https://avatars.githubusercontent.com/u/71556073?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Sean Sattler](https://github.com/fb-sean '+2/-8 ()')
- <img src="https://avatars.githubusercontent.com/u/4294069?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Mustafa Ateş Uzun](https://github.com/0o001 '+4/-4 ()')
- <img src="https://avatars.githubusercontent.com/u/132928043?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Przemyslaw Motacki](https://github.com/sfc-gh-pmotacki '+2/-1 (#5892 )')
- <img src="https://avatars.githubusercontent.com/u/5492927?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Michael Di Prisco](https://github.com/Cadienvan '+1/-1 ()')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
# [1.5.0](https://github.com/axios/axios/compare/v1.4.0...v1.5.0) (2023-08-26)
### Bug Fixes
- **adapter:** make adapter loading error more clear by using platform-specific adapters explicitly ([#5837](https://github.com/axios/axios/issues/5837)) ([9a414bb](https://github.com/axios/axios/commit/9a414bb6c81796a95c6c7fe668637825458e8b6d))
- **dns:** fixed `cacheable-lookup` integration; ([#5836](https://github.com/axios/axios/issues/5836)) ([b3e327d](https://github.com/axios/axios/commit/b3e327dcc9277bdce34c7ef57beedf644b00d628))
- **headers:** added support for setting header names that overlap with class methods; ([#5831](https://github.com/axios/axios/issues/5831)) ([d8b4ca0](https://github.com/axios/axios/commit/d8b4ca0ea5f2f05efa4edfe1e7684593f9f68273))
- **headers:** fixed common Content-Type header merging; ([#5832](https://github.com/axios/axios/issues/5832)) ([8fda276](https://github.com/axios/axios/commit/8fda2766b1e6bcb72c3fabc146223083ef13ce17))
### Features
- export getAdapter function ([#5324](https://github.com/axios/axios/issues/5324)) ([ca73eb8](https://github.com/axios/axios/commit/ca73eb878df0ae2dace81fe3a7f1fb5986231bf1))
- **export:** export adapters without `unsafe` prefix ([#5839](https://github.com/axios/axios/issues/5839)) ([1601f4a](https://github.com/axios/axios/commit/1601f4a27a81ab47fea228f1e244b2c4e3ce28bf))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+66/-29 (#5839 #5837 #5836 #5832 #5831 )')
- <img src="https://avatars.githubusercontent.com/u/102841186?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [夜葬](https://github.com/geekact '+42/-0 (#5324 )')
- <img src="https://avatars.githubusercontent.com/u/65978976?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Jonathan Budiman](https://github.com/JBudiman00 '+30/-0 (#5788 )')
- <img src="https://avatars.githubusercontent.com/u/5492927?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Michael Di Prisco](https://github.com/Cadienvan '+3/-5 (#5791 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
# [1.4.0](https://github.com/axios/axios/compare/v1.3.6...v1.4.0) (2023-04-27)
### Bug Fixes
- **formdata:** add `multipart/form-data` content type for FormData payload on custom client environments; ([#5678](https://github.com/axios/axios/issues/5678)) ([bbb61e7](https://github.com/axios/axios/commit/bbb61e70cb1185adfb1cbbb86eaf6652c48d89d1))
- **package:** export package internals with unsafe path prefix; ([#5677](https://github.com/axios/axios/issues/5677)) ([df38c94](https://github.com/axios/axios/commit/df38c949f26414d88ba29ec1e353c4d4f97eaf09))
### Features
- **dns:** added support for a custom lookup function; ([#5339](https://github.com/axios/axios/issues/5339)) ([2701911](https://github.com/axios/axios/commit/2701911260a1faa5cc5e1afe437121b330a3b7bb))
- **types:** export `AxiosHeaderValue` type. ([#5525](https://github.com/axios/axios/issues/5525)) ([726f1c8](https://github.com/axios/axios/commit/726f1c8e00cffa0461a8813a9bdcb8f8b9d762cf))
### Performance Improvements
- **merge-config:** optimize mergeConfig performance by avoiding duplicate key visits; ([#5679](https://github.com/axios/axios/issues/5679)) ([e6f7053](https://github.com/axios/axios/commit/e6f7053bf1a3e87cf1f9da8677e12e3fe829d68e))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+151/-16 (#5684 #5339 #5679 #5678 #5677 )')
- <img src="https://avatars.githubusercontent.com/u/47537704?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Arthur Fiorette](https://github.com/arthurfiorette '+19/-19 (#5525 )')
- <img src="https://avatars.githubusercontent.com/u/43876655?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [PIYUSH NEGI](https://github.com/npiyush97 '+2/-18 (#5670 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.3.6](https://github.com/axios/axios/compare/v1.3.5...v1.3.6) (2023-04-19)
### Bug Fixes
- **types:** added transport to RawAxiosRequestConfig ([#5445](https://github.com/axios/axios/issues/5445)) ([6f360a2](https://github.com/axios/axios/commit/6f360a2531d8d70363fd9becef6a45a323f170e2))
- **utils:** make isFormData detection logic stricter to avoid unnecessary calling of the `toString` method on the target; ([#5661](https://github.com/axios/axios/issues/5661)) ([aa372f7](https://github.com/axios/axios/commit/aa372f7306295dfd1100c1c2c77ce95c95808e76))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+48/-10 (#5665 #5661 #5663 )')
- <img src="https://avatars.githubusercontent.com/u/5492927?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Michael Di Prisco](https://github.com/Cadienvan '+2/-0 (#5445 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.3.5](https://github.com/axios/axios/compare/v1.3.4...v1.3.5) (2023-04-05)
### Bug Fixes
- **headers:** fixed isValidHeaderName to support full list of allowed characters; ([#5584](https://github.com/axios/axios/issues/5584)) ([e7decef](https://github.com/axios/axios/commit/e7decef6a99f4627e27ed9ea5b00ce8e201c3841))
- **params:** re-added the ability to set the function as `paramsSerializer` config; ([#5633](https://github.com/axios/axios/issues/5633)) ([a56c866](https://github.com/axios/axios/commit/a56c8661209d5ce5a645a05f294a0e08a6c1f6b3))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+28/-10 (#5633 #5584 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.3.4](https://github.com/axios/axios/compare/v1.3.3...v1.3.4) (2023-02-22)
### Bug Fixes
- **blob:** added a check to make sure the Blob class is available in the browser's global scope; ([#5548](https://github.com/axios/axios/issues/5548)) ([3772c8f](https://github.com/axios/axios/commit/3772c8fe74112a56e3e9551f894d899bc3a9443a))
- **http:** fixed regression bug when handling synchronous errors inside the adapter; ([#5564](https://github.com/axios/axios/issues/5564)) ([a3b246c](https://github.com/axios/axios/commit/a3b246c9de5c3bc4b5a742e15add55b375479451))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+38/-26 (#5564 )')
- <img src="https://avatars.githubusercontent.com/u/19550000?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [lcysgsg](https://github.com/lcysgsg '+4/-0 (#5548 )')
- <img src="https://avatars.githubusercontent.com/u/5492927?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Michael Di Prisco](https://github.com/Cadienvan '+3/-0 (#5444 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.3.3](https://github.com/axios/axios/compare/v1.3.2...v1.3.3) (2023-02-13)
### Bug Fixes
- **formdata:** added a check to make sure the FormData class is available in the browser's global scope; ([#5545](https://github.com/axios/axios/issues/5545)) ([a6dfa72](https://github.com/axios/axios/commit/a6dfa72010db5ad52db8bd13c0f98e537e8fd05d))
- **formdata:** fixed setting NaN as Content-Length for form payload in some cases; ([#5535](https://github.com/axios/axios/issues/5535)) ([c19f7bf](https://github.com/axios/axios/commit/c19f7bf770f90ae8307f4ea3104f227056912da1))
- **headers:** fixed the filtering logic of the clear method; ([#5542](https://github.com/axios/axios/issues/5542)) ([ea87ebf](https://github.com/axios/axios/commit/ea87ebfe6d1699af072b9e7cd40faf8f14b0ab93))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+11/-7 (#5545 #5535 #5542 )')
- <img src="https://avatars.githubusercontent.com/u/19842213?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [陈若枫](https://github.com/ruofee '+2/-2 (#5467 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.3.2](https://github.com/axios/axios/compare/v1.3.1...v1.3.2) (2023-02-03)
### Bug Fixes
- **http:** treat http://localhost as base URL for relative paths to avoid `ERR_INVALID_URL` error; ([#5528](https://github.com/axios/axios/issues/5528)) ([128d56f](https://github.com/axios/axios/commit/128d56f4a0fb8f5f2ed6e0dd80bc9225fee9538c))
- **http:** use explicit import instead of TextEncoder global; ([#5530](https://github.com/axios/axios/issues/5530)) ([6b3c305](https://github.com/axios/axios/commit/6b3c305fc40c56428e0afabedc6f4d29c2830f6f))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+2/-1 (#5530 #5528 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.3.1](https://github.com/axios/axios/compare/v1.3.0...v1.3.1) (2023-02-01)
### Bug Fixes
- **formdata:** add hotfix to use the asynchronous API to compute the content-length header value; ([#5521](https://github.com/axios/axios/issues/5521)) ([96d336f](https://github.com/axios/axios/commit/96d336f527619f21da012fe1f117eeb53e5a2120))
- **serializer:** fixed serialization of array-like objects; ([#5518](https://github.com/axios/axios/issues/5518)) ([08104c0](https://github.com/axios/axios/commit/08104c028c0f9353897b1b6691d74c440fd0c32d))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+27/-8 (#5521 #5518 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
# [1.3.0](https://github.com/axios/axios/compare/v1.2.6...v1.3.0) (2023-01-31)
### Bug Fixes
- **headers:** fixed & optimized clear method; ([#5507](https://github.com/axios/axios/issues/5507)) ([9915635](https://github.com/axios/axios/commit/9915635c69d0ab70daca5738488421f67ca60959))
- **http:** add zlib headers if missing ([#5497](https://github.com/axios/axios/issues/5497)) ([65e8d1e](https://github.com/axios/axios/commit/65e8d1e28ce829f47a837e45129730e541950d3c))
### Features
- **fomdata:** added support for spec-compliant FormData & Blob types; ([#5316](https://github.com/axios/axios/issues/5316)) ([6ac574e](https://github.com/axios/axios/commit/6ac574e00a06731288347acea1e8246091196953))
### Contributors to this release
- <img src="https://avatars.githubusercontent.com/u/12586868?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+352/-67 (#5514 #5512 #5510 #5509 #5508 #5316 #5507 )')
- <img src="https://avatars.githubusercontent.com/u/35015993?v&#x3D;4&amp;s&#x3D;18" alt="avatar" width="18"/> [ItsNotGoodName](https://github.com/ItsNotGoodName '+43/-2 (#5497 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.2.6](https://github.com/axios/axios/compare/v1.2.5...v1.2.6) (2023-01-28)
### Bug Fixes
- **headers:** added missed Authorization accessor; ([#5502](https://github.com/axios/axios/issues/5502)) ([342c0ba](https://github.com/axios/axios/commit/342c0ba9a16ea50f5ed7d2366c5c1a2c877e3f26))
- **types:** fixed `CommonRequestHeadersList` & `CommonResponseHeadersList` types to be private in commonJS; ([#5503](https://github.com/axios/axios/issues/5503)) ([5a3d0a3](https://github.com/axios/axios/commit/5a3d0a3234d77361a1bc7cedee2da1e11df08e2c))
### Contributors to this release
- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+24/-9 (#5503 #5502 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.2.5](https://github.com/axios/axios/compare/v1.2.4...v1.2.5) (2023-01-26)
### Bug Fixes
- **types:** fixed AxiosHeaders to handle spread syntax by making all methods non-enumerable; ([#5499](https://github.com/axios/axios/issues/5499)) ([580f1e8](https://github.com/axios/axios/commit/580f1e8033a61baa38149d59fd16019de3932c22))
### Contributors to this release
- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+82/-54 (#5499 )')
- ![avatar](https://avatars.githubusercontent.com/u/20516159?v=4&s=16) [Elliot Ford](https://github.com/EFord36 '+1/-1 (#5462 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.2.4](https://github.com/axios/axios/compare/v1.2.3...v1.2.4) (2023-01-22)
### Bug Fixes
- **types:** renamed `RawAxiosRequestConfig` back to `AxiosRequestConfig`; ([#5486](https://github.com/axios/axios/issues/5486)) ([2a71f49](https://github.com/axios/axios/commit/2a71f49bc6c68495fa419003a3107ed8bd703ad0))
- **types:** fix `AxiosRequestConfig` generic; ([#5478](https://github.com/axios/axios/issues/5478)) ([9bce81b](https://github.com/axios/axios/commit/186ea062da8b7d578ae78b1a5c220986b9bce81b))
### Contributors to this release
- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+242/-108 (#5486 #5482 )')
- ![avatar](https://avatars.githubusercontent.com/u/9430821?v=4&s=16) [Daniel Hillmann](https://github.com/hilleer '+1/-1 (#5478 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.2.3](https://github.com/axios/axios/compare/1.2.2...1.2.3) (2023-01-10)
### Bug Fixes
- **types:** fixed AxiosRequestConfig header interface by refactoring it to RawAxiosRequestConfig; ([#5420](https://github.com/axios/axios/issues/5420)) ([0811963](https://github.com/axios/axios/commit/08119634a22f1d5b19f5c9ea0adccb6d3eebc3bc))
### Contributors to this release
- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS '+938/-442 (#5456 #5455 #5453 #5451 #5449 #5447 #5446 #5443 #5442 #5439 #5420 )')
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.2.2] - 2022-12-29
### Fixed
- fix(ci): fix release script inputs [#5392](https://github.com/axios/axios/pull/5392)
- fix(ci): prerelease scipts [#5377](https://github.com/axios/axios/pull/5377)
- fix(ci): release scripts [#5376](https://github.com/axios/axios/pull/5376)
- fix(ci): typescript tests [#5375](https://github.com/axios/axios/pull/5375)
- fix: Brotli decompression [#5353](https://github.com/axios/axios/pull/5353)
- fix: add missing HttpStatusCode [#5345](https://github.com/axios/axios/pull/5345)
### Chores
- chore(ci): set conventional-changelog header config [#5406](https://github.com/axios/axios/pull/5406)
- chore(ci): fix automatic contributors resolving [#5403](https://github.com/axios/axios/pull/5403)
- chore(ci): improved logging for the contributors list generator [#5398](https://github.com/axios/axios/pull/5398)
- chore(ci): fix release action [#5397](https://github.com/axios/axios/pull/5397)
- chore(ci): fix version bump script by adding bump argument for target version [#5393](https://github.com/axios/axios/pull/5393)
- chore(deps): bump decode-uri-component from 0.2.0 to 0.2.2 [#5342](https://github.com/axios/axios/pull/5342)
- chore(ci): GitHub Actions Release script [#5384](https://github.com/axios/axios/pull/5384)
- chore(ci): release scripts [#5364](https://github.com/axios/axios/pull/5364)
### Contributors to this release
- ![avatar](https://avatars.githubusercontent.com/u/12586868?v=4&s=16) [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
- ![avatar](https://avatars.githubusercontent.com/u/1652293?v=4&s=16) [Winnie](https://github.com/winniehell)
## [1.2.1] - 2022-12-05
### Changed
- feat(exports): export mergeConfig [#5151](https://github.com/axios/axios/pull/5151)
### Fixed
- fix(CancelledError): include config [#4922](https://github.com/axios/axios/pull/4922)
- fix(general): removing multiple/trailing/leading whitespace [#5022](https://github.com/axios/axios/pull/5022)
- fix(headers): decompression for responses without Content-Length header [#5306](https://github.com/axios/axios/pull/5306)
- fix(webWorker): exception to sending form data in web worker [#5139](https://github.com/axios/axios/pull/5139)
### Refactors
- refactor(types): AxiosProgressEvent.event type to any [#5308](https://github.com/axios/axios/pull/5308)
- refactor(types): add missing types for static AxiosError.from method [#4956](https://github.com/axios/axios/pull/4956)
### Chores
- chore(docs): remove README link to non-existent upgrade guide [#5307](https://github.com/axios/axios/pull/5307)
- chore(docs): typo in issue template name [#5159](https://github.com/axios/axios/pull/5159)
### Contributors to this release
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
- [Zachary Lysobey](https://github.com/zachlysobey)
- [Kevin Ennis](https://github.com/kevincennis)
- [Philipp Loose](https://github.com/phloose)
- [secondl1ght](https://github.com/secondl1ght)
- [wenzheng](https://github.com/0x30)
- [Ivan Barsukov](https://github.com/ovarn)
- [Arthur Fiorette](https://github.com/arthurfiorette)
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.2.0] - 2022-11-10
### Changed
- changed: refactored module exports [#5162](https://github.com/axios/axios/pull/5162)
- change: re-added support for loading Axios with require('axios').default [#5225](https://github.com/axios/axios/pull/5225)
### Fixed
- fix: improve AxiosHeaders class [#5224](https://github.com/axios/axios/pull/5224)
- fix: TypeScript type definitions for commonjs [#5196](https://github.com/axios/axios/pull/5196)
- fix: type definition of use method on AxiosInterceptorManager to match the README [#5071](https://github.com/axios/axios/pull/5071)
- fix: \_\_dirname is not defined in the sandbox [#5269](https://github.com/axios/axios/pull/5269)
- fix: AxiosError.toJSON method to avoid circular references [#5247](https://github.com/axios/axios/pull/5247)
- fix: Z_BUF_ERROR when content-encoding is set but the response body is empty [#5250](https://github.com/axios/axios/pull/5250)
### Refactors
- refactor: allowing adapters to be loaded by name [#5277](https://github.com/axios/axios/pull/5277)
### Chores
- chore: force CI restart [#5243](https://github.com/axios/axios/pull/5243)
- chore: update ECOSYSTEM.md [#5077](https://github.com/axios/axios/pull/5077)
- chore: update get/index.html [#5116](https://github.com/axios/axios/pull/5116)
- chore: update Sandbox UI/UX [#5205](https://github.com/axios/axios/pull/5205)
- chore:(actions): remove git credentials after checkout [#5235](https://github.com/axios/axios/pull/5235)
- chore(actions): bump actions/dependency-review-action from 2 to 3 [#5266](https://github.com/axios/axios/pull/5266)
- chore(packages): bump loader-utils from 1.4.1 to 1.4.2 [#5295](https://github.com/axios/axios/pull/5295)
- chore(packages): bump engine.io from 6.2.0 to 6.2.1 [#5294](https://github.com/axios/axios/pull/5294)
- chore(packages): bump socket.io-parser from 4.0.4 to 4.0.5 [#5241](https://github.com/axios/axios/pull/5241)
- chore(packages): bump loader-utils from 1.4.0 to 1.4.1 [#5245](https://github.com/axios/axios/pull/5245)
- chore(docs): update Resources links in README [#5119](https://github.com/axios/axios/pull/5119)
- chore(docs): update the link for JSON url [#5265](https://github.com/axios/axios/pull/5265)
- chore(docs): fix broken links [#5218](https://github.com/axios/axios/pull/5218)
- chore(docs): update and rename UPGRADE_GUIDE.md to MIGRATION_GUIDE.md [#5170](https://github.com/axios/axios/pull/5170)
- chore(docs): typo fix line #856 and #920 [#5194](https://github.com/axios/axios/pull/5194)
- chore(docs): typo fix #800 [#5193](https://github.com/axios/axios/pull/5193)
- chore(docs): fix typos [#5184](https://github.com/axios/axios/pull/5184)
- chore(docs): fix punctuation in README.md [#5197](https://github.com/axios/axios/pull/5197)
- chore(docs): update readme in the Handling Errors section - issue reference #5260 [#5261](https://github.com/axios/axios/pull/5261)
- chore: remove \b from filename [#5207](https://github.com/axios/axios/pull/5207)
- chore(docs): update CHANGELOG.md [#5137](https://github.com/axios/axios/pull/5137)
- chore: add sideEffects false to package.json [#5025](https://github.com/axios/axios/pull/5025)
### Contributors to this release
- [Maddy Miller](https://github.com/me4502)
- [Amit Saini](https://github.com/amitsainii)
- [ecyrbe](https://github.com/ecyrbe)
- [Ikko Ashimine](https://github.com/eltociear)
- [Geeth Gunnampalli](https://github.com/thetechie7)
- [Shreem Asati](https://github.com/shreem-123)
- [Frieder Bluemle](https://github.com/friederbluemle)
- [윤세영](https://github.com/yunseyeong)
- [Claudio Busatto](https://github.com/cjcbusatto)
- [Remco Haszing](https://github.com/remcohaszing)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
- [Csaba Maulis](https://github.com/om4csaba)
- [MoPaMo](https://github.com/MoPaMo)
- [Daniel Fjeldstad](https://github.com/w3bdesign)
- [Adrien Brunet](https://github.com/adrien-may)
- [Frazer Smith](https://github.com/Fdawgs)
- [HaiTao](https://github.com/836334258)
- [AZM](https://github.com/aziyatali)
- [relbns](https://github.com/relbns)
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.1.3] - 2022-10-15
### Added
- Added custom params serializer support [#5113](https://github.com/axios/axios/pull/5113)
### Fixed
- Fixed top-level export to keep them in-line with static properties [#5109](https://github.com/axios/axios/pull/5109)
- Stopped including null values to query string. [#5108](https://github.com/axios/axios/pull/5108)
- Restored proxy config backwards compatibility with 0.x [#5097](https://github.com/axios/axios/pull/5097)
- Added back AxiosHeaders in AxiosHeaderValue [#5103](https://github.com/axios/axios/pull/5103)
- Pin CDN install instructions to a specific version [#5060](https://github.com/axios/axios/pull/5060)
- Handling of array values fixed for AxiosHeaders [#5085](https://github.com/axios/axios/pull/5085)
### Chores
- docs: match badge style, add link to them [#5046](https://github.com/axios/axios/pull/5046)
- chore: fixing comments typo [#5054](https://github.com/axios/axios/pull/5054)
- chore: update issue template [#5061](https://github.com/axios/axios/pull/5061)
- chore: added progress capturing section to the docs; [#5084](https://github.com/axios/axios/pull/5084)
### Contributors to this release
- [Jason Saayman](https://github.com/jasonsaayman)
- [scarf](https://github.com/scarf005)
- [Lenz Weber-Tronic](https://github.com/phryneas)
- [Arvindh](https://github.com/itsarvindh)
- [Félix Legrelle](https://github.com/FelixLgr)
- [Patrick Petrovic](https://github.com/ppati000)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
- [littledian](https://github.com/littledian)
- [ChronosMasterOfAllTime](https://github.com/ChronosMasterOfAllTime)
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.1.2] - 2022-10-07
### Fixed
- Fixed broken exports for UMD builds.
### Contributors to this release
- [Jason Saayman](https://github.com/jasonsaayman)
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.1.1] - 2022-10-07
### Fixed
- Fixed broken exports for common js. This fix breaks a prior fix, I will fix both issues ASAP but the commonJS use is more impactful.
### Contributors to this release
- [Jason Saayman](https://github.com/jasonsaayman)
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.1.0] - 2022-10-06
### Fixed
- Fixed missing exports in type definition index.d.ts [#5003](https://github.com/axios/axios/pull/5003)
- Fixed query params composing [#5018](https://github.com/axios/axios/pull/5018)
- Fixed GenericAbortSignal interface by making it more generic [#5021](https://github.com/axios/axios/pull/5021)
- Fixed adding "clear" to AxiosInterceptorManager [#5010](https://github.com/axios/axios/pull/5010)
- Fixed commonjs & umd exports [#5030](https://github.com/axios/axios/pull/5030)
- Fixed inability to access response headers when using axios 1.x with Jest [#5036](https://github.com/axios/axios/pull/5036)
### Contributors to this release
- [Trim21](https://github.com/trim21)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
- [shingo.sasaki](https://github.com/s-sasaki-0529)
- [Ivan Pepelko](https://github.com/ivanpepelko)
- [Richard Kořínek](https://github.com/risa)
### PRs
- CVE 2023 45857 ( [#6028](https://api.github.com/repos/axios/axios/pulls/6028) )
```
⚠️ Critical vulnerability fix. See https://security.snyk.io/vuln/SNYK-JS-AXIOS-6032459
```
## [1.0.0] - 2022-10-04
### Added
- Added stack trace to AxiosError [#4624](https://github.com/axios/axios/pull/4624)
- Add AxiosError to AxiosStatic [#4654](https://github.com/axios/axios/pull/4654)
- Replaced Rollup as our build runner [#4596](https://github.com/axios/axios/pull/4596)
- Added generic TS types for the exposed toFormData helper [#4668](https://github.com/axios/axios/pull/4668)
- Added listen callback function [#4096](https://github.com/axios/axios/pull/4096)
- Added instructions for installing using PNPM [#4207](https://github.com/axios/axios/pull/4207)
- Added generic AxiosAbortSignal TS interface to avoid importing AbortController polyfill [#4229](https://github.com/axios/axios/pull/4229)
- Added axios-url-template in ECOSYSTEM.md [#4238](https://github.com/axios/axios/pull/4238)
- Added a clear() function to the request and response interceptors object so a user can ensure that all interceptors have been removed from an axios instance [#4248](https://github.com/axios/axios/pull/4248)
- Added react hook plugin [#4319](https://github.com/axios/axios/pull/4319)
- Adding HTTP status code for transformResponse [#4580](https://github.com/axios/axios/pull/4580)
- Added blob to the list of protocols supported by the browser [#4678](https://github.com/axios/axios/pull/4678)
- Resolving proxy from env on redirect [#4436](https://github.com/axios/axios/pull/4436)
- Added enhanced toFormData implementation with additional options [4704](https://github.com/axios/axios/pull/4704)
- Adding Canceler parameters config and request [#4711](https://github.com/axios/axios/pull/4711)
- Added automatic payload serialization to application/x-www-form-urlencoded [#4714](https://github.com/axios/axios/pull/4714)
- Added the ability for webpack users to overwrite built-ins [#4715](https://github.com/axios/axios/pull/4715)
- Added string[] to AxiosRequestHeaders type [#4322](https://github.com/axios/axios/pull/4322)
- Added the ability for the url-encoded-form serializer to respect the formSerializer config [#4721](https://github.com/axios/axios/pull/4721)
- Added isCancel type assert [#4293](https://github.com/axios/axios/pull/4293)
- Added data URL support for node.js [#4725](https://github.com/axios/axios/pull/4725)
- Adding types for progress event callbacks [#4675](https://github.com/axios/axios/pull/4675)
- URL params serializer [#4734](https://github.com/axios/axios/pull/4734)
- Added axios.formToJSON method [#4735](https://github.com/axios/axios/pull/4735)
- Bower platform add data protocol [#4804](https://github.com/axios/axios/pull/4804)
- Use WHATWG URL API instead of url.parse() [#4852](https://github.com/axios/axios/pull/4852)
- Add ENUM containing Http Status Codes to typings [#4903](https://github.com/axios/axios/pull/4903)
- Improve typing of timeout in index.d.ts [#4934](https://github.com/axios/axios/pull/4934)
### Changed
- Updated AxiosError.config to be optional in the type definition [#4665](https://github.com/axios/axios/pull/4665)
- Updated README emphasizing the URLSearchParam built-in interface over other solutions [#4590](https://github.com/axios/axios/pull/4590)
- Include request and config when creating a CanceledError instance [#4659](https://github.com/axios/axios/pull/4659)
- Changed func-names eslint rule to as-needed [#4492](https://github.com/axios/axios/pull/4492)
- Replacing deprecated substr() with slice() as substr() is deprecated [#4468](https://github.com/axios/axios/pull/4468)
- Updating HTTP links in README.md to use HTTPS [#4387](https://github.com/axios/axios/pull/4387)
- Updated to a better trim() polyfill [#4072](https://github.com/axios/axios/pull/4072)
- Updated types to allow specifying partial default headers on instance create [#4185](https://github.com/axios/axios/pull/4185)
- Expanded isAxiosError types [#4344](https://github.com/axios/axios/pull/4344)
- Updated type definition for axios instance methods [#4224](https://github.com/axios/axios/pull/4224)
- Updated eslint config [#4722](https://github.com/axios/axios/pull/4722)
- Updated Docs [#4742](https://github.com/axios/axios/pull/4742)
- Refactored Axios to use ES2017 [#4787](https://github.com/axios/axios/pull/4787)
### Deprecated
- There are multiple deprecations, refactors and fixes provided in this release. Please read through the full release notes to see how this may impact your project and use case.
### Removed
- Removed incorrect argument for NetworkError constructor [#4656](https://github.com/axios/axios/pull/4656)
- Removed Webpack [#4596](https://github.com/axios/axios/pull/4596)
- Removed function that transform arguments to array [#4544](https://github.com/axios/axios/pull/4544)
### Fixed
- Fixed grammar in README [#4649](https://github.com/axios/axios/pull/4649)
- Fixed code error in README [#4599](https://github.com/axios/axios/pull/4599)
- Optimized the code that checks cancellation [#4587](https://github.com/axios/axios/pull/4587)
- Fix url pointing to defaults.js in README [#4532](https://github.com/axios/axios/pull/4532)
- Use type alias instead of interface for AxiosPromise [#4505](https://github.com/axios/axios/pull/4505)
- Fix some word spelling and lint style in code comments [#4500](https://github.com/axios/axios/pull/4500)
- Edited readme with 3 updated browser icons of Chrome, FireFox and Safari [#4414](https://github.com/axios/axios/pull/4414)
- Bump follow-redirects from 1.14.9 to 1.15.0 [#4673](https://github.com/axios/axios/pull/4673)
- Fixing http tests to avoid hanging when assertions fail [#4435](https://github.com/axios/axios/pull/4435)
- Fix TS definition for AxiosRequestTransformer [#4201](https://github.com/axios/axios/pull/4201)
- Fix grammatical issues in README [#4232](https://github.com/axios/axios/pull/4232)
- Fixing instance.defaults.headers type [#4557](https://github.com/axios/axios/pull/4557)
- Fixed race condition on immediate requests cancellation [#4261](https://github.com/axios/axios/pull/4261)
- Fixing Z_BUF_ERROR when no content [#4701](https://github.com/axios/axios/pull/4701)
- Fixing proxy beforeRedirect regression [#4708](https://github.com/axios/axios/pull/4708)
- Fixed AxiosError status code type [#4717](https://github.com/axios/axios/pull/4717)
- Fixed AxiosError stack capturing [#4718](https://github.com/axios/axios/pull/4718)
- Fixing AxiosRequestHeaders typings [#4334](https://github.com/axios/axios/pull/4334)
- Fixed max body length defaults [#4731](https://github.com/axios/axios/pull/4731)
- Fixed toFormData Blob issue on node>v17 [#4728](https://github.com/axios/axios/pull/4728)
- Bump grunt from 1.5.2 to 1.5.3 [#4743](https://github.com/axios/axios/pull/4743)
- Fixing content-type header repeated [#4745](https://github.com/axios/axios/pull/4745)
- Fixed timeout error message for http [4738](https://github.com/axios/axios/pull/4738)
- Request ignores false, 0 and empty string as body values [#4785](https://github.com/axios/axios/pull/4785)
- Added back missing minified builds [#4805](https://github.com/axios/axios/pull/4805)
- Fixed a type error [#4815](https://github.com/axios/axios/pull/4815)
- Fixed a regression bug with unsubscribing from cancel token; [#4819](https://github.com/axios/axios/pull/4819)
- Remove repeated compression algorithm [#4820](https://github.com/axios/axios/pull/4820)
- The error of calling extend to pass parameters [#4857](https://github.com/axios/axios/pull/4857)
- SerializerOptions.indexes allows boolean | null | undefined [#4862](https://github.com/axios/axios/pull/4862)
- Require interceptors to return values [#4874](https://github.com/axios/axios/pull/4874)
- Removed unused imports [#4949](https://github.com/axios/axios/pull/4949)
- Allow null indexes on formSerializer and paramsSerializer [#4960](https://github.com/axios/axios/pull/4960)
### Chores
- Set permissions for GitHub actions [#4765](https://github.com/axios/axios/pull/4765)
- Included githubactions in the dependabot config [#4770](https://github.com/axios/axios/pull/4770)
- Included dependency review [#4771](https://github.com/axios/axios/pull/4771)
- Update security.md [#4784](https://github.com/axios/axios/pull/4784)
- Remove unnecessary spaces [#4854](https://github.com/axios/axios/pull/4854)
- Simplify the import path of AxiosError [#4875](https://github.com/axios/axios/pull/4875)
- Fix Gitpod dead link [#4941](https://github.com/axios/axios/pull/4941)
- Enable syntax highlighting for a code block [#4970](https://github.com/axios/axios/pull/4970)
- Using Logo Axios in Readme.md [#4993](https://github.com/axios/axios/pull/4993)
- Fix markup for note in README [#4825](https://github.com/axios/axios/pull/4825)
- Fix typo and formatting, add colons [#4853](https://github.com/axios/axios/pull/4853)
- Fix typo in readme [#4942](https://github.com/axios/axios/pull/4942)
### Security
- Update SECURITY.md [#4687](https://github.com/axios/axios/pull/4687)
### Contributors to this release
- [Bertrand Marron](https://github.com/tusbar)
- [Dmitriy Mozgovoy](https://github.com/DigitalBrainJS)
- [Dan Mooney](https://github.com/danmooney)
- [Michael Li](https://github.com/xiaoyu-tamu)
- [aong](https://github.com/yxwzaxns)
- [Des Preston](https://github.com/despreston)
- [Ted Robertson](https://github.com/tredondo)
- [zhoulixiang](https://github.com/zh-lx)
- [Arthur Fiorette](https://github.com/arthurfiorette)
- [Kumar Shanu](https://github.com/Kr-Shanu)
- [JALAL](https://github.com/JLL32)
- [Jingyi Lin](https://github.com/MageeLin)
- [Philipp Loose](https://github.com/phloose)
- [Alexander Shchukin](https://github.com/sashsvamir)
- [Dave Cardwell](https://github.com/davecardwell)
- [Cat Scarlet](https://github.com/catscarlet)
- [Luca Pizzini](https://github.com/lpizzinidev)
- [Kai](https://github.com/Schweinepriester)
- [Maxime Bargiel](https://github.com/mbargiel)
- [Brian Helba](https://github.com/brianhelba)
- [reslear](https://github.com/reslear)
- [Jamie Slome](https://github.com/JamieSlome)
- [Landro3](https://github.com/Landro3)
- [rafw87](https://github.com/rafw87)
- [Afzal Sayed](https://github.com/afzalsayed96)
- [Koki Oyatsu](https://github.com/kaishuu0123)
- [Dave](https://github.com/wangcch)
- [暴走老七](https://github.com/baozouai)
- [Spencer](https://github.com/spalger)
- [Adrian Wieprzkowicz](https://github.com/Argeento)
- [Jamie Telin](https://github.com/lejahmie)
- [毛呆](https://github.com/aweikalee)
- [Kirill Shakirov](https://github.com/turisap)
- [Rraji Abdelbari](https://github.com/estarossa0)
- [Jelle Schutter](https://github.com/jelleschutter)
- [Tom Ceuppens](https://github.com/KyorCode)
- [Johann Cooper](https://github.com/JohannCooper)
- [Dimitris Halatsis](https://github.com/mitsos1os)
- [chenjigeng](https://github.com/chenjigeng)
- [João Gabriel Quaresma](https://github.com/joaoGabriel55)
- [Victor Augusto](https://github.com/VictorAugDB)
- [neilnaveen](https://github.com/neilnaveen)
- [Pavlos](https://github.com/psmoros)
- [Kiryl Valkovich](https://github.com/visortelle)
- [Naveen](https://github.com/naveensrinivasan)
- [wenzheng](https://github.com/0x30)
- [hcwhan](https://github.com/hcwhan)
- [Bassel Rachid](https://github.com/basselworkforce)
- [Grégoire Pineau](https://github.com/lyrixx)
- [felipedamin](https://github.com/felipedamin)
- [Karl Horky](https://github.com/karlhorky)
- [Yue JIN](https://github.com/kingyue737)
- [Usman Ali Siddiqui](https://github.com/usman250994)
- [WD](https://github.com/techbirds)
- [Günther Foidl](https://github.com/gfoidl)
- [Stephen Jennings](https://github.com/jennings)
- [C.T.Lin](https://github.com/chentsulin)
- [mia-z](https://github.com/mia-z)
- [Parth Banathia](https://github.com/Parth0105)
- [parth0105pluang](https://github.com/parth0105pluang)
- [Marco Weber](https://github.com/mrcwbr)
- [Luca Pizzini](https://github.com/lpizzinidev)
- [Willian Agostini](https://github.com/WillianAgostini)
- [Huyen Nguyen](https://github.com/huyenltnguyen)
Generated Vendored
+7
View File
@@ -0,0 +1,7 @@
# Copyright (c) 2014-present Matt Zabriskie & Collaborators
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+877
View File
@@ -0,0 +1,877 @@
# Axios Migration Guide
> **Migrating from Axios 0.x to 1.x**
>
> This guide helps developers upgrade from Axios 0.x to 1.x by documenting breaking changes, providing migration strategies, and offering solutions to common upgrade challenges.
## Table of Contents
- [Overview](#overview)
- [Breaking Changes](#breaking-changes)
- [Error Handling Migration](#error-handling-migration)
- [API Changes](#api-changes)
- [Configuration Changes](#configuration-changes)
- [Migration Strategies](#migration-strategies)
- [Common Patterns](#common-patterns)
- [Troubleshooting](#troubleshooting)
- [Resources](#resources)
## Overview
Axios 1.x introduced several breaking changes to improve consistency, security, and developer experience. While these changes provide better error handling and more predictable behavior, they require code updates when migrating from 0.x versions.
### Key Changes Summary
| Area | 0.x Behavior | 1.x Behavior | Impact |
|------|--------------|--------------|--------|
| Error Handling | Selective throwing | Consistent throwing | High |
| JSON Parsing | Lenient | Strict | Medium |
| Browser Support | IE11+ | Modern browsers | Low-Medium |
| TypeScript | Partial | Full support | Low |
### Migration Complexity
- **Simple applications**: 1-2 hours
- **Medium applications**: 1-2 days
- **Large applications with complex error handling**: 3-5 days
## Breaking Changes
### 1. Error Handling Changes
**The most significant change in Axios 1.x is how errors are handled.**
#### 0.x Behavior
```javascript
// Axios 0.x - Some HTTP error codes didn't throw
axios.get('/api/data')
.then(response => {
// Response interceptor could handle all errors
console.log('Success:', response.data);
});
// Response interceptor handled everything
axios.interceptors.response.use(
response => response,
error => {
handleError(error);
// Error was "handled" and didn't propagate
}
);
```
#### 1.x Behavior
```javascript
// Axios 1.x - All HTTP errors throw consistently
axios.get('/api/data')
.then(response => {
console.log('Success:', response.data);
})
.catch(error => {
// Must handle errors at call site or they propagate
console.error('Request failed:', error);
});
// Response interceptor must re-throw or return rejected promise
axios.interceptors.response.use(
response => response,
error => {
handleError(error);
// Must explicitly handle propagation
return Promise.reject(error); // or throw error;
}
);
```
#### Impact
- **Response interceptors** can no longer "swallow" errors silently
- **Every API call** must handle errors explicitly or they become unhandled promise rejections
- **Centralized error handling** requires new patterns
### 2. JSON Parsing Changes
#### 0.x Behavior
```javascript
// Axios 0.x - Lenient JSON parsing
// Would attempt to parse even invalid JSON
response.data; // Might contain partial data or fallbacks
```
#### 1.x Behavior
```javascript
// Axios 1.x - Strict JSON parsing
// Throws clear errors for invalid JSON
try {
const data = response.data;
} catch (error) {
// Handle JSON parsing errors explicitly
}
```
### 3. Request/Response Transform Changes
#### 0.x Behavior
```javascript
// Implicit transformations with some edge cases
transformRequest: [function (data) {
// Less predictable behavior
return data;
}]
```
#### 1.x Behavior
```javascript
// More consistent transformation pipeline
transformRequest: [function (data, headers) {
// Headers parameter always available
// More predictable behavior
return data;
}]
```
### 4. Browser Support Changes
- **0.x**: Supported IE11 and older browsers
- **1.x**: Requires modern browsers with Promise support
- **Polyfills**: May be needed for older browser support
## Error Handling Migration
The error handling changes are the most complex part of migrating to Axios 1.x. Here are proven strategies:
### Strategy 1: Centralized Error Handling with Error Boundary
```javascript
// Create a centralized error handler
class ApiErrorHandler {
constructor() {
this.setupInterceptors();
}
setupInterceptors() {
axios.interceptors.response.use(
response => response,
error => {
// Centralized error processing
this.processError(error);
// Return a resolved promise with error info for handled errors
if (this.isHandledError(error)) {
return Promise.resolve({
data: null,
error: this.normalizeError(error),
handled: true
});
}
// Re-throw unhandled errors
return Promise.reject(error);
}
);
}
processError(error) {
// Log errors
console.error('API Error:', error);
// Show user notifications
if (error.response?.status === 401) {
this.handleAuthError();
} else if (error.response?.status >= 500) {
this.showErrorNotification('Server error occurred');
}
}
isHandledError(error) {
// Define which errors are "handled" centrally
const handledStatuses = [401, 403, 404, 422, 500, 502, 503];
return handledStatuses.includes(error.response?.status);
}
normalizeError(error) {
return {
status: error.response?.status,
message: error.response?.data?.message || error.message,
code: error.response?.data?.code || error.code
};
}
handleAuthError() {
// Redirect to login, clear tokens, etc.
localStorage.removeItem('token');
window.location.href = '/login';
}
showErrorNotification(message) {
// Show user-friendly error message
console.error(message); // Replace with your notification system
}
}
// Initialize globally
const errorHandler = new ApiErrorHandler();
// Usage in components/services
async function fetchUserData(userId) {
try {
const response = await axios.get(`/api/users/${userId}`);
// Check if error was handled centrally
if (response.handled) {
return { data: null, error: response.error };
}
return { data: response.data, error: null };
} catch (error) {
// Unhandled errors still need local handling
return { data: null, error: { message: 'Unexpected error occurred' } };
}
}
```
### Strategy 2: Wrapper Function Pattern
```javascript
// Create a wrapper that provides 0.x-like behavior
function createApiWrapper() {
const api = axios.create();
// Add response interceptor for centralized handling
api.interceptors.response.use(
response => response,
error => {
// Handle common errors centrally
if (error.response?.status === 401) {
// Handle auth errors
handleAuthError();
}
if (error.response?.status >= 500) {
// Handle server errors
showServerErrorNotification();
}
// Always reject to maintain error propagation
return Promise.reject(error);
}
);
// Wrapper function that mimics 0.x behavior
function safeRequest(requestConfig, options = {}) {
return api(requestConfig)
.then(response => response)
.catch(error => {
if (options.suppressErrors) {
// Return error info instead of throwing
return {
data: null,
error: {
status: error.response?.status,
message: error.response?.data?.message || error.message
}
};
}
throw error;
});
}
return { safeRequest, axios: api };
}
// Usage
const { safeRequest } = createApiWrapper();
// For calls where you want centralized error handling
const result = await safeRequest(
{ method: 'get', url: '/api/data' },
{ suppressErrors: true }
);
if (result.error) {
// Handle error case
console.log('Request failed:', result.error.message);
} else {
// Handle success case
console.log('Data:', result.data);
}
```
### Strategy 3: Global Error Handler with Custom Events
```javascript
// Set up global error handling with events
class GlobalErrorHandler extends EventTarget {
constructor() {
super();
this.setupInterceptors();
}
setupInterceptors() {
axios.interceptors.response.use(
response => response,
error => {
// Emit custom event for global handling
this.dispatchEvent(new CustomEvent('apiError', {
detail: { error, timestamp: new Date() }
}));
// Always reject to maintain proper error flow
return Promise.reject(error);
}
);
}
}
const globalErrorHandler = new GlobalErrorHandler();
// Set up global listeners
globalErrorHandler.addEventListener('apiError', (event) => {
const { error } = event.detail;
// Centralized error logic
if (error.response?.status === 401) {
handleAuthError();
}
if (error.response?.status >= 500) {
showErrorNotification('Server error occurred');
}
});
// Usage remains clean
async function apiCall() {
try {
const response = await axios.get('/api/data');
return response.data;
} catch (error) {
// Error was already handled globally
// Just handle component-specific logic
return null;
}
}
```
## API Changes
### Request Configuration
#### 0.x to 1.x Changes
```javascript
// 0.x - Some properties had different defaults
const config = {
timeout: 0, // No timeout by default
maxContentLength: -1, // No limit
};
// 1.x - More secure defaults
const config = {
timeout: 0, // Still no timeout, but easier to configure
maxContentLength: 2000, // Default limit for security
maxBodyLength: 2000, // New property
};
```
### Response Object
The response object structure remains largely the same, but error responses are more consistent:
```javascript
// Both 0.x and 1.x
response = {
data: {}, // Response body
status: 200, // HTTP status
statusText: 'OK', // HTTP status message
headers: {}, // Response headers
config: {}, // Request config
request: {} // Request object
};
// Error responses are more consistent in 1.x
error.response = {
data: {}, // Error response body
status: 404, // HTTP error status
statusText: 'Not Found',
headers: {},
config: {},
request: {}
};
```
## Configuration Changes
### Default Configuration Updates
```javascript
// 0.x defaults
axios.defaults.timeout = 0; // No timeout
axios.defaults.maxContentLength = -1; // No limit
// 1.x defaults (more secure)
axios.defaults.timeout = 0; // Still no timeout
axios.defaults.maxContentLength = 2000; // 2MB limit
axios.defaults.maxBodyLength = 2000; // 2MB limit
```
### Instance Configuration
```javascript
// 0.x - Instance creation
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
});
// 1.x - Same API, but more options available
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 1000,
maxBodyLength: Infinity, // Override default if needed
maxContentLength: Infinity,
});
```
## Migration Strategies
### Step-by-Step Migration Process
#### Phase 1: Preparation
1. **Audit Current Error Handling**
```bash
# Find all axios usage
grep -r "axios\." src/
grep -r "\.catch" src/
grep -r "interceptors" src/
```
2. **Identify Patterns**
- Response interceptors that handle errors
- Components that rely on centralized error handling
- Authentication and retry logic
3. **Create Test Cases**
```javascript
// Test current error handling behavior
describe('Error Handling Migration', () => {
it('should handle 401 errors consistently', async () => {
// Test authentication error flows
});
it('should handle 500 errors with user feedback', async () => {
// Test server error handling
});
});
```
#### Phase 2: Implementation
1. **Update Dependencies**
```bash
npm update axios
```
2. **Implement New Error Handling**
- Choose one of the strategies above
- Update response interceptors
- Add error handling to API calls
3. **Update Authentication Logic**
```javascript
// 0.x pattern
axios.interceptors.response.use(null, error => {
if (error.response?.status === 401) {
logout();
// Error was "handled"
}
});
// 1.x pattern
axios.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
logout();
}
return Promise.reject(error); // Always propagate
}
);
```
#### Phase 3: Testing and Validation
1. **Test Error Scenarios**
- Network failures
- HTTP error codes (401, 403, 404, 500, etc.)
- Timeout errors
- JSON parsing errors
2. **Validate User Experience**
- Error messages are shown appropriately
- Authentication redirects work
- Loading states are handled correctly
### Gradual Migration Approach
For large applications, consider gradual migration:
```javascript
// Create a compatibility layer
const axiosCompat = {
// Use new axios instance for new code
v1: axios.create({
// 1.x configuration
}),
// Wrapper for legacy code
legacy: createLegacyWrapper(axios.create({
// Configuration that mimics 0.x behavior
}))
};
function createLegacyWrapper(axiosInstance) {
// Add interceptors that provide 0.x-like behavior
axiosInstance.interceptors.response.use(
response => response,
error => {
// Handle errors in 0.x style for legacy code
handleLegacyError(error);
// Don't propagate certain errors
if (shouldSuppressError(error)) {
return Promise.resolve({ data: null, error: true });
}
return Promise.reject(error);
}
);
return axiosInstance;
}
```
## Common Patterns
### Authentication Interceptors
#### Updated Authentication Pattern
```javascript
// Token refresh interceptor for 1.x
let isRefreshing = false;
let refreshSubscribers = [];
function subscribeTokenRefresh(cb) {
refreshSubscribers.push(cb);
}
function onTokenRefreshed(token) {
refreshSubscribers.forEach(cb => cb(token));
refreshSubscribers = [];
}
axios.interceptors.response.use(
response => response,
async error => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
// Wait for token refresh
return new Promise(resolve => {
subscribeTokenRefresh(token => {
originalRequest.headers.Authorization = `Bearer ${token}`;
resolve(axios(originalRequest));
});
});
}
originalRequest._retry = true;
isRefreshing = true;
try {
const newToken = await refreshToken();
onTokenRefreshed(newToken);
isRefreshing = false;
originalRequest.headers.Authorization = `Bearer ${newToken}`;
return axios(originalRequest);
} catch (refreshError) {
isRefreshing = false;
logout();
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
```
### Retry Logic
```javascript
// Retry interceptor for 1.x
function createRetryInterceptor(maxRetries = 3, retryDelay = 1000) {
return axios.interceptors.response.use(
response => response,
async error => {
const config = error.config;
if (!config || !config.retry) {
return Promise.reject(error);
}
config.__retryCount = config.__retryCount || 0;
if (config.__retryCount >= maxRetries) {
return Promise.reject(error);
}
config.__retryCount += 1;
// Exponential backoff
const delay = retryDelay * Math.pow(2, config.__retryCount - 1);
await new Promise(resolve => setTimeout(resolve, delay));
return axios(config);
}
);
}
// Usage
const api = axios.create();
createRetryInterceptor(3, 1000);
// Make request with retry
api.get('/api/data', { retry: true });
```
### Loading State Management
```javascript
// Loading interceptor for 1.x
class LoadingManager {
constructor() {
this.requests = new Set();
this.setupInterceptors();
}
setupInterceptors() {
axios.interceptors.request.use(config => {
this.requests.add(config);
this.updateLoadingState();
return config;
});
axios.interceptors.response.use(
response => {
this.requests.delete(response.config);
this.updateLoadingState();
return response;
},
error => {
this.requests.delete(error.config);
this.updateLoadingState();
return Promise.reject(error);
}
);
}
updateLoadingState() {
const isLoading = this.requests.size > 0;
// Update your loading UI
document.body.classList.toggle('loading', isLoading);
}
}
const loadingManager = new LoadingManager();
```
## Troubleshooting
### Common Migration Issues
#### Issue 1: Unhandled Promise Rejections
**Problem:**
```javascript
// This pattern worked in 0.x but causes unhandled rejections in 1.x
axios.get('/api/data'); // No .catch() handler
```
**Solution:**
```javascript
// Always handle promises
axios.get('/api/data')
.catch(error => {
// Handle error appropriately
console.error('Request failed:', error.message);
});
// Or use async/await with try/catch
async function fetchData() {
try {
const response = await axios.get('/api/data');
return response.data;
} catch (error) {
console.error('Request failed:', error.message);
return null;
}
}
```
#### Issue 2: Response Interceptors Not "Handling" Errors
**Problem:**
```javascript
// 0.x style - interceptor "handled" errors
axios.interceptors.response.use(null, error => {
showErrorMessage(error.message);
// Error was considered "handled"
});
```
**Solution:**
```javascript
// 1.x style - explicitly control error propagation
axios.interceptors.response.use(
response => response,
error => {
showErrorMessage(error.message);
// Choose whether to propagate the error
if (shouldPropagateError(error)) {
return Promise.reject(error);
}
// Return success-like response for "handled" errors
return Promise.resolve({
data: null,
handled: true,
error: normalizeError(error)
});
}
);
```
#### Issue 3: JSON Parsing Errors
**Problem:**
```javascript
// 1.x is stricter about JSON parsing
// This might throw where 0.x was lenient
const data = response.data;
```
**Solution:**
```javascript
// Add response transformer for better error handling
axios.defaults.transformResponse = [
function (data) {
if (typeof data === 'string') {
try {
return JSON.parse(data);
} catch (e) {
// Handle JSON parsing errors gracefully
console.warn('Invalid JSON response:', data);
return { error: 'Invalid JSON', rawData: data };
}
}
return data;
}
];
```
#### Issue 4: TypeScript Errors After Upgrade
**Problem:**
```typescript
// TypeScript errors after upgrade
const response = await axios.get('/api/data');
// Property 'someProperty' does not exist on type 'any'
```
**Solution:**
```typescript
// Define proper interfaces
interface ApiResponse {
data: any;
message: string;
success: boolean;
}
const response = await axios.get<ApiResponse>('/api/data');
// Now properly typed
console.log(response.data.data);
```
### Debug Migration Issues
#### Enable Debug Logging
```javascript
// Add request/response logging
axios.interceptors.request.use(config => {
console.log('Request:', config);
return config;
});
axios.interceptors.response.use(
response => {
console.log('Response:', response);
return response;
},
error => {
console.log('Error:', error);
return Promise.reject(error);
}
);
```
#### Compare Behavior
```javascript
// Create side-by-side comparison during migration
const axios0x = require('axios-0x'); // Keep old version for testing
const axios1x = require('axios');
async function compareRequests(config) {
try {
const [result0x, result1x] = await Promise.allSettled([
axios0x(config),
axios1x(config)
]);
console.log('0.x result:', result0x);
console.log('1.x result:', result1x);
} catch (error) {
console.log('Comparison error:', error);
}
}
```
## Resources
### Official Documentation
- [Axios 1.x Documentation](https://axios-http.com/)
- [Axios GitHub Repository](https://github.com/axios/axios)
- [Axios Changelog](https://github.com/axios/axios/blob/main/CHANGELOG.md)
### Migration Tools
- [Axios Migration Codemod](https://github.com/axios/axios-migration-codemod) *(if available)*
- [ESLint Rules for Axios 1.x](https://github.com/axios/eslint-plugin-axios) *(if available)*
### Community Resources
- [Stack Overflow - Axios Migration Questions](https://stackoverflow.com/questions/tagged/axios+migration)
- [GitHub Discussions](https://github.com/axios/axios/discussions)
- [Axios Discord Community](https://discord.gg/axios) *(if available)*
### Related Issues
- [Error Handling Changes Discussion](https://github.com/axios/axios/issues/7208)
- [Migration Guide Request](https://github.com/axios/axios/issues/xxxx) *(link to related issues)*
---
## Need Help?
If you encounter issues during migration that aren't covered in this guide:
1. **Search existing issues** in the [Axios GitHub repository](https://github.com/axios/axios/issues)
2. **Ask questions** in [GitHub Discussions](https://github.com/axios/axios/discussions)
3. **Contribute improvements** to this migration guide
---
*This migration guide is maintained by the community. If you find errors or have suggestions, please [open an issue](https://github.com/axios/axios/issues) or submit a pull request.*
+2559
View File
@@ -0,0 +1,2559 @@
<h3 align="center">💎 Platinum sponsors <br /></h3>
<table align="center">
<tr>
<td align="center" width="50%">
<a
href="https://thanks.dev/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="90px"
height="90px"
src="https://images.opencollective.com/thanks-dev/360b917/logo/256.png?height=256"
alt="Thanks.dev"
/>
</a>
<p
align="center"
>
We're passionate about making open source sustainable. Scan your dependency tree to better understand which open source projects need funding.
</p>
<p align="center">
<a
href="https://thanks.dev/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
target="_blank"
><b>thanks.dev</b></a
>
</p>
</td>
<td align="center" width="50%">
<a
href="https://opencollective.com/axios/contribute"
target="_blank"
>💜 Become a sponsor</a
>
</td>
</tr>
</table>
<table align="center">
<tr>
<td align="center" width="50%">
<a
href="https://opencollective.com/axios/contribute"
target="_blank"
>💜 Become a sponsor</a
>
</td>
<td align="center" width="50%">
<a
href="https://opencollective.com/axios/contribute"
target="_blank"
>💜 Become a sponsor</a
>
</td>
</tr>
</table>
<h3 align="center">🥇 Gold sponsors <br /></h3>
<table align="center" width="100%">
<tr width="33.333333333333336%">
<td align="center" width="33.333333333333336%">
<a
href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="90px"
height="90px"
src="https://images.opencollective.com/principal/431e690/logo.png"
alt="Principal Financial Group"
/>
</a>
<p
align="center"
>
Free tools to help with your financial planning needs!
</p>
<p align="center">
<a
href="https://www.principal.com/about-us?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
target="_blank"
><b>principal.com</b></a
>
</p>
</td>
<td align="center" width="33.333333333333336%">
<a
href="https://opensource.sap.com?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="90px"
height="90px"
src="https://avatars.githubusercontent.com/u/2531208?s=200&v=4"
alt="SAP"
/>
</a>
<p
align="center"
title="SAP SE, a global software company, is one of the largest vendors of ERP and other enterprise applications."
>
BSAP SE, a global software company, is one of the largest vendors of ERP and other enterprise applications.
</p>
<p align="center">
<a
href="https://opensource.sap.com?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
target="_blank"
><b>opensource.sap.com</b></a
>
</p>
</td>
<td align="center" width="33.333333333333336%">
<a
href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="90px"
height="90px"
src="https://images.opencollective.com/descope/b53243e/logo.png"
alt="Descope"
/>
</a>
<p
align="center"
title="Hi, we&#x27;re Descope! We are building something in the authentication space for app developers and can't wait to place it in your hands."
>
Reduce user friction, prevent account takeover, and get a 360° view of your customer and agentic identities with the Descope External IAM platform.
</p>
<p align="center">
<a
href="https://www.descope.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;referral&amp;utm_campaign&#x3D;axios-oss-sponsorship"
target="_blank"
><b>descope.com</b></a
>
</p>
</td>
</tr>
<tr width="33.333333333333336%">
<td align="center" width="33.333333333333336%">
<a
href="https://stytch.com/"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="90px"
height="90px"
src="https://images.opencollective.com/stytch/f84ce43/logo/256.png?height=256"
alt="Stytch"
/>
</a>
<p
align="center"
>
The identity platform for humans & AI agents
</p>
<p align="center">
<a
href="https://stytch.com"
target="_blank"
><b>stytch.com</b></a
>
</p>
</td>
<td align="center" width="33.333333333333336%">
<a
href="https://rxdb.info/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship&utm_content=logo"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="90px"
height="90px"
src="https://rxdb.info/files/logo/logo_text_white.svg"
alt="RxDB"
/>
</a>
<p
align="center"
>
RxDB is a NoSQL database for JavaScript that runs directly in your app.
</p>
<p align="center">
<a
href="https://rxdb.info/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship&utm_content=logo"
target="_blank"
><b>rxdb.info</b></a
>
</p>
</td>
<td align="center" width="33.333333333333336%">
<a
href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;sponsorlist&amp;utm_campaign&#x3D;sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="70px"
height="70px"
src="https://images.opencollective.com/instagram-likes/2a72a03/avatar.png"
alt="Poprey"
/>
</a>
<p align="center">
Buy Instagram Likes
</p>
<p align="center">
<a
href="https://poprey.com/?utm_source&#x3D;axios&amp;utm_medium&#x3D;readme_sponsorlist&amp;utm_campaign&#x3D;sponsorship"
target="_blank"
><b>poprey.com</b></a
>
</p>
</td>
</tr>
<tr width="33.333333333333336%">
<td align="center" width="33.333333333333336%">
<a
href="https://buzzoid.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="71px"
height="70px"
src="https://images.opencollective.com/buzzoid-buy-instagram-followers/56a09fe/logo.png"
alt="Buzzoid - Buy Instagram Followers"
/>
</a>
<p
align="center"
>
At Buzzoid, you can buy Instagram followers through a short checkout flow with safety controls. Rated world&#39;s #1 IG service since 2012.
</p>
<p align="center">
<a
href="https://buzzoid.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
target="_blank"
><b>buzzoid.com</b></a
>
</p>
</td>
<td align="center" width="33.333333333333336%">
<a
href="https://twicsy.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="71px"
height="70px"
src="https://images.opencollective.com/buy-instagram-followers-twicsy/b4c5d7f/logo/256.png?height=256"
alt="Buy Instagram Followers Twicsy"
/>
</a>
<p
align="center"
>
Buy real Instagram followers from Twicsy. Twicsy has been voted the best site to buy followers from the likes of US Magazine.
</p>
<p align="center">
<a
href="https://twicsy.com/buy-instagram-followers/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
target="_blank"
><b>twicsy.com</b></a
>
</p>
</td>
<td align="center" width="33.333333333333336%">
<a
href="https://global.fun88.com/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
style="padding: 10px; display: inline-block"
target="_blank"
>
<img
width="71px"
height="70px"
src="https://images.opencollective.com/fun88-official/bf2843c/logo.png"
alt="Fun 88"
/>
</a>
<p
align="center"
>
Fun88 is a global online gambling and betting brand founded in 2009, offering a wide range of services including sports betting, live casino games, slots, and virtual gaming.
</p>
<p align="center">
<a
href="https://global.fun88.com/?utm_source=axios_docs_website&utm_medium=website&utm_campaign=axios_open_collective_sponsorship"
target="_blank"
><b>global.fun88.com</b></a
>
</p>
</td>
</tr>
</table>
<!--<div>marker</div>-->
<br><br>
<div align="center">
<a href="https://axios.rest"><img src="https://axios.rest/logo.svg" alt="Axios" /></a><br>
</div>
<p align="center">Promise based HTTP client for the browser and node.js</p>
<p align="center">
<a href="https://axios.rest/"><b>Website</b></a> •
<a href="https://axios.rest/pages/getting-started/first-steps.html"><b>Documentation</b></a>
</p>
<div align="center">
[![npm version](https://img.shields.io/npm/v/axios.svg?style=flat-square)](https://www.npmjs.org/package/axios)
[![Build status](https://img.shields.io/github/actions/workflow/status/axios/axios/ci.yml?branch=v1.x&label=CI&logo=github&style=flat-square)](https://github.com/axios/axios/actions/workflows/ci.yml)
[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod&style=flat-square)](https://gitpod.io/#https://github.com/axios/axios)
[![install size](https://img.shields.io/badge/dynamic/json?url=https://packagephobia.com/v2/api.json?p=axios&query=$.install.pretty&label=install%20size&style=flat-square)](https://packagephobia.now.sh/result?p=axios)
[![npm bundle size](https://img.shields.io/bundlephobia/minzip/axios?style=flat-square)](https://bundlephobia.com/package/axios@latest)
[![npm downloads](https://img.shields.io/npm/dm/axios.svg?style=flat-square)](https://npm-stat.com/charts.html?package=axios)
[![gitter chat](https://img.shields.io/gitter/room/mzabriskie/axios.svg?style=flat-square)](https://gitter.im/mzabriskie/axios)
[![code helpers](https://www.codetriage.com/axios/axios/badges/users.svg)](https://www.codetriage.com/axios/axios)
[![Contributors](https://img.shields.io/github/contributors/axios/axios.svg?style=flat-square)](CONTRIBUTORS.md)
[![Agent Friendly](https://agentfriendlycode.com/api/badge/github/axios/axios.svg)](https://agentfriendlycode.com/repo/32)
</div>
## Table of contents
- [Features](#features)
- [Browser support](#browser-support)
- [Installing](#installing)
- [Package manager](#package-manager)
- [CDN](#cdn)
- [Example](#example)
- [Axios API](#axios-api)
- [Request method aliases](#request-method-aliases)
- [Concurrency](#concurrency-deprecated)
- [Creating an instance](#creating-an-instance)
- [Instance methods](#instance-methods)
- [Request config](#request-config)
- [Response schema](#response-schema)
- [Config defaults](#config-defaults)
- [Global axios defaults](#global-axios-defaults)
- [Custom instance defaults](#custom-instance-defaults)
- [Config order of precedence](#config-order-of-precedence)
- [Interceptors](#interceptors)
- [Multiple interceptors](#multiple-interceptors)
- [Handling errors](#handling-errors)
- [Handling timeouts](#handling-timeouts)
- [Cancellation](#cancellation)
- [AbortController](#abortcontroller)
- [CancelToken](#canceltoken-deprecated)
- [Using application/x-www-form-urlencoded format](#using-applicationx-www-form-urlencoded-format)
- [URLSearchParams](#urlsearchparams)
- [Query string](#query-string-older-browsers)
- [Automatic serialization](#automatic-serialization-to-urlsearchparams)
- [Using multipart/form-data format](#using-multipartform-data-format)
- [FormData](#formdata)
- [Automatic serialization](#automatic-serialization-to-formdata)
- [Posting files](#posting-files)
- [HTML form posting](#html-form-posting-browser)
- [Progress capturing](#progress-capturing)
- [Rate limiting](#rate-limiting)
- [AxiosHeaders](#axiosheaders)
- [Fetch adapter](#fetch-adapter)
- [Custom fetch](#custom-fetch)
- [Using with Tauri](#using-with-tauri)
- [Using with SvelteKit](#using-with-sveltekit)
- [HTTP/2 support](#http2-support)
- [Semver](#semver)
- [Promises](#promises)
- [TypeScript](#typescript)
- [Contributing](#contributing)
- [Local setup](#local-setup)
- [Resources](#resources)
- [Credits](#credits)
- [License](#license)
## Features
- Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser.
- Make [http](https://nodejs.org/api/http.html) requests from Node.js.
- Use the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API for asynchronous request handling.
- Intercept requests and responses to add custom logic or transform data.
- Transform request and response data.
- Cancel requests with built-in cancellation APIs.
- Serialize and parse [JSON](https://www.json.org/json-en.html) data.
- Serialize data objects to `multipart/form-data` or `application/x-www-form-urlencoded`.
- Add client-side protection against [Cross-Site Request Forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery).
## Browser support
| Chrome | Firefox | Safari | Opera | Edge |
| :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------------------------: |
| ![Chrome browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/chrome/chrome_48x48.png) | ![Firefox browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/firefox/firefox_48x48.png) | ![Safari browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/safari/safari_48x48.png) | ![Opera browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/opera/opera_48x48.png) | ![Edge browser logo](https://raw.githubusercontent.com/alrra/browser-logos/main/src/edge/edge_48x48.png) |
| Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |
[![Browser Matrix](https://saucelabs.com/open_sauce/build_matrix/axios.svg)](https://saucelabs.com/u/axios)
## Installing
### Package manager
Using npm:
```bash
$ npm install axios
```
Using yarn:
```bash
$ yarn add axios
```
Using pnpm:
```bash
$ pnpm add axios
```
Using bun:
```bash
$ bun add axios
```
Using Deno:
```bash
$ deno add axios
```
Once the package is installed, import it with `import` or `require`:
```js
import axios, { isCancel, AxiosError } from 'axios';
```
You can also use the default export, since the named export is just a re-export from the Axios factory:
```js
import axios from 'axios';
console.log(axios.isCancel('something'));
```
If you use `require` for importing, **only the default export is available**:
```js
const axios = require('axios');
console.log(axios.isCancel('something'));
```
Some bundlers and ES6 linters need this form:
```js
import { default as axios } from 'axios';
```
In custom or legacy environments, you can import the bundle directly:
```js
const axios = require('axios/dist/browser/axios.cjs'); // browser commonJS bundle (ES2017)
// const axios = require('axios/dist/node/axios.cjs'); // node commonJS bundle (ES2017)
```
### CDN
Using jsDelivr CDN (ES5 UMD browser module):
```html
<script src="https://cdn.jsdelivr.net/npm/axios@1.13.2/dist/axios.min.js"></script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/axios@1.13.2/dist/axios.min.js"></script>
```
## Example
```js
import axios from 'axios';
//const axios = require('axios'); // legacy way
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
// Optionally the request above could also be done as
axios
.get('/user', {
params: {
ID: 12345,
},
timeout: 5000, // 5 seconds. See "Handling Timeouts" below for matching error handling
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
// Example: GET request with query parameters
const response = await axios.get('/user', {
params: {
ID: 12345,
},
});
// Using the `params` option improves readability and automatically formats query strings
console.log(response);
} catch (error) {
console.error(error);
}
}
```
> Note: Set a `timeout` in production. Without one, a stalled request can hang
> indefinitely. See [Handling Timeouts](#handling-timeouts) for the matching error handling.
> Note: `async/await` is part of ECMAScript 2017 and is not supported in Internet
> Explorer and older browsers, so use with caution.
Performing a `POST` request
```js
const response = await axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone',
});
console.log(response);
```
Performing multiple concurrent requests
```js
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
Promise.all([getUserAccount(), getUserPermissions()]).then(function (results) {
const acct = results[0];
const perm = results[1];
});
```
## axios API
Requests can be made by passing the relevant config to `axios`.
##### axios(config)
```js
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone',
},
});
```
```js
// GET request for remote image in node.js
const response = await axios({
method: 'get',
url: 'https://bit.ly/2mTM3nY',
responseType: 'stream',
});
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'));
```
##### axios(url[, config])
```js
// Send a GET request (default method)
axios('/user/12345');
```
### Request method aliases
For convenience, aliases have been provided for all common request methods.
##### axios.request(config)
##### axios.get(url[, config])
##### axios.delete(url[, config])
##### axios.head(url[, config])
##### axios.options(url[, config])
##### axios.post(url[, data[, config]])
##### axios.put(url[, data[, config]])
##### axios.patch(url[, data[, config]])
###### Note
When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config.
### Concurrency (deprecated)
Use `Promise.all` instead of these helpers.
Helper functions for dealing with concurrent requests.
axios.all(iterable)
axios.spread(callback)
### Creating an instance
You can create a new instance of axios with a custom config.
##### axios.create([config])
```js
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: { 'X-Custom-Header': 'foobar' },
});
```
### Instance methods
The following instance methods are available. Axios merges the specified config with the instance config.
##### axios#request(config)
##### axios#get(url[, config])
##### axios#delete(url[, config])
##### axios#head(url[, config])
##### axios#options(url[, config])
##### axios#post(url[, data[, config]])
##### axios#put(url[, data[, config]])
##### axios#patch(url[, data[, config]])
##### axios#getUri([config])
## Request config
### Security notice: decompression-bomb protection is opt-in
By default `maxContentLength` and `maxBodyLength` are `-1` (unlimited). A malicious or compromised server can return a tiny gzip/deflate/brotli/zstd body that expands to gigabytes and exhaust the Node.js process.
If you call servers you do not fully trust, **set a cap**:
```js
axios.defaults.maxContentLength = 10 * 1024 * 1024; // 10 MB
axios.defaults.maxBodyLength = 10 * 1024 * 1024;
```
See the [security guide](https://axios.rest/pages/misc/security.html) for details.
These config options are available for requests. Only `url` is required. Requests default to `GET` when `method` is not set.
```js
{
// `url` is the server URL for the request
url: '/user',
// `method` is the request method to be used when making the request
method: 'get', // default
// Axios prepends `baseURL` to `url` unless `url` is absolute and `allowAbsoluteUrls` is set to true.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to the methods of that instance.
baseURL: 'https://some-domain.com/api/',
// `allowAbsoluteUrls` determines whether or not absolute URLs will override a configured `baseUrl`.
// When set to true (default), absolute values for `url` will override `baseUrl`.
// When set to false, absolute values for `url` will always be prepended by `baseUrl`.
allowAbsoluteUrls: true,
// `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
// FormData or Stream
// You may modify the headers object.
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],
// `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `parseReviver` is an optional function passed as the
// second argument (reviver) to JSON.parse()
parseReviver: function (key, value, context) {
// In modern environments, context.source provides the raw JSON string
// allowing for precision-safe parsing of BigInt
if (typeof value === 'number' && context?.source) {
const isInteger = Number.isInteger(value);
const isUnsafe = !Number.isSafeInteger(value);
const isValidIntegerString = /^-?\d+$/.test(context.source);
if (isInteger && isUnsafe && isValidIntegerString) {
try {
return BigInt(context.source);
} catch {
// Fallback: return original value if parsing fails
}
}
}
return value;
},
// `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
},
// `paramsSerializer` is an optional config that allows you to customize serializing `params`.
paramsSerializer: {
// Custom encoder function which sends key/value pairs in an iterative fashion.
encode?: (param: string): string => { /* Do custom operations here and return transformed string */ },
// Custom serializer function for the entire parameter. Allows the user to mimic pre 1.x behaviour.
serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ),
// Configuration for formatting array indexes in the params.
indexes: false, // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes).
// Maximum object nesting depth when serializing params. Payloads deeper than this throw an
// AxiosError with code ERR_FORM_DATA_DEPTH_EXCEEDED. Default: 100. Set to Infinity to disable.
maxDepth: 100
},
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'
// `data` is request-specific: axios does not inherit or deep-merge it from defaults.
// To add shared body fields, use a request interceptor or transformRequest.
// When no `transformRequest` is set, it must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - React Native: FormData
// - Node only: Stream, Buffer, FormData (form-data package)
data: {
firstName: 'Fred'
},
// `formDataHeaderPolicy` controls how node.js FormData#getHeaders() is copied.
// 'legacy' (default) copies all returned headers for v1 compatibility.
// 'content-only' copies only Content-Type and Content-Length.
formDataHeaderPolicy: 'legacy',
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, Axios aborts it.
timeout: 1000, // default is `0` (no timeout)
// `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
// This only controls whether the browser sends credentials.
// It does not control whether the XSRF header is added.
withCredentials: false, // default
// `adapter` allows custom handling of requests which makes testing easier.
// Return a promise and supply a valid response (see lib/adapters/README.md)
adapter: function (config) {
/* ... */
},
// Also, you can set the name of the built-in adapter, or provide an array with their names
// to choose the first available in the environment
adapter: 'xhr', // 'fetch' | 'http' | ['xhr', 'http', 'fetch']
// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
// If `auth` is omitted, the Node.js HTTP and fetch adapters can read
// HTTP Basic auth credentials from the request URL, for example
// `https://user:pass@example.com`. Axios decodes percent-encoded URL
// credentials, and `auth` takes precedence over URL-embedded credentials.
// The Node.js HTTP adapter preserves Basic auth on same-origin redirects
// and strips it on cross-origin redirects.
// Please note that only HTTP Basic auth is configurable through this parameter.
// For Bearer tokens and such, use `Authorization` custom headers instead.
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
// browser only: 'blob'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
// Note: Ignored for `responseType` of 'stream' or client-side requests
// options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',
// 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',
// 'utf8', 'UTF8', 'utf16le', 'UTF16LE'
responseEncoding: 'utf8', // default
// `xsrfCookieName` is the name of the cookie to use as a value for the xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `withXSRFToken` defines whether to send the XSRF header in browser requests.
// `undefined` (default) - set XSRF header only for the same origin requests
// `true` - always set XSRF header, including for cross-origin requests
// `false` - never set XSRF header
// function - resolve with custom logic; receives the internal config object
withXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),
// `withXSRFToken` controls whether Axios reads the XSRF cookie and sets the XSRF header.
// - `undefined` (default): the XSRF header is set only for same-origin requests.
// - `true`: attempt to set the XSRF header for all requests (including cross-origin).
// - `false`: never set the XSRF header.
// - function: a callback that receives the request `config` and returns `true`,
// `false`, or `undefined` to decide per-request behavior.
//
// Note about `withCredentials`: `withCredentials` controls whether cross-site
// requests include credentials (cookies and HTTP auth). In older Axios versions,
// setting `withCredentials: true` implicitly caused Axios to set the XSRF header
// for cross-origin requests. Newer Axios separates these concerns: to allow the
// XSRF header to be sent for cross-origin requests you should set both
// `withCredentials: true` and `withXSRFToken: true`.
//
// Example:
// axios.get('/user', { withCredentials: true, withXSRFToken: true });
// `onUploadProgress` allows handling of progress events for uploads
// browser & node.js
onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
// Do whatever you want with the Axios progress event
},
// `onDownloadProgress` allows handling of progress events for downloads
// browser & node.js
onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
// Do whatever you want with the Axios progress event
},
// `maxContentLength` defines the max size of the response content in bytes.
// It is enforced by the Node.js HTTP adapter and the fetch adapter.
maxContentLength: 2000,
// `maxBodyLength` defines the max size of the request content in bytes.
// It is enforced by the Node.js HTTP adapter and the fetch adapter when the body length can be determined.
maxBodyLength: 2000,
// `redact` masks matching config keys when AxiosError#toJSON() is called.
// Matching is case-insensitive and recursive. It does not change the request.
redact: ['authorization', 'password'],
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` or is set to
// `null`, Axios resolves the promise; otherwise, Axios rejects it.
// Explicit `validateStatus: undefined` resolves every status by default for
// backward compatibility. Set `transitional.validateStatusUndefinedResolves`
// to `false` to make explicit `undefined` behave as if this option was omitted.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` defines the maximum number of redirects to follow in node.js.
// If set to 0, Axios follows no redirects.
maxRedirects: 21, // default
// `sensitiveHeaders` (Node only option) lists custom secret-bearing headers
// (such as `X-API-Key`) to remove from cross-origin redirects. Matching is
// case-insensitive. Same-origin redirects keep these headers. If
// `maxRedirects` is 0, this option is not used.
sensitiveHeaders: ['X-API-Key'],
// `beforeRedirect` defines a function that Axios calls before redirect.
// Use this to adjust the request options upon redirecting,
// to inspect the latest response headers,
// or to cancel the request by throwing an error
// If maxRedirects is set to 0, `beforeRedirect` is not used.
beforeRedirect: (options, { headers }) => {
if (
options.hostname === "example.com" &&
options.protocol === "https:"
) {
options.auth = "user:password";
}
},
// Security note:
// The `beforeRedirect` hook runs after sensitive headers are stripped during redirects.
// `follow-redirects` removes credentials on protocol downgrades
// (HTTPS to HTTP). Because `beforeRedirect` runs after that step,
// re-injecting credentials without checking the destination can expose
// sensitive data. Only add credentials for trusted HTTPS destinations.
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
//
// Security: when `socketPath` is set, hostname/port of the URL are ignored,
// which bypasses hostname-based SSRF protections. Never derive `socketPath`
// from untrusted input. Use `allowedSocketPaths` (below) to restrict accepted
// socket paths for defense-in-depth.
socketPath: null, // default
// `allowedSocketPaths` restricts which `socketPath` values are accepted.
// Accepts a string or array of strings. Entries and the incoming socketPath
// are compared after path.resolve(). A mismatch throws AxiosError with code
// `ERR_BAD_OPTION_VALUE`. When null/undefined, no restriction is applied.
allowedSocketPaths: null, // default
// `transport` determines the transport method for the request.
// If defined, Axios uses it. Otherwise, if `maxRedirects` is 0,
// Axios uses the default `http` or `https` library, depending on the protocol specified in `protocol`.
// Otherwise, Axios uses the `httpFollow` or `httpsFollow` library, again depending on the protocol,
// which can handle redirects.
transport: undefined, // default
// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
// and https requests, respectively, in node.js. This allows options to be added like
// `keepAlive` that are not enabled by default before Node.js v19.0.0. After Node.js
// v19.0.0, you no longer need to customize the agent to enable `keepAlive` because
// `http.globalAgent` has `keepAlive` enabled by default.
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the hostname, port, and protocol of the proxy server.
// You can also define your proxy using the conventional `http_proxy` and
// `https_proxy` environment variables. If you are using environment variables
// for your proxy configuration, you can also define a `no_proxy` environment
// variable as a comma-separated list of domains that should not be proxied.
// Use `false` to disable proxies, ignoring environment variables.
// On Node.js versions with native environment proxy support, axios defers
// environment proxy handling to Node when the selected agent has `proxyEnv`
// enabled, including processes started with `NODE_USE_ENV_PROXY=1`,
// `--use-env-proxy`, or `NODE_OPTIONS=--use-env-proxy`. Custom agents without
// `proxyEnv` continue to use axios environment proxy resolution. Explicit
// `proxy` config is still handled by axios.
// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
// supplies credentials.
// For `http://` targets, axios sends the request to the proxy in
// forward-proxy mode and stamps `Proxy-Authorization` onto the request
// headers (overwriting any user-supplied `Proxy-Authorization` header).
// For `https://` targets, axios establishes a CONNECT tunnel through the
// proxy and performs TLS end-to-end with the origin; `Proxy-Authorization`
// is sent on the CONNECT request only, never on the wrapped TLS request,
// so the proxy never sees the URL, headers, or body. Axios forwards
// `httpsAgent` TLS options such as `ca`, `cert`, `key`, and
// `rejectUnauthorized` to the generated tunneling agent, so they still apply
// to the origin TLS connection.
// If you supply an `HttpsProxyAgent`, axios leaves tunneling to that agent.
// If the proxy server uses HTTPS, then you must set the protocol to `https`.
// A user-supplied `Host` header in `headers` is preserved when forwarding
// through a proxy (case-insensitive match on `host`/`Host`/`HOST`); this
// lets you target a virtual host that differs from the request URL, for
// example, hitting `127.0.0.1:4000` while having the proxy treat the
// request as `example.com`. If no `Host` header is supplied, axios
// defaults it to the request URL's `hostname:port` as before. The Host
// header is only set in forward-proxy mode (HTTP targets); for HTTPS
// tunneling the Host header is sent inside the TLS connection, not seen
// by the proxy.
proxy: {
protocol: 'https',
host: '127.0.0.1',
// hostname: '127.0.0.1' // Takes precedence over 'host' if both are defined
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` specifies a cancel token that can be used to cancel the request
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
}),
// an alternative way to cancel Axios requests using AbortController
signal: new AbortController().signal,
// `decompress` indicates whether or not the response body should be decompressed
// automatically. If set to `true` will also remove the 'content-encoding' header
// from the responses objects of all decompressed responses
// Axios supports gzip, deflate, brotli, and zstd when the current Node.js
// runtime provides the corresponding zlib decompressor.
// - Node only (XHR cannot turn off decompression)
decompress: true, // default
// `insecureHTTPParser` boolean.
// Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
// This may allow interoperability with non-conformant HTTP implementations.
// Using the insecure parser should be avoided.
// see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
// see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
insecureHTTPParser: undefined, // default
// transitional options for backward compatibility that may be removed in the newer versions
transitional: {
// silent JSON parsing mode
// `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
// `false` - throw SyntaxError if JSON parsing failed
// Important: this option only takes effect when `responseType` is explicitly set to 'json'.
// When `responseType` is omitted (defaults to no value), axios uses `forcedJSONParsing`
// to attempt JSON parsing, but will silently return the raw string on failure regardless
// of this setting. To have invalid JSON throw errors, use:
// { responseType: 'json', transitional: { silentJSONParsing: false } }
silentJSONParsing: true, // default value for the current Axios version
// try to parse the response string as JSON even if `responseType` is not 'json'
forcedJSONParsing: true,
// throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
clarifyTimeoutError: false,
// keep explicit `validateStatus: undefined` resolving every response status
// for backward compatibility. Set to false to make explicit undefined behave
// as if validateStatus was omitted.
validateStatusUndefinedResolves: true,
// advertise `zstd` in the default Accept-Encoding header when the current
// Node.js runtime supports zstd decompression. Axios still decompresses
// zstd responses when support exists and `decompress` is true.
advertiseZstdAcceptEncoding: false,
// use the legacy interceptor request/response ordering
legacyInterceptorReqResOrdering: true, // default
},
env: {
// The FormData class to be used to automatically serialize the payload into a FormData object
FormData: window?.FormData || global?.FormData
},
formSerializer: {
visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form values
dots: boolean; // use dots instead of brackets format
metaTokens: boolean; // keep special endings like {} in parameter key
indexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes
maxDepth: 100; // maximum object nesting depth; throws AxiosError (ERR_FORM_DATA_DEPTH_EXCEEDED) if exceeded. Set to Infinity to disable.
},
// http adapter only (node.js)
maxRate: [
100 * 1024, // 100KB/s upload limit,
100 * 1024 // 100KB/s download limit
]
}
```
For custom secret-bearing headers in Node.js, list them in `sensitiveHeaders` so Axios removes them when following a redirect to another origin:
```js
axios.get('https://api.example.com/users', {
headers: { 'X-API-Key': 'secret' },
sensitiveHeaders: ['X-API-Key'],
});
```
### Strict RFC 3986 percent-encoding for query params
By default, axios decodes `%3A`, `%24`, `%2C` and `%20` back to `:`, `$`, `,` and `+` for readability (the `+` follows the `application/x-www-form-urlencoded` convention for spaces in query strings). These characters are valid in a query component under [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3.4), so the default output is correct, but some backends require strict percent-encoding and reject the readable form.
Override the default encoder via `paramsSerializer.encode`:
```js
// Per-request: emit strict RFC 3986 percent-encoding for query values
axios.get('/foo', {
params: { filter: JSON.stringify({ startedAt: '2026-01-23' }) },
paramsSerializer: { encode: encodeURIComponent },
});
// Or set it on the instance defaults
const client = axios.create({
paramsSerializer: { encode: encodeURIComponent },
});
```
## HTTP/2 support
Axios has experimental HTTP/2 support in the Node.js HTTP adapter.
Support depends on the runtime environment and Node.js version. Redirects and some adapter behavior may differ from HTTP/1.1.
Options like `httpVersion` and `http2Options` are adapter-specific and may not work the same way in every environment.
If you need HTTP/2, check runtime support or use a custom adapter.
## Response schema
The response to a request contains the following information.
```js
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the HTTP headers that the server responded with
// All header names are lowercase and can be accessed using the bracket notation.
// Example: `response.headers['content-type']`
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {},
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}
```
When using `then`, you receive the response like this:
```js
const response = await axios.get('/user/12345');
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
```
When using `catch`, or passing a [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) as the second parameter of `then`, read the response from the `error` object. See [Handling errors](#handling-errors).
## Config defaults
Config defaults apply to every request.
### Global axios defaults
```js
axios.defaults.baseURL = 'https://api.example.com';
// Important: If you use axios with multiple domains, Axios sends AUTH_TOKEN to all of them.
// See below for an example using Custom instance defaults instead.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
```
### Custom instance defaults
```js
// Set config defaults when creating the instance
const instance = axios.create({
baseURL: 'https://api.example.com',
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
```
### Config order of precedence
Axios merges config in this order: library defaults from [lib/defaults/index.js](https://github.com/axios/axios/blob/main/lib/defaults/index.js#L49), the instance `defaults` property, and the request `config` argument. Later values take precedence over earlier ones.
Some options are request-specific and are only taken from the request `config`. `data` is one of those options: axios does not inherit or deep-merge request bodies from global or instance defaults. If every request needs shared body fields, add them with a request interceptor or `transformRequest`, and scope that logic carefully so sensitive values are not sent to the wrong endpoint.
```js
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();
// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
timeout: 5000,
});
```
## Interceptors
You can intercept requests or responses before methods like `.get()` or `.post()`
resolve their promises (before code inside `then` or `catch`, or after `await`)
```js
const instance = axios.create();
// Add a request interceptor
instance.interceptors.request.use(
function (config) {
// Do something before the request is sent
return config;
},
function (error) {
// Do something with the request error
return Promise.reject(error);
}
);
// Add a response interceptor
instance.interceptors.response.use(
function (response) {
// Any status code that lies within the range of 2xx causes this function to trigger
// Do something with response data
return response;
},
function (error) {
// Any status codes that fall outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
}
);
```
If you need to remove an interceptor later you can.
```js
const instance = axios.create();
const myInterceptor = instance.interceptors.request.use(function () {
/*...*/
});
instance.interceptors.request.eject(myInterceptor);
```
You can also clear all interceptors for requests or responses.
```js
const instance = axios.create();
instance.interceptors.request.use(function () {
/*...*/
});
instance.interceptors.request.clear(); // Removes interceptors from requests
instance.interceptors.response.use(function () {
/*...*/
});
instance.interceptors.response.clear(); // Removes interceptors from responses
```
You can add interceptors to a custom instance of axios.
```js
const instance = axios.create();
instance.interceptors.request.use(function () {
/*...*/
});
```
When you add request interceptors, they are presumed to be asynchronous by default. This can cause a delay
in the execution of your axios request when the main thread is blocked (a promise is created under the hood for
the interceptor and your request gets put at the bottom of the call stack). If your request interceptors are synchronous you can add a flag
to the options object that will tell axios to run the code synchronously and avoid any delays in request execution.
```js
axios.interceptors.request.use(
function (config) {
config.headers.test = 'I am only a header!';
return config;
},
null,
{ synchronous: true }
);
```
If you want to execute a particular interceptor based on a runtime check,
you can add a `runWhen` function to the options object. The request interceptor will not run **if and only if** the return
of `runWhen` is `false`. Axios calls the function with the config
object (don't forget that you can bind your own arguments to it as well.) This can be handy when you have an
asynchronous request interceptor that only needs to run at certain times.
```js
function onGetCall(config) {
return config.method === 'get';
}
axios.interceptors.request.use(
function (config) {
config.headers.test = 'special get headers';
return config;
},
null,
{ runWhen: onGetCall }
);
```
> Note: The options parameter (with `synchronous` and `runWhen` properties) is only supported for request interceptors at the moment.
### Interceptor execution order
Request and response interceptors use different execution orders.
Request interceptors run in reverse order (LIFO: last in, first out). The last interceptor added runs first.
Response interceptors run in the order they were added (FIFO: first in, first out). The first interceptor added runs first.
Example:
```js
const instance = axios.create();
const interceptor = (id) => (base) => {
console.log(id);
return base;
};
instance.interceptors.request.use(interceptor('Request Interceptor 1'));
instance.interceptors.request.use(interceptor('Request Interceptor 2'));
instance.interceptors.request.use(interceptor('Request Interceptor 3'));
instance.interceptors.response.use(interceptor('Response Interceptor 1'));
instance.interceptors.response.use(interceptor('Response Interceptor 2'));
instance.interceptors.response.use(interceptor('Response Interceptor 3'));
// Console output:
// Request Interceptor 3
// Request Interceptor 2
// Request Interceptor 1
// [HTTP request is made]
// Response Interceptor 1
// Response Interceptor 2
// Response Interceptor 3
```
### Multiple interceptors
When a response is fulfilled and multiple response interceptors are registered:
- Each interceptor runs in registration order.
- Each interceptor receives the result from the previous interceptor.
- The chain returns the result from the last interceptor.
- If a fulfillment interceptor throws, Axios skips the next fulfillment interceptor and calls the next rejection interceptor.
- After the error is caught, later fulfillment interceptors run again, just like in a promise chain.
Read [the interceptor tests](./test/specs/interceptors.spec.js) to see all this in code.
## Error types
Axios error messages include details that can help you debug the request.
Axios errors use this structure:
| Property | Definition |
| -------- | ---------- |
| message | A quick summary of the error message and the status it failed with. |
| name | This defines where the error originated from. For axios, it will always be an 'AxiosError'. |
| stack | Stack trace for the error. |
| config | An axios config object with specific instance configurations defined by the user from when the request was made |
| code | Axios error code. The table below lists internal Axios error codes. |
| status | HTTP response status code. See [here](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) for common HTTP response status code meanings.
These are the internal Axios error codes:
| Code | Definition |
| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ERR_BAD_OPTION_VALUE | Invalid value provided in axios configuration. |
| ERR_BAD_OPTION | Invalid option provided in axios configuration. |
| ERR_NOT_SUPPORT | Feature or method not supported in the current axios environment. |
| ERR_DEPRECATED | Deprecated feature or method used in axios. |
| ERR_INVALID_URL | Invalid URL provided for axios request. |
| ECONNABORTED | Typically indicates that the request has been timed out (unless `transitional.clarifyTimeoutError` is set) or aborted by the browser or its plugin. |
| ERR_CANCELED | The user explicitly canceled the request with an AbortSignal or CancelToken. |
| ETIMEDOUT | Request timed out after exceeding the configured Axios timeout. Set `transitional.clarifyTimeoutError` to `true`; otherwise Axios throws a generic `ECONNABORTED` error. |
| ERR_NETWORK | Network-related issue. In the browser, this error can also be caused by a [CORS](https://developer.mozilla.org/ru/docs/Web/HTTP/Guides/CORS) or [Mixed Content](https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content) policy violation. The browser does not allow the JS code to clarify the real reason for the error caused by security issues, so please check the console. |
| ERR_FR_TOO_MANY_REDIRECTS | Request exceeded the configured maximum number of redirects. |
| ERR_BAD_RESPONSE | Response cannot be parsed properly or is in an unexpected format. Usually related to a response with `5xx` status code. |
| ERR_BAD_REQUEST | The request has an unexpected format or is missing required parameters. Usually related to a response with `4xx` status code. |
## Handling errors
By default, Axios rejects responses with status codes outside the 2xx range.
```js
axios.get('/user/12345').catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
```
Use `validateStatus` to override the default condition (`status >= 200 && status < 300`) and choose which HTTP status codes should reject.
```js
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Resolve only if the status code is less than 500
},
});
```
By default, explicit `validateStatus: undefined` keeps legacy behavior and resolves every response status because `transitional.validateStatusUndefinedResolves` defaults to `true`. Set it to `false` to make explicit `validateStatus: undefined` behave like the option was omitted, so Axios uses the configured/default validator and rejects non-2xx responses by default.
`validateStatus: null` still accepts every response status. If you disable the transitional behavior and intentionally want all statuses to resolve, use `null` or `() => true`.
```js
axios.get('/user/12345', {
validateStatus: undefined,
transitional: {
validateStatusUndefinedResolves: false,
},
});
```
Use `toJSON` to get more information about the HTTP error.
```js
axios.get('/user/12345').catch(function (error) {
console.log(error.toJSON());
});
```
To avoid logging secrets from `error.config`, pass a `redact` array in the request config. Matching config keys are masked case-insensitively at any depth when `AxiosError#toJSON()` is called.
```js
axios
.get('/user/12345', {
headers: { Authorization: 'Bearer token' },
redact: ['authorization'],
})
.catch(function (error) {
console.log(error.toJSON().config.headers.Authorization); // [REDACTED ****]
});
```
## Handling timeouts
```js
async function fetchWithTimeout() {
try {
const response = await axios.get('https://example.com/data', {
timeout: 5000, // 5 seconds
transitional: {
// set to true if you prefer ETIMEDOUT over ECONNABORTED
clarifyTimeoutError: false,
},
});
console.log('Response:', response.data);
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
console.error('Request timed out. Please try again.');
return;
}
console.error('Axios error:', error.message);
return;
}
console.error('Unexpected error:', error);
}
}
```
## Cancellation
### AbortController
Since `v0.22.0`, Axios supports AbortController:
```js
const controller = new AbortController();
axios
.get('/foo/bar', {
signal: controller.signal,
})
.then(function (response) {
//...
});
// cancel the request
controller.abort();
```
### CancelToken (deprecated)
You can also cancel a request using a _CancelToken_.
> The axios cancel token API is based on the withdrawn [cancellable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
> This API is deprecated since v0.22.0 and should not be used in new projects.
Create a cancel token with the `CancelToken.source` factory:
```js
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios
.get('/user/12345', {
cancelToken: source.token,
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post(
'/user/12345',
{
name: 'new name',
},
{
cancelToken: source.token,
}
);
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
```
You can also pass an executor function to the `CancelToken` constructor:
```js
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
}),
});
// cancel the request
cancel();
```
`CancelToken` also exposes low-level helpers for legacy integrations:
```js
const source = axios.CancelToken.source();
const listener = (cancel) => {
console.log(cancel.message);
};
source.token.subscribe(listener);
const signal = source.token.toAbortSignal();
// Pass `signal` to APIs that accept AbortSignal.
source.cancel('Operation canceled by the user.');
source.token.unsubscribe(listener);
```
Canceled requests reject with `axios.CanceledError`. The legacy `axios.Cancel` export is an alias of `axios.CanceledError`, and cancellation errors include `__CANCEL__` for `axios.isCancel` compatibility.
> Note: You can cancel several requests with the same cancel token or abort controller.
> If a cancellation token is already cancelled when an Axios request starts, Axios cancels the request immediately without making a real request.
> During the transition period, you can use both cancellation APIs, even for the same request:
```js
const controller = new AbortController();
const source = axios.CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token,
signal: controller.signal,
});
controller.abort();
source.cancel('Operation canceled by the user.');
```
## Using `application/x-www-form-urlencoded` format
### URLSearchParams
By default, axios serializes JavaScript objects to `JSON`. To send data as [`application/x-www-form-urlencoded`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST), use the [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) API. It works in most browsers and in [Node](https://nodejs.org/api/url.html#url_class_urlsearchparams) v10 and later.
```js
const params = new URLSearchParams({ foo: 'bar' });
params.append('extraparam', 'value');
axios.post('/foo', params);
```
### Query string (older browsers)
For very old browsers, use a [polyfill](https://github.com/WebReflection/url-search-params) and make sure it patches the global environment.
Alternatively, you can encode data using the [`qs`](https://github.com/ljharb/qs) library:
```js
const qs = require('qs');
axios.post('/foo', qs.stringify({ bar: 123 }));
```
With ES modules:
```js
import qs from 'qs';
const data = { bar: 123 };
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);
```
### Older Node.js versions
For older Node.js engines, use the [`querystring`](https://nodejs.org/api/querystring.html) module:
```js
const querystring = require('querystring');
axios.post('https://something.com/', querystring.stringify({ foo: 'bar' }));
```
You can also use the [`qs`](https://github.com/ljharb/qs) library.
> Note: The `qs` library is preferable if you need to stringify nested objects, as the `querystring` method has [known issues](https://github.com/nodejs/node-v0.x-archive/issues/1665) with that use case.
### Automatic serialization to URLSearchParams
Axios automatically serializes the data object to urlencoded format if the content-type header is set to "application/x-www-form-urlencoded".
```js
const data = {
x: 1,
arr: [1, 2, 3],
arr2: [1, [2], 3],
users: [
{ name: 'Peter', surname: 'Griffin' },
{ name: 'Thomas', surname: 'Anderson' },
],
};
await axios.postForm('https://postman-echo.com/post', data, {
headers: { 'content-type': 'application/x-www-form-urlencoded' },
});
```
The server receives these fields:
```js
{
x: '1',
'arr[]': [ '1', '2', '3' ],
'arr2[0]': '1',
'arr2[1][0]': '2',
'arr2[2]': '3',
'arr3[]': [ '1', '2', '3' ],
'users[0][name]': 'Peter',
'users[0][surname]': 'griffin',
'users[1][name]': 'Thomas',
'users[1][surname]': 'Anderson'
}
```
If your backend body parser, such as `body-parser` for `express.js`, supports nested object decoding, the server receives the same object structure:
```js
const app = express();
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/', function (req, res, next) {
// echo body as JSON
res.send(JSON.stringify(req.body));
});
server = app.listen(3000);
```
## Using `multipart/form-data` format
### FormData
To send data as `multipart/form-data`, pass a FormData instance as the payload.
You do not need to set the `Content-Type` header. Axios detects it from the payload type.
For browser, web worker, and React Native `FormData`, leave `Content-Type` unset so the runtime can add the multipart boundary.
```js
const formData = new FormData();
formData.append('foo', 'bar');
axios.post('https://httpbin.org/post', formData);
```
In node.js, use the [`form-data`](https://github.com/form-data/form-data) library:
```js
const FormData = require('form-data');
const form = new FormData();
form.append('my_field', 'my value');
form.append('my_buffer', Buffer.alloc(10));
form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
axios.post('https://example.com', form);
```
In node.js, when a `FormData` object provides `getHeaders()`, axios copies all returned headers by default for v1 compatibility. If the `FormData` object is custom or not fully trusted, set `formDataHeaderPolicy: 'content-only'` to copy only `Content-Type` and `Content-Length`, and set any other request headers explicitly with the request `headers` config.
### Automatic serialization to FormData
Since `v0.27.0`, Axios can serialize an object to FormData if the request `Content-Type`
header is set to `multipart/form-data`.
This request submits data as FormData in browsers and Node.js:
```js
import axios from 'axios';
axios
.post(
'https://httpbin.org/post',
{ x: 1 },
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
)
.then(({ data }) => console.log(data));
```
The Node.js build uses the [`form-data`](https://github.com/form-data/form-data) polyfill by default.
You can override the FormData class with the `env.FormData` config option, but most applications do not need this:
```js
const axios = require('axios');
var FormData = require('form-data');
axios
.post(
'https://httpbin.org/post',
{ x: 1, buf: Buffer.alloc(10) },
{
headers: {
'Content-Type': 'multipart/form-data',
},
}
)
.then(({ data }) => console.log(data));
```
The Axios FormData serializer supports these special endings:
- `{}` - serialize the value with JSON.stringify
- `[]` - unwrap the array-like object as separate fields with the same key
> Note: Arrays and FileList objects are unwrapped by default.
FormData serializer supports additional options via `config.formSerializer: object` property to handle rare cases:
- `visitor: Function` - user-defined visitor function that Axios calls recursively to serialize the data object
to a `FormData` object by following custom rules.
- `dots: boolean = false` - use dot notation instead of brackets to serialize arrays and objects;
- `metaTokens: boolean = true` - add the special ending (e.g `user{}: '{"name": "John"}'`) in the FormData key.
A backend body parser can use this meta-information to parse the value as JSON.
- `indexes: null|false|true = false` - controls how Axios adds indexes to unwrapped keys of `flat` array-like objects.
- `null` - don't add brackets (`arr: 1`, `arr: 2`, `arr: 3`)
- `false`(default) - add empty brackets (`arr[]: 1`, `arr[]: 2`, `arr[]: 3`)
- `true` - add brackets with indexes (`arr[0]: 1`, `arr[1]: 2`, `arr[2]: 3`)
- `maxDepth: number = 100` - maximum object nesting depth the serializer will recurse into. If the
input object exceeds this depth, an `AxiosError` with `code: 'ERR_FORM_DATA_DEPTH_EXCEEDED'` is
thrown instead of overflowing the call stack. This protects server applications from DoS
attacks via deeply nested payloads. Set to `Infinity` to disable the limit and restore pre-fix behaviour.
- `Blob: typeof Blob` - Blob constructor used when converting ArrayBuffer-like values for spec-compliant
`FormData`. Override it only for runtimes that provide a compatible `Blob` constructor under a
different binding.
```js
// Raise the limit for a schema that genuinely nests deeper than 100 levels:
axios.postForm('/api', data, { formSerializer: { maxDepth: 200 } });
// Same protection applies to params serialization:
axios.get('/api', { params: data, paramsSerializer: { maxDepth: 200 } });
```
Given this object:
```js
const obj = {
x: 1,
arr: [1, 2, 3],
arr2: [1, [2], 3],
users: [
{ name: 'Peter', surname: 'Griffin' },
{ name: 'Thomas', surname: 'Anderson' },
],
'obj2{}': [{ x: 1 }],
};
```
The Axios serializer appends these fields:
```js
const formData = new FormData();
formData.append('x', '1');
formData.append('arr[]', '1');
formData.append('arr[]', '2');
formData.append('arr[]', '3');
formData.append('arr2[0]', '1');
formData.append('arr2[1][0]', '2');
formData.append('arr2[2]', '3');
formData.append('users[0][name]', 'Peter');
formData.append('users[0][surname]', 'Griffin');
formData.append('users[1][name]', 'Thomas');
formData.append('users[1][surname]', 'Anderson');
formData.append('obj2{}', '[{"x":1}]');
```
Axios supports `postForm`, `putForm`, and `patchForm` as shortcuts for the matching HTTP methods with the `Content-Type` header preset to `multipart/form-data`.
## Posting files
Submit a single file:
```js
await axios.postForm('https://httpbin.org/post', {
myVar: 'foo',
file: document.querySelector('#fileInput').files[0],
});
```
or multiple files as `multipart/form-data`:
```js
await axios.postForm('https://httpbin.org/post', {
'files[]': document.querySelector('#fileInput').files,
});
```
`FileList` object can be passed directly:
```js
await axios.postForm('https://httpbin.org/post', document.querySelector('#fileInput').files);
```
Axios sends all files with the same field name: `files[]`.
## HTML form posting (browser)
Pass an HTML Form element as a payload to submit it as `multipart/form-data` content.
```js
await axios.postForm('https://httpbin.org/post', document.querySelector('#htmlForm'));
```
`FormData` and `HTMLForm` objects can also be posted as `JSON` by explicitly setting the `Content-Type` header to `application/json`:
```js
await axios.post('https://httpbin.org/post', document.querySelector('#htmlForm'), {
headers: {
'Content-Type': 'application/json',
},
});
```
For example, the Form
```html
<form id="form">
<input type="text" name="foo" value="1" />
<input type="text" name="deep.prop" value="2" />
<input type="text" name="deep prop spaced" value="3" />
<input type="text" name="baz" value="4" />
<input type="text" name="baz" value="5" />
<select name="user.age">
<option value="value1">Value 1</option>
<option value="value2" selected>Value 2</option>
<option value="value3">Value 3</option>
</select>
<input type="submit" value="Save" />
</form>
```
submits this JSON object:
```js
{
"foo": "1",
"deep": {
"prop": {
"spaced": "3"
}
},
"baz": [
"4",
"5"
],
"user": {
"age": "value2"
}
}
```
Sending `Blobs`/`Files` as JSON (`base64`) is not currently supported.
## Progress capturing
Axios can capture request upload and download progress in browsers and Node.js.
Progress events are limited to `3` times per second.
```js
await axios.post(url, data, {
onUploadProgress: function (axiosProgressEvent) {
/*{
loaded: number;
total?: number;
progress?: number; // in range [0..1]
bytes: number; // how many bytes have been transferred since the last trigger (delta)
estimated?: number; // estimated time in seconds
rate?: number; // upload speed in bytes
upload: true; // upload sign
}*/
},
onDownloadProgress: function (axiosProgressEvent) {
/*{
loaded: number;
total?: number;
progress?: number;
bytes: number;
estimated?: number;
rate?: number; // download speed in bytes
download: true; // download sign
}*/
},
});
```
You can also track stream upload/download progress in node.js:
```js
const { data } = await axios.post(SERVER_URL, readableStream, {
onUploadProgress: ({ progress }) => {
console.log((progress * 100).toFixed(2));
},
headers: {
'Content-Length': contentLength,
},
maxRedirects: 0, // avoid buffering the entire stream
});
```
> Note:
> Capturing FormData upload progress is not currently supported in node.js environments.
> Warning:
> Set `maxRedirects: 0` when uploading streams in node.js.
> The follow-redirects package buffers the entire stream in RAM and does not follow the "backpressure" algorithm.
## Rate limiting
Download and upload rate limits can only be set for the http adapter (node.js):
```js
const { data } = await axios.post(LOCAL_SERVER_URL, myBuffer, {
onUploadProgress: ({ progress, rate }) => {
console.log(`Upload [${(progress * 100).toFixed(2)}%]: ${(rate / 1024).toFixed(2)}KB/s`);
},
maxRate: [100 * 1024], // 100KB/s limit
});
```
## AxiosHeaders
Axios includes an `AxiosHeaders` class for working with headers through a Map-like API.
HTTP header names are case-insensitive, but Axios keeps the original header case for style and for servers that incorrectly depend on case.
Directly manipulating the headers object still works, but it is deprecated.
### Working with headers
An `AxiosHeaders` instance can contain several internal value types that control setting and merging.
Axios gets the final headers object with string values by calling `toJSON`.
> Note: By JSON here we mean an object consisting only of string values intended to be sent over the network.
The header value can be one of the following types:
- `string` - normal string value sent to the server
- `null` - skip header when rendering to JSON
- `false` - skip header when rendering to JSON. Also indicates that the `set` method must be called with `rewrite` set to `true`
to overwrite this value (Axios uses this internally to allow users to opt out of installing certain headers like `User-Agent` or `Content-Type`)
- `undefined` - value is not set
> Note: The header value is considered set if it is not equal to undefined.
The headers object is always initialized inside interceptors and transformers:
```ts
axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
request.headers.set('My-header', 'value');
request.headers.set({
'My-set-header1': 'my-set-value1',
'My-set-header2': 'my-set-value2',
});
request.headers.set('User-Agent', false); // prevent Axios from setting this header later
request.headers.setContentType('text/plain');
request.headers['My-set-header2'] = 'newValue'; // direct access is deprecated
return request;
});
```
You can iterate over an `AxiosHeaders` instance using a `for...of` statement:
```js
const headers = new AxiosHeaders({
foo: '1',
bar: '2',
baz: '3',
});
for (const [header, value] of headers) {
console.log(header, value);
}
// foo 1
// bar 2
// baz 3
```
### Preserving a specific header case
Header names are case-insensitive, but `AxiosHeaders` keeps the case of the first matching key it sees.
If you need a specific case for non-standard case-sensitive servers, define a case preset with `undefined` and then set the value later:
```js
const api = axios.create();
api.defaults.headers.common = {
'content-type': undefined,
accept: undefined,
};
await api.put(url, data, {
headers: {
'Content-Type': 'application/octet-stream',
Accept: 'application/json',
},
});
```
You can also compose the same behavior with `AxiosHeaders.concat`:
```js
const headers = axios.AxiosHeaders.concat(
{ 'content-type': undefined },
{ 'Content-Type': 'application/octet-stream' }
);
await axios.put(url, data, { headers });
```
### new AxiosHeaders(headers?)
Constructs a new `AxiosHeaders` instance.
```
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
```
If the headers object is a string, Axios parses it as raw HTTP headers.
```js
const headers = new AxiosHeaders(`
Host: www.bing.com
User-Agent: curl/7.54.0
Accept: */*`);
console.log(headers);
// Object [AxiosHeaders] {
// host: 'www.bing.com',
// 'user-agent': 'curl/7.54.0',
// accept: '*/*'
// }
```
### AxiosHeaders#set
```ts
set(headerName, value: Axios, rewrite?: boolean);
set(headerName, value, rewrite?: (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean);
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean);
set(headers?: Iterable<[string, AxiosHeaderValue]>, rewrite?: boolean);
```
The `rewrite` argument controls the overwriting behavior:
- `false` - do not overwrite if the header's value is set (is not `undefined`)
- `undefined` (default) - overwrite the header unless its value is set to `false`
- `true` - rewrite anyway
The option can also accept a user-defined function that determines whether to overwrite the value.
Empty or whitespace-only header names are ignored.
Iterable key/value pairs, such as a `Map`, are accepted:
```js
const headers = new AxiosHeaders();
headers.set(
new Map([
['X-Trace-Id', 'abc123'],
['Accept', 'application/json'],
])
);
```
Returns `this`.
### AxiosHeaders#get(header)
```
get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
```
Returns the internal value of the header. It can take an extra argument to parse the header's value with `RegExp.exec`,
matcher function or internal key-value parser.
```ts
const headers = new AxiosHeaders({
'Content-Type': 'multipart/form-data; boundary=Asrf456BGe4h',
});
console.log(headers.get('Content-Type'));
// multipart/form-data; boundary=Asrf456BGe4h
console.log(headers.get('Content-Type', true)); // parse key-value pairs from a string separated with \s,;= delimiters:
// [Object: null prototype] {
// 'multipart/form-data': undefined,
// boundary: 'Asrf456BGe4h'
// }
console.log(
headers.get('Content-Type', (value, name, headers) => {
return String(value).replace(/a/g, 'ZZZ');
})
);
// multipZZZrt/form-dZZZtZZZ; boundZZZry=Asrf456BGe4h
console.log(headers.get('Content-Type', /boundary=(\w+)/)?.[0]);
// boundary=Asrf456BGe4h
```
Returns the value of the header.
### AxiosHeaders#has(header, matcher?)
```
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
```
Returns `true` if the header is set (has no `undefined` value).
### AxiosHeaders#delete(header, matcher?)
```
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
```
Returns `true` if at least one header has been removed.
### AxiosHeaders#clear(matcher?)
```
clear(matcher?: AxiosHeaderMatcher): boolean;
```
Removes all headers.
Unlike the `delete` method matcher, this optional matcher matches the header name rather than the value.
```ts
const headers = new AxiosHeaders({
foo: '1',
'x-foo': '2',
'x-bar': '3',
});
console.log(headers.clear(/^x-/)); // true
console.log(headers.toJSON()); // [Object: null prototype] { foo: '1' }
```
Returns `true` if at least one header has been cleared.
### AxiosHeaders#normalize(format);
If the headers object was changed directly, it can have duplicates with the same name but in different cases.
This method normalizes the headers object by combining duplicate keys into one.
Axios uses this method internally after calling each interceptor.
Set `format` to true for converting header names to lowercase and capitalizing the initial letters (`cOntEnt-type` => `Content-Type`)
```js
const headers = new AxiosHeaders({
foo: '1',
});
headers.Foo = '2';
headers.FOO = '3';
console.log(headers.toJSON()); // [Object: null prototype] { foo: '1', Foo: '2', FOO: '3' }
console.log(headers.normalize().toJSON()); // [Object: null prototype] { foo: '3' }
console.log(headers.normalize(true).toJSON()); // [Object: null prototype] { Foo: '3' }
```
Returns `this`.
### AxiosHeaders#concat(...targets)
```
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
```
Merges the instance with targets into a new `AxiosHeaders` instance. If the target is a string, Axios parses it as raw HTTP headers.
Returns a new `AxiosHeaders` instance.
### AxiosHeaders#toJSON(asStrings?)
```
toJSON(asStrings: true): Record<string, string>;
toJSON(asStrings?: false): Record<string, string | string[]>;
```
Resolves all internal header values into a new null prototype object.
Set `asStrings` to true to resolve arrays as a string containing all elements, separated by commas.
### AxiosHeaders#toString()
```
toString(): string;
```
Returns the headers as a CRLF-free HTTP header block, one `name: value` pair per line.
### AxiosHeaders.from(thing?)
```
from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
```
Returns a new `AxiosHeaders` instance created from the raw headers passed in,
or returns the given headers object if it's already an `AxiosHeaders` instance.
### AxiosHeaders.concat(...targets)
```
concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;
```
Returns a new `AxiosHeaders` instance created by merging the target objects.
### Shortcuts
The following shortcuts are available:
- `setContentType`, `getContentType`, `hasContentType`
- `setContentLength`, `getContentLength`, `hasContentLength`
- `setAccept`, `getAccept`, `hasAccept`
- `setUserAgent`, `getUserAgent`, `hasUserAgent`
- `setContentEncoding`, `getContentEncoding`, `hasContentEncoding`
## Fetch adapter
Axios introduced the fetch adapter in `v1.7.0`. By default, Axios uses it when the `xhr` and `http` adapters are not available in the build or not supported by the environment.
To use it by default, select it explicitly:
```js
const { data } = axios.get(url, {
adapter: 'fetch', // by default ['xhr', 'http', 'fetch']
});
```
You can create a separate instance for this:
```js
const fetchAxios = axios.create({
adapter: 'fetch',
});
const { data } = fetchAxios.get(url);
```
The adapter supports the same features as the `xhr` adapter, including upload and download progress capturing.
It also supports response types such as `stream` and `formdata` when the environment supports them.
When `auth` is omitted, the fetch adapter can read HTTP Basic auth credentials from the request URL, for example `https://user:pass@example.com`. Percent-encoded URL credentials are decoded before the `Authorization` header is generated, and `auth` takes precedence over URL-embedded credentials.
### Custom fetch
Since `v1.12.0`, you can configure the fetch adapter to use a custom fetch API instead of environment globals.
Pass a custom `fetch` function, `Request`, and `Response` constructors through `env` config.
This helps in custom environments and app frameworks.
When using a custom fetch, you may also need to set custom `Request` and `Response` constructors. If you do not set them, Axios uses the global objects.
If your custom fetch API does not provide these objects and the globals are incompatible with it, pass `null` to disable them inside the fetch adapter.
> Note: Setting `Request` and `Response` to `null` prevents the fetch adapter from capturing upload and download progress.
Basic example:
```js
import customFetchFunction from 'customFetchModule';
const instance = axios.create({
adapter: 'fetch',
onDownloadProgress(e) {
console.log('downloadProgress', e);
},
env: {
fetch: customFetchFunction,
Request: null, // undefined -> use the global constructor
Response: null,
},
});
```
#### Using with Tauri
A minimal example of setting up Axios for use in a [Tauri](https://tauri.app/plugin/http-client/) app with a platform fetch function that ignores CORS policy for requests.
```js
import { fetch } from '@tauri-apps/plugin-http';
import axios from 'axios';
const instance = axios.create({
adapter: 'fetch',
onDownloadProgress(e) {
console.log('downloadProgress', e);
},
env: {
fetch,
},
});
const { data } = await instance.get('https://google.com');
```
#### Using with SvelteKit
[SvelteKit](https://svelte.dev/docs/kit/web-standards#Fetch-APIs) uses a custom fetch function for server rendering in `load` functions. It also uses relative paths, which are incompatible with the standard URL API. Configure Axios to use SvelteKit's custom fetch API:
```js
export async function load({ fetch }) {
const { data: post } = await axios.get('https://jsonplaceholder.typicode.com/posts/1', {
adapter: 'fetch',
env: {
fetch,
Request: null,
Response: null,
},
});
return { post };
}
```
#### HTTP/2 support
Axios supports HTTP/2 through the Node.js `http` adapter, introduced in v1.13.0.
Support depends on the runtime environment. Axios relies on Node.js APIs, so HTTP/2 works in supported Node.js versions but may not work in other environments such as Bun or Deno.
Options like `httpVersion` and `http2Options` are adapter-specific and may not behave the same way in every environment.
Note: HTTP/2 redirects are currently not supported by the HTTP/2 adapter.
```js
const form = new FormData();
form.append('foo', '123');
const { data, headers, status } = await axios.post('https://httpbin.org/post', form, {
onUploadProgress(e) {
console.log('upload progress', e);
},
onDownloadProgress(e) {
console.log('download progress', e);
},
responseType: 'arraybuffer',
});
```
## Semver
Axios follows [semver](https://semver.org/) since `v1.0.0`.
## Promises
axios depends on a native ES6 Promise implementation to be [supported](https://caniuse.com/promises).
If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise).
## TypeScript
axios includes [TypeScript](https://typescriptlang.org) definitions and a type guard for axios errors.
```typescript
let user: User = null;
try {
const { data } = await axios.get('/user?ID=12345');
user = data.userDetails;
} catch (error) {
if (axios.isAxiosError(error)) {
handleAxiosError(error);
} else {
handleUnexpectedError(error);
}
}
```
Use `axios.isCancel<T>()` to narrow cancellation errors to `CanceledError<T>`:
```typescript
const controller = new AbortController();
try {
await axios.get<User>('/user?ID=12345', { signal: controller.signal });
} catch (error) {
if (axios.isCancel<User>(error)) {
handleCancellation(error);
}
}
```
Because axios publishes an ESM default export and a CJS `module.exports`, TypeScript has a few caveats.
The recommended setting is `"moduleResolution": "node16"`, which is implied by `"module": "node16"`. This requires TypeScript 4.7 or greater.
If you use ESM, your settings should be fine.
If you compile TypeScript to CJS and can't use `"moduleResolution": "node 16"`, enable `esModuleInterop`.
If you use TypeScript to type check CJS JavaScript code, your only option is to use `"moduleResolution": "node16"`.
You can also create a custom instance with typed interceptors:
```typescript
import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
const apiClient: AxiosInstance = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
});
apiClient.interceptors.request.use((config: InternalAxiosRequestConfig) => {
// Add auth token
return config;
});
```
## Online one-click setup
You can use Gitpod, a free online IDE for open source projects, to contribute or run the examples online.
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/axios/axios/blob/main/examples/server.js)
## Contributing
### Local setup
As a supply-chain hardening measure, this repository ships a project-level `.npmrc` that sets `ignore-scripts=true`. This blocks npm lifecycle scripts (`preinstall`, `install`, `postinstall`, `prepare`) from any direct or transitive dependency when you run `npm install` or `npm ci` inside the repo. See [THREATMODEL.md](./THREATMODEL.md) (threat T-S2) for the rationale.
One consequence: the repository's own `prepare` hook (which installs Husky's git hooks) will **not** run automatically. After your first install, enable the git hooks manually:
```bash
npm ci
npm rebuild husky && npx husky
```
Run those two commands once per fresh checkout. You do **not** need to re-run them after every subsequent `npm install`.
Do not remove `ignore-scripts=true` from `.npmrc` to "fix" this. That reopens the lifecycle-script attack surface for every other package in the tree. All CI workflows already invoke npm with `--ignore-scripts`, so local behaviour matches CI.
## Resources
- [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md)
- [Ecosystem](https://github.com/axios/axios/blob/v1.x/ECOSYSTEM.md)
- [Contributing Guide](https://github.com/axios/axios/blob/v1.x/CONTRIBUTING.md)
- [Code of Conduct](https://github.com/axios/axios/blob/v1.x/CODE_OF_CONDUCT.md)
## Credits
axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) in [AngularJS](https://angularjs.org/). It provides a standalone `$http`-like service for use outside AngularJS.
## License
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
+5249
View File
@@ -0,0 +1,5249 @@
/*! Axios v1.18.1 Copyright (c) 2026 Matt Zabriskie and contributors */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.axios = factory());
})(this, (function () { 'use strict';
function _OverloadYield(e, d) {
this.v = e, this.k = d;
}
function _arrayLikeToArray(r, a) {
(null == a || a > r.length) && (a = r.length);
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
return n;
}
function _arrayWithHoles(r) {
if (Array.isArray(r)) return r;
}
function _arrayWithoutHoles(r) {
if (Array.isArray(r)) return _arrayLikeToArray(r);
}
function _assertThisInitialized(e) {
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return e;
}
function _asyncGeneratorDelegate(t) {
var e = {},
n = false;
function pump(e, r) {
return n = true, r = new Promise(function (n) {
n(t[e](r));
}), {
done: false,
value: new _OverloadYield(r, 1)
};
}
return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () {
return this;
}, e.next = function (t) {
return n ? (n = false, t) : pump("next", t);
}, "function" == typeof t.throw && (e.throw = function (t) {
if (n) throw n = false, t;
return pump("throw", t);
}), "function" == typeof t.return && (e.return = function (t) {
return n ? (n = false, t) : pump("return", t);
}), e;
}
function _asyncIterator(r) {
var n,
t,
o,
e = 2;
for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
if (t && null != (n = r[t])) return n.call(r);
if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
t = "@@asyncIterator", o = "@@iterator";
}
throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(r) {
function AsyncFromSyncIteratorContinuation(r) {
if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
var n = r.done;
return Promise.resolve(r.value).then(function (r) {
return {
value: r,
done: n
};
});
}
return AsyncFromSyncIterator = function (r) {
this.s = r, this.n = r.next;
}, AsyncFromSyncIterator.prototype = {
s: null,
n: null,
next: function () {
return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
},
return: function (r) {
var n = this.s.return;
return void 0 === n ? Promise.resolve({
value: r,
done: true
}) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
},
throw: function (r) {
var n = this.s.return;
return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
}
}, new AsyncFromSyncIterator(r);
}
function asyncGeneratorStep(n, t, e, r, o, a, c) {
try {
var i = n[a](c),
u = i.value;
} catch (n) {
return void e(n);
}
i.done ? t(u) : Promise.resolve(u).then(r, o);
}
function _asyncToGenerator(n) {
return function () {
var t = this,
e = arguments;
return new Promise(function (r, o) {
var a = n.apply(t, e);
function _next(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
}
function _throw(n) {
asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
}
_next(void 0);
});
};
}
function _awaitAsyncGenerator(e) {
return new _OverloadYield(e, 0);
}
function _callSuper(t, o, e) {
return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
}
function _classCallCheck(a, n) {
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
}
function _construct(t, e, r) {
if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
var o = [null];
o.push.apply(o, e);
var p = new (t.bind.apply(t, o))();
return r && _setPrototypeOf(p, r.prototype), p;
}
function _defineProperties(e, r) {
for (var t = 0; t < r.length; t++) {
var o = r[t];
o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
}
}
function _createClass(e, r, t) {
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
writable: false
}), e;
}
function _createForOfIteratorHelper(r, e) {
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (!t) {
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) {
t && (r = t);
var n = 0,
F = function () {};
return {
s: F,
n: function () {
return n >= r.length ? {
done: true
} : {
done: false,
value: r[n++]
};
},
e: function (r) {
throw r;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var o,
a = true,
u = false;
return {
s: function () {
t = t.call(r);
},
n: function () {
var r = t.next();
return a = r.done, r;
},
e: function (r) {
u = true, o = r;
},
f: function () {
try {
a || null == t.return || t.return();
} finally {
if (u) throw o;
}
}
};
}
function _defineProperty(e, r, t) {
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
value: t,
enumerable: true,
configurable: true,
writable: true
}) : e[r] = t, e;
}
function _getPrototypeOf(t) {
return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
return t.__proto__ || Object.getPrototypeOf(t);
}, _getPrototypeOf(t);
}
function _inherits(t, e) {
if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
t.prototype = Object.create(e && e.prototype, {
constructor: {
value: t,
writable: true,
configurable: true
}
}), Object.defineProperty(t, "prototype", {
writable: false
}), e && _setPrototypeOf(t, e);
}
function _isNativeFunction(t) {
try {
return -1 !== Function.toString.call(t).indexOf("[native code]");
} catch (n) {
return "function" == typeof t;
}
}
function _isNativeReflectConstruct() {
try {
var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
} catch (t) {}
return (_isNativeReflectConstruct = function () {
return !!t;
})();
}
function _iterableToArray(r) {
if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
}
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = true,
o = false;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = true, n = r;
} finally {
try {
if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function ownKeys(e, r) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
r && (o = o.filter(function (r) {
return Object.getOwnPropertyDescriptor(e, r).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function _objectSpread2(e) {
for (var r = 1; r < arguments.length; r++) {
var t = null != arguments[r] ? arguments[r] : {};
r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
_defineProperty(e, r, t[r]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
});
}
return e;
}
function _possibleConstructorReturn(t, e) {
if (e && ("object" == typeof e || "function" == typeof e)) return e;
if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
return _assertThisInitialized(t);
}
function _regenerator() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
var e,
t,
r = "function" == typeof Symbol ? Symbol : {},
n = r.iterator || "@@iterator",
o = r.toStringTag || "@@toStringTag";
function i(r, n, o, i) {
var c = n && n.prototype instanceof Generator ? n : Generator,
u = Object.create(c.prototype);
return _regeneratorDefine(u, "_invoke", function (r, n, o) {
var i,
c,
u,
f = 0,
p = o || [],
y = false,
G = {
p: 0,
n: 0,
v: e,
a: d,
f: d.bind(e, 4),
d: function (t, r) {
return i = t, c = 0, u = e, G.n = r, a;
}
};
function d(r, n) {
for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
var o,
i = p[t],
d = G.p,
l = i[2];
r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
}
if (o || r > 1) return a;
throw y = true, n;
}
return function (o, p, l) {
if (f > 1) throw TypeError("Generator is already running");
for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
try {
if (f = 2, i) {
if (c || (o = "next"), t = i[o]) {
if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
if (!t.done) return t;
u = t.value, c < 2 && (c = 0);
} else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
i = e;
} else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
} catch (t) {
i = e, c = 1, u = t;
} finally {
f = 1;
}
}
return {
value: t,
done: y
};
};
}(r, o, i), true), u;
}
var a = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
t = Object.getPrototypeOf;
var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
return this;
}), t),
u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
function f(e) {
return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
return this;
}), _regeneratorDefine(u, "toString", function () {
return "[object Generator]";
}), (_regenerator = function () {
return {
w: i,
m: f
};
})();
}
function _regeneratorDefine(e, r, n, t) {
var i = Object.defineProperty;
try {
i({}, "", {});
} catch (e) {
i = 0;
}
_regeneratorDefine = function (e, r, n, t) {
function o(r, n) {
_regeneratorDefine(e, r, function (e) {
return this._invoke(r, n, e);
});
}
r ? i ? i(e, r, {
value: n,
enumerable: !t,
configurable: !t,
writable: !t
}) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
}, _regeneratorDefine(e, r, n, t);
}
function _regeneratorValues(e) {
if (null != e) {
var t = e["function" == typeof Symbol && Symbol.iterator || "@@iterator"],
r = 0;
if (t) return t.call(e);
if ("function" == typeof e.next) return e;
if (!isNaN(e.length)) return {
next: function () {
return e && r >= e.length && (e = void 0), {
value: e && e[r++],
done: !e
};
}
};
}
throw new TypeError(typeof e + " is not iterable");
}
function _setPrototypeOf(t, e) {
return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
return t.__proto__ = e, t;
}, _setPrototypeOf(t, e);
}
function _slicedToArray(r, e) {
return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
}
function _toConsumableArray(r) {
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
}
function _toPrimitive(t, r) {
if ("object" != typeof t || !t) return t;
var e = t[Symbol.toPrimitive];
if (void 0 !== e) {
var i = e.call(t, r);
if ("object" != typeof i) return i;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return ("string" === r ? String : Number)(t);
}
function _toPropertyKey(t) {
var i = _toPrimitive(t, "string");
return "symbol" == typeof i ? i : i + "";
}
function _typeof(o) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, _typeof(o);
}
function _unsupportedIterableToArray(r, a) {
if (r) {
if ("string" == typeof r) return _arrayLikeToArray(r, a);
var t = {}.toString.call(r).slice(8, -1);
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
}
}
function _wrapAsyncGenerator(e) {
return function () {
return new AsyncGenerator(e.apply(this, arguments));
};
}
function AsyncGenerator(e) {
var t, n;
function resume(t, n) {
try {
var r = e[t](n),
o = r.value,
u = o instanceof _OverloadYield;
Promise.resolve(u ? o.v : o).then(function (n) {
if (u) {
var i = "return" === t && o.k ? t : "next";
if (!o.k || n.done) return resume(i, n);
n = e[i](n).value;
}
settle(!!r.done, n);
}, function (e) {
resume("throw", e);
});
} catch (e) {
settle(2, e);
}
}
function settle(e, r) {
2 === e ? t.reject(r) : t.resolve({
value: r,
done: e
}), (t = t.next) ? resume(t.key, t.arg) : n = null;
}
this._invoke = function (e, r) {
return new Promise(function (o, u) {
var i = {
key: e,
arg: r,
resolve: o,
reject: u,
next: null
};
n ? n = n.next = i : (t = n = i, resume(e, r));
});
}, "function" != typeof e.return && (this.return = void 0);
}
AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () {
return this;
}, AsyncGenerator.prototype.next = function (e) {
return this._invoke("next", e);
}, AsyncGenerator.prototype.throw = function (e) {
return this._invoke("throw", e);
}, AsyncGenerator.prototype.return = function (e) {
return this._invoke("return", e);
};
function _wrapNativeSuper(t) {
var r = "function" == typeof Map ? new Map() : void 0;
return _wrapNativeSuper = function (t) {
if (null === t || !_isNativeFunction(t)) return t;
if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
if (void 0 !== r) {
if (r.has(t)) return r.get(t);
r.set(t, Wrapper);
}
function Wrapper() {
return _construct(t, arguments, _getPrototypeOf(this).constructor);
}
return Wrapper.prototype = Object.create(t.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
}), _setPrototypeOf(Wrapper, t);
}, _wrapNativeSuper(t);
}
/**
* Create a bound version of a function with a specified `this` context
*
* @param {Function} fn - The function to bind
* @param {*} thisArg - The value to be passed as the `this` parameter
* @returns {Function} A new function that will call the original function with the specified `this` context
*/
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
var getPrototypeOf = Object.getPrototypeOf;
var iterator = Symbol.iterator,
toStringTag = Symbol.toStringTag;
/* Creating a function that will check if an object has a property. */
var hasOwnProperty = function (_ref) {
var hasOwnProperty = _ref.hasOwnProperty;
return function (obj, prop) {
return hasOwnProperty.call(obj, prop);
};
}(Object.prototype);
/**
* Walk the prototype chain (excluding the shared Object.prototype) looking for
* an own `prop`. This distinguishes genuine own/inherited members — including
* class accessors and template prototypes — from members injected via
* Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
* live on Object.prototype itself and are therefore never matched.
*
* @param {*} thing The value whose chain to inspect
* @param {string|symbol} prop The property key to look for
*
* @returns {boolean} True when `prop` is owned below Object.prototype
*/
var hasOwnInPrototypeChain = function hasOwnInPrototypeChain(thing, prop) {
var obj = thing;
var seen = [];
while (obj != null && obj !== Object.prototype) {
if (seen.indexOf(obj) !== -1) {
return false;
}
seen.push(obj);
if (hasOwnProperty(obj, prop)) {
return true;
}
obj = getPrototypeOf(obj);
}
return false;
};
/**
* Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
* properties and members inherited from a non-Object.prototype source (a class
* instance or template object) are honored; a value reachable only through a
* polluted Object.prototype is ignored and `undefined` is returned.
*
* @param {*} obj The source object
* @param {string|symbol} prop The property key to read
*
* @returns {*} The resolved value, or undefined when unsafe/absent
*/
var getSafeProp = function getSafeProp(obj, prop) {
return obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
};
var kindOf = function (cache) {
return function (thing) {
var str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
};
}(Object.create(null));
var kindOfTest = function kindOfTest(type) {
type = type.toLowerCase();
return function (thing) {
return kindOf(thing) === type;
};
};
var typeOfTest = function typeOfTest(type) {
return function (thing) {
return _typeof(thing) === type;
};
};
/**
* Determine if a value is a non-null object
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
var isArray = Array.isArray;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
var isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
var isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && isArrayBuffer(val.buffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
var isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
var isFunction$1 = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
var isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
var isObject = function isObject(thing) {
return thing !== null && _typeof(thing) === 'object';
};
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
var isBoolean = function isBoolean(thing) {
return thing === true || thing === false;
};
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
var isPlainObject = function isPlainObject(val) {
if (!isObject(val)) {
return false;
}
var prototype = getPrototypeOf(val);
return (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) &&
// Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
// Symbol.iterator as evidence the value is a tagged/iterable type rather
// than a plain object, while ignoring keys injected onto Object.prototype.
!hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator);
};
/**
* Determine if a value is an empty object (safely handles Buffers)
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an empty object, otherwise false
*/
var isEmptyObject = function isEmptyObject(val) {
// Early return for non-objects or Buffers to prevent RangeError
if (!isObject(val) || isBuffer(val)) {
return false;
}
try {
return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
} catch (e) {
// Fallback for any other objects that might cause RangeError with Object.keys()
return false;
}
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
var isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
var isFile = kindOfTest('File');
/**
* Determine if a value is a React Native Blob
* React Native "blob": an object with a `uri` attribute. Optionally, it can
* also have a `name` and `type` attribute to specify filename and content type
*
* @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
*
* @param {*} value The value to test
*
* @returns {boolean} True if value is a React Native Blob, otherwise false
*/
var isReactNativeBlob = function isReactNativeBlob(value) {
return !!(value && typeof value.uri !== 'undefined');
};
/**
* Determine if environment is React Native
* ReactNative `FormData` has a non-standard `getParts()` method
*
* @param {*} formData The formData to test
*
* @returns {boolean} True if environment is React Native, otherwise false
*/
var isReactNative = function isReactNative(formData) {
return formData && typeof formData.getParts !== 'undefined';
};
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
var isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a FileList, otherwise false
*/
var isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
var isStream = function isStream(val) {
return isObject(val) && isFunction$1(val.pipe);
};
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
function getGlobal() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
return {};
}
var G = getGlobal();
var FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
var isFormData = function isFormData(thing) {
if (!thing) return false;
if (FormDataCtor && thing instanceof FormDataCtor) return true;
// Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
var proto = getPrototypeOf(thing);
if (!proto || proto === Object.prototype) return false;
if (!isFunction$1(thing.append)) return false;
var kind = kindOf(thing);
return kind === 'formdata' ||
// detect form-data instance
kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]';
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
var isURLSearchParams = kindOfTest('URLSearchParams');
var _map = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest),
_map2 = _slicedToArray(_map, 4),
isReadableStream = _map2[0],
isRequest = _map2[1],
isResponse = _map2[2],
isHeaders = _map2[3];
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
var trim = function trim(str) {
return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array<unknown>} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn) {
var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
_ref2$allOwnKeys = _ref2.allOwnKeys,
allOwnKeys = _ref2$allOwnKeys === void 0 ? false : _ref2$allOwnKeys;
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
var i;
var l;
// Force an array if not already something iterable
if (_typeof(obj) !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Buffer check
if (isBuffer(obj)) {
return;
}
// Iterate over object keys
var keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
var len = keys.length;
var key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
/**
* Finds a key in an object, case-insensitive, returning the actual key name.
* Returns null if the object is a Buffer or if no match is found.
*
* @param {Object} obj - The object to search.
* @param {string} key - The key to find (case-insensitive).
* @returns {?string} The actual key name if found, otherwise null.
*/
function findKey(obj, key) {
if (isBuffer(obj)) {
return null;
}
key = key.toLowerCase();
var keys = Object.keys(obj);
var i = keys.length;
var _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
var _global = function () {
/*eslint no-undef:0*/
if (typeof globalThis !== 'undefined') return globalThis;
return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
}();
var isContextDefined = function isContextDefined(context) {
return !isUndefined(context) && context !== _global;
};
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* const result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge() {
var _ref3 = isContextDefined(this) && this || {},
caseless = _ref3.caseless,
skipUndefined = _ref3.skipUndefined;
var result = {};
var assignValue = function assignValue(val, key) {
// Skip dangerous property names to prevent prototype pollution
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return;
}
// findKey lowercases the key, so caseless lookup only applies to strings —
// symbol keys are identity-matched.
var targetKey = caseless && typeof key === 'string' && findKey(result, key) || key;
// Read via own-prop only — a bare `result[targetKey]` walks the prototype
// chain, so a polluted Object.prototype value could surface here and get
// copied into the merged result.
var existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
if (isPlainObject(existing) && isPlainObject(val)) {
result[targetKey] = merge(existing, val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else if (!skipUndefined || !isUndefined(val)) {
result[targetKey] = val;
}
};
for (var i = 0, l = arguments.length; i < l; i++) {
var source = i < 0 || arguments.length <= i ? undefined : arguments[i];
if (!source || isBuffer(source)) {
continue;
}
forEach(source, assignValue);
if (_typeof(source) !== 'object' || isArray(source)) {
continue;
}
var symbols = Object.getOwnPropertySymbols(source);
for (var j = 0; j < symbols.length; j++) {
var symbol = symbols[j];
if (propertyIsEnumerable.call(source, symbol)) {
assignValue(source[symbol], symbol);
}
}
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys]
* @returns {Object} The resulting value of object a
*/
var extend = function extend(a, b, thisArg) {
var _ref4 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
allOwnKeys = _ref4.allOwnKeys;
forEach(b, function (val, key) {
if (thisArg && isFunction$1(val)) {
Object.defineProperty(a, key, {
// Null-proto descriptor so a polluted Object.prototype.get cannot
// hijack defineProperty's accessor-vs-data resolution.
__proto__: null,
value: bind(val, thisArg),
writable: true,
enumerable: true,
configurable: true
});
} else {
Object.defineProperty(a, key, {
__proto__: null,
value: val,
writable: true,
enumerable: true,
configurable: true
});
}
}, {
allOwnKeys: allOwnKeys
});
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
var stripBOM = function stripBOM(content) {
if (content.charCodeAt(0) === 0xfeff) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
var inherits = function inherits(constructor, superConstructor, props, descriptors) {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
Object.defineProperty(constructor.prototype, 'constructor', {
__proto__: null,
value: constructor,
writable: true,
enumerable: false,
configurable: true
});
Object.defineProperty(constructor, 'super', {
__proto__: null,
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
var toFlatObject = function toFlatObject(sourceObj, destObj, filter, propFilter) {
var props;
var i;
var prop;
var merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
var endsWith = function endsWith(str, searchString, position) {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
var lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
var toArray = function toArray(thing) {
if (!thing) return null;
if (isArray(thing)) return thing;
var i = thing.length;
if (!isNumber(i)) return null;
var arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
var isTypedArray = function (TypedArray) {
// eslint-disable-next-line func-names
return function (thing) {
return TypedArray && thing instanceof TypedArray;
};
}(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object<any, any>} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
var forEachEntry = function forEachEntry(obj, fn) {
var generator = obj && obj[iterator];
var _iterator = generator.call(obj);
var result;
while ((result = _iterator.next()) && !result.done) {
var pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array<boolean>}
*/
var matchAll = function matchAll(regExp, str) {
var matches;
var arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
var isHTMLForm = kindOfTest('HTMLFormElement');
var toCamelCase = function toCamelCase(str) {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
});
};
var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
var isRegExp = kindOfTest('RegExp');
var reduceDescriptors = function reduceDescriptors(obj, reducer) {
var descriptors = Object.getOwnPropertyDescriptors(obj);
var reducedDescriptors = {};
forEach(descriptors, function (descriptor, name) {
var ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
var freezeMethods = function freezeMethods(obj) {
reduceDescriptors(obj, function (descriptor, name) {
// skip restricted props in strict mode
if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
return false;
}
var value = obj[name];
if (!isFunction$1(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = function () {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
/**
* Converts an array or a delimited string into an object set with values as keys and true as values.
* Useful for fast membership checks.
*
* @param {Array|string} arrayOrString - The array or string to convert.
* @param {string} delimiter - The delimiter to use if input is a string.
* @returns {Object} An object with keys from the array or string, values set to true.
*/
var toObjectSet = function toObjectSet(arrayOrString, delimiter) {
var obj = {};
var define = function define(arr) {
arr.forEach(function (value) {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
var noop = function noop() {};
var toFiniteNumber = function toFiniteNumber(value, defaultValue) {
return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
}
/**
* Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
*
* @param {Object} obj - The object to convert.
* @returns {Object} The JSON-compatible object.
*/
var toJSONObject = function toJSONObject(obj) {
var visited = new WeakSet();
var _visit = function visit(source) {
if (isObject(source)) {
if (visited.has(source)) {
return;
}
//Buffer check
if (isBuffer(source)) {
return source;
}
if (!('toJSON' in source)) {
// add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
visited.add(source);
var target = isArray(source) ? [] : {};
forEach(source, function (value, key) {
var reducedValue = _visit(value);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
visited["delete"](source);
return target;
}
}
return source;
};
return _visit(obj);
};
/**
* Determines if a value is an async function.
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is an async function, otherwise false.
*/
var isAsyncFn = kindOfTest('AsyncFunction');
/**
* Determines if a value is thenable (has then and catch methods).
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is thenable, otherwise false.
*/
var isThenable = function isThenable(thing) {
return thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing["catch"]);
};
// original code
// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
/**
* Provides a cross-platform setImmediate implementation.
* Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
*
* @param {boolean} setImmediateSupported - Whether setImmediate is supported.
* @param {boolean} postMessageSupported - Whether postMessage is supported.
* @returns {Function} A function to schedule a callback asynchronously.
*/
var _setImmediate = function (setImmediateSupported, postMessageSupported) {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported ? function (token, callbacks) {
_global.addEventListener('message', function (_ref5) {
var source = _ref5.source,
data = _ref5.data;
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
}, false);
return function (cb) {
callbacks.push(cb);
_global.postMessage(token, '*');
};
}("axios@".concat(Math.random()), []) : function (cb) {
return setTimeout(cb);
};
}(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
/**
* Schedules a microtask or asynchronous callback as soon as possible.
* Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
*
* @type {Function}
*/
var asap = typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) : typeof process !== 'undefined' && process.nextTick || _setImmediate;
// *********************
var isIterable = function isIterable(thing) {
return thing != null && isFunction$1(thing[iterator]);
};
/**
* Determine if a value is iterable via an iterator that is NOT sourced solely
* from a polluted Object.prototype. Use this instead of `isIterable` whenever
* the iterable comes from untrusted input (e.g. user-supplied header sources),
* so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
* into an attacker-controlled entries iterator.
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value has a non-polluted iterator
*/
var isSafeIterable = function isSafeIterable(thing) {
return thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
};
var utils$1 = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isBoolean: isBoolean,
isObject: isObject,
isPlainObject: isPlainObject,
isEmptyObject: isEmptyObject,
isReadableStream: isReadableStream,
isRequest: isRequest,
isResponse: isResponse,
isHeaders: isHeaders,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isReactNativeBlob: isReactNativeBlob,
isReactNative: isReactNative,
isBlob: isBlob,
isRegExp: isRegExp,
isFunction: isFunction$1,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isTypedArray: isTypedArray,
isFileList: isFileList,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM,
inherits: inherits,
toFlatObject: toFlatObject,
kindOf: kindOf,
kindOfTest: kindOfTest,
endsWith: endsWith,
toArray: toArray,
forEachEntry: forEachEntry,
matchAll: matchAll,
isHTMLForm: isHTMLForm,
hasOwnProperty: hasOwnProperty,
hasOwnProp: hasOwnProperty,
// an alias to avoid ESLint no-prototype-builtins detection
hasOwnInPrototypeChain: hasOwnInPrototypeChain,
getSafeProp: getSafeProp,
reduceDescriptors: reduceDescriptors,
freezeMethods: freezeMethods,
toObjectSet: toObjectSet,
toCamelCase: toCamelCase,
noop: noop,
toFiniteNumber: toFiniteNumber,
findKey: findKey,
global: _global,
isContextDefined: isContextDefined,
isSpecCompliantForm: isSpecCompliantForm,
toJSONObject: toJSONObject,
isAsyncFn: isAsyncFn,
isThenable: isThenable,
setImmediate: _setImmediate,
asap: asap,
isIterable: isIterable,
isSafeIterable: isSafeIterable
};
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = utils$1.toObjectSet(['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = (function (rawHeaders) {
var parsed = {};
var key;
var val;
var i;
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || parsed[key] && ignoreDuplicateOf[key]) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
});
function trimSPorHTAB(str) {
var start = 0;
var end = str.length;
while (start < end) {
var code = str.charCodeAt(start);
if (code !== 0x09 && code !== 0x20) {
break;
}
start += 1;
}
while (end > start) {
var _code = str.charCodeAt(end - 1);
if (_code !== 0x09 && _code !== 0x20) {
break;
}
end -= 1;
}
return start === 0 && end === str.length ? str : str.slice(start, end);
}
// The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
// eslint-disable-next-line no-control-regex
var INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+", 'g');
// eslint-disable-next-line no-control-regex
var INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+", 'g');
function sanitizeValue(value, invalidChars) {
if (utils$1.isArray(value)) {
return value.map(function (item) {
return sanitizeValue(item, invalidChars);
});
}
return trimSPorHTAB(String(value).replace(invalidChars, ''));
}
var sanitizeHeaderValue = function sanitizeHeaderValue(value) {
return sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
};
var sanitizeByteStringHeaderValue = function sanitizeByteStringHeaderValue(value) {
return sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
};
function toByteStringHeaderObject(headers) {
var byteStringHeaders = Object.create(null);
utils$1.forEach(headers.toJSON(), function (value, header) {
byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
});
return byteStringHeaders;
}
var $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
}
function parseTokens(str) {
var tokens = Object.create(null);
var tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
var match;
while (match = tokensRE.exec(str)) {
tokens[match[1]] = match[2];
}
return tokens;
}
var isValidHeaderName = function isValidHeaderName(str) {
return /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
};
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils$1.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils$1.isString(value)) return;
if (utils$1.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils$1.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, function (w, _char, str) {
return _char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
var accessorName = utils$1.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(function (methodName) {
Object.defineProperty(obj, methodName + accessorName, {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: function value(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
var AxiosHeaders = /*#__PURE__*/function () {
function AxiosHeaders(headers) {
_classCallCheck(this, AxiosHeaders);
headers && this.set(headers);
}
return _createClass(AxiosHeaders, [{
key: "set",
value: function set(header, valueOrRewrite, rewrite) {
var self = this;
function setHeader(_value, _header, _rewrite) {
var lHeader = normalizeHeader(_header);
if (!lHeader) {
return;
}
var key = utils$1.findKey(self, lHeader);
if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) {
self[key || _header] = normalizeValue(_value);
}
}
var setHeaders = function setHeaders(headers, _rewrite) {
return utils$1.forEach(headers, function (_value, _header) {
return setHeader(_value, _header, _rewrite);
});
};
if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
var obj = Object.create(null),
dest,
key;
var _iterator = _createForOfIteratorHelper(header),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var entry = _step.value;
if (!utils$1.isArray(entry)) {
throw new TypeError('Object iterator must return a key-value pair');
}
key = entry[0];
if (utils$1.hasOwnProp(obj, key)) {
dest = obj[key];
obj[key] = utils$1.isArray(dest) ? [].concat(_toConsumableArray(dest), [entry[1]]) : [dest, entry[1]];
} else {
obj[key] = entry[1];
}
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
setHeaders(obj, valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
}, {
key: "get",
value: function get(header, parser) {
header = normalizeHeader(header);
if (header) {
var key = utils$1.findKey(this, header);
if (key) {
var value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils$1.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils$1.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
}, {
key: "has",
value: function has(header, matcher) {
header = normalizeHeader(header);
if (header) {
var key = utils$1.findKey(this, header);
return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
}, {
key: "delete",
value: function _delete(header, matcher) {
var self = this;
var deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
var key = utils$1.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils$1.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
}, {
key: "clear",
value: function clear(matcher) {
var keys = Object.keys(this);
var i = keys.length;
var deleted = false;
while (i--) {
var key = keys[i];
if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
}, {
key: "normalize",
value: function normalize(format) {
var self = this;
var headers = {};
utils$1.forEach(this, function (value, header) {
var key = utils$1.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
var normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
}, {
key: "concat",
value: function concat() {
var _this$constructor;
for (var _len = arguments.length, targets = new Array(_len), _key = 0; _key < _len; _key++) {
targets[_key] = arguments[_key];
}
return (_this$constructor = this.constructor).concat.apply(_this$constructor, [this].concat(targets));
}
}, {
key: "toJSON",
value: function toJSON(asStrings) {
var obj = Object.create(null);
utils$1.forEach(this, function (value, header) {
value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
});
return obj;
}
}, {
key: Symbol.iterator,
value: function value() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
}, {
key: "toString",
value: function toString() {
return Object.entries(this.toJSON()).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
header = _ref2[0],
value = _ref2[1];
return header + ': ' + value;
}).join('\n');
}
}, {
key: "getSetCookie",
value: function getSetCookie() {
return this.get('set-cookie') || [];
}
}, {
key: Symbol.toStringTag,
get: function get() {
return 'AxiosHeaders';
}
}], [{
key: "from",
value: function from(thing) {
return thing instanceof this ? thing : new this(thing);
}
}, {
key: "concat",
value: function concat(first) {
var computed = new this(first);
for (var _len2 = arguments.length, targets = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
targets[_key2 - 1] = arguments[_key2];
}
targets.forEach(function (target) {
return computed.set(target);
});
return computed;
}
}, {
key: "accessor",
value: function accessor(header) {
var internals = this[$internals] = this[$internals] = {
accessors: {}
};
var accessors = internals.accessors;
var prototype = this.prototype;
function defineAccessor(_header) {
var lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}]);
}();
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
// reserved names hotfix
utils$1.reduceDescriptors(AxiosHeaders.prototype, function (_ref3, key) {
var value = _ref3.value;
var mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: function get() {
return value;
},
set: function set(headerValue) {
this[mapped] = headerValue;
}
};
});
utils$1.freezeMethods(AxiosHeaders);
var REDACTED = '[REDACTED ****]';
function hasOwnOrPrototypeToJSON(source) {
if (utils$1.hasOwnProp(source, 'toJSON')) {
return true;
}
var prototype = Object.getPrototypeOf(source);
while (prototype && prototype !== Object.prototype) {
if (utils$1.hasOwnProp(prototype, 'toJSON')) {
return true;
}
prototype = Object.getPrototypeOf(prototype);
}
return false;
}
// Build a plain-object snapshot of `config` and replace the value of any key
// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
// and AxiosHeaders, and short-circuits on circular references.
function redactConfig(config, redactKeys) {
var lowerKeys = new Set(redactKeys.map(function (k) {
return String(k).toLowerCase();
}));
var seen = [];
var _visit = function visit(source) {
if (source === null || _typeof(source) !== 'object') return source;
if (utils$1.isBuffer(source)) return source;
if (seen.indexOf(source) !== -1) return undefined;
if (source instanceof AxiosHeaders) {
source = source.toJSON();
}
seen.push(source);
var result;
if (utils$1.isArray(source)) {
result = [];
source.forEach(function (v, i) {
var reducedValue = _visit(v);
if (!utils$1.isUndefined(reducedValue)) {
result[i] = reducedValue;
}
});
} else {
if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
seen.pop();
return source;
}
result = Object.create(null);
for (var _i = 0, _Object$entries = Object.entries(source); _i < _Object$entries.length; _i++) {
var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
key = _Object$entries$_i[0],
value = _Object$entries$_i[1];
var reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : _visit(value);
if (!utils$1.isUndefined(reducedValue)) {
result[key] = reducedValue;
}
}
}
seen.pop();
return result;
};
return _visit(config);
}
var AxiosError = /*#__PURE__*/function (_Error) {
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
function AxiosError(message, code, config, request, response) {
var _this;
_classCallCheck(this, AxiosError);
_this = _callSuper(this, AxiosError, [message]);
// Make message enumerable to maintain backward compatibility
// The native Error constructor sets message as non-enumerable,
// but axios < v1.13.3 had it as enumerable
Object.defineProperty(_this, 'message', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: message,
enumerable: true,
writable: true,
configurable: true
});
_this.name = 'AxiosError';
_this.isAxiosError = true;
code && (_this.code = code);
config && (_this.config = config);
request && (_this.request = request);
if (response) {
_this.response = response;
_this.status = response.status;
}
return _this;
}
_inherits(AxiosError, _Error);
return _createClass(AxiosError, [{
key: "toJSON",
value: function toJSON() {
// Opt-in redaction: when the request config carries a `redact` array, the
// value of any matching key (case-insensitive, at any depth) is replaced
// with REDACTED in the serialized snapshot. Undefined or empty leaves the
// existing serialization behavior unchanged.
var config = this.config;
var redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
var serializedConfig = utils$1.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : utils$1.toJSONObject(config);
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: serializedConfig,
code: this.code,
status: this.status
};
}
}], [{
key: "from",
value: function from(error, code, config, request, response, customProps) {
var axiosError = new AxiosError(error.message, code || error.code, config, request, response);
// Match native `Error` `cause` semantics: non-enumerable. The wrapped
// error often carries circular internals (sockets, requests, agents), so
// an enumerable `cause` makes structured loggers (pino/winston) and any
// own-property walk throw "Converting circular structure to JSON".
// Regression from #6982; see #7205. `__proto__: null` mirrors the
// `message` descriptor below (prototype-pollution-safe descriptor).
Object.defineProperty(axiosError, 'cause', {
__proto__: null,
value: error,
writable: true,
enumerable: false,
configurable: true
});
axiosError.name = error.name;
// Preserve status from the original error if not already set from response
if (error.status != null && axiosError.status == null) {
axiosError.status = error.status;
}
customProps && Object.assign(axiosError, customProps);
return axiosError;
}
}]);
}(/*#__PURE__*/_wrapNativeSuper(Error)); // This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
AxiosError.ECONNABORTED = 'ECONNABORTED';
AxiosError.ETIMEDOUT = 'ETIMEDOUT';
AxiosError.ECONNREFUSED = 'ECONNREFUSED';
AxiosError.ERR_NETWORK = 'ERR_NETWORK';
AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
AxiosError.ERR_CANCELED = 'ERR_CANCELED';
AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
// eslint-disable-next-line strict
var httpAdapter = null;
// Default nesting limit shared with the inverse transform (formDataToJSON) so
// the FormData <-> JSON round-trip stays symmetric.
var DEFAULT_FORM_DATA_MAX_DEPTH = 100;
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
}).join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array<any>} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils$1.isArray(arr) && !arr.some(isVisitable);
}
var predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object<any, any>} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object<string, any>} options
*
* @returns
*/
function toFormData(obj, formData, options) {
if (!utils$1.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (FormData)();
// eslint-disable-next-line no-param-reassign
options = utils$1.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils$1.isUndefined(source[option]);
});
var metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
var visitor = options.visitor || defaultVisitor;
var dots = options.dots;
var indexes = options.indexes;
var _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
var maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
var useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
var stack = [];
if (!utils$1.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils$1.isDate(value)) {
return value.toISOString();
}
if (utils$1.isBoolean(value)) {
return value.toString();
}
if (!useBlob && utils$1.isBlob(value)) {
throw new AxiosError('Blob is not supported. Use a Buffer instead.');
}
if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
if (useBlob && typeof _Blob === 'function') {
return new _Blob([value]);
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(value);
}
throw new AxiosError('Blob is not supported. Use a Buffer instead.', AxiosError.ERR_NOT_SUPPORT);
}
return value;
}
function throwIfMaxDepthExceeded(depth) {
if (depth > maxDepth) {
throw new AxiosError('Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
}
}
function stringifyWithDepthLimit(value, depth) {
if (maxDepth === Infinity) {
return JSON.stringify(value);
}
var ancestors = [];
return JSON.stringify(value, function limitDepth(_key, currentValue) {
if (!utils$1.isObject(currentValue)) {
return currentValue;
}
while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
ancestors.pop();
}
ancestors.push(currentValue);
throwIfMaxDepthExceeded(depth + ancestors.length - 1);
return currentValue;
});
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array<String|Number>} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
var arr = value;
if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
if (value && !path && _typeof(value) === 'object') {
if (utils$1.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = stringifyWithDepthLimit(value, 1);
} else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils$1.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el));
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
var exposedHelpers = Object.assign(predicates, {
defaultVisitor: defaultVisitor,
convertValue: convertValue,
isVisitable: isVisitable
});
function build(value, path) {
var depth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
if (utils$1.isUndefined(value)) return;
throwIfMaxDepthExceeded(depth);
if (stack.indexOf(value) !== -1) {
throw new Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils$1.forEach(value, function each(el, key) {
var result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
if (result === true) {
build(el, path ? path.concat(key) : [key], depth + 1);
}
});
stack.pop();
}
if (!utils$1.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode$1(str) {
var charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+'
};
return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
var prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
var _this = this;
var _encode = encoder ? function (value) {
return encoder.call(_this, value, encode$1);
} : encode$1;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '').join('&');
};
/**
* It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
* their plain counterparts (`:`, `$`, `,`, `+`).
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?(object|Function)} options
*
* @returns {string} The formatted url
*/
function buildURL(url, params, options) {
if (!params) {
return url;
}
url = url || '';
var _options = utils$1.isFunction(options) ? {
serialize: options
} : options;
// Read serializer options pollution-safely: own properties and methods on a
// class/template prototype are honored, but values injected onto a polluted
// Object.prototype are ignored.
var _encode = utils$1.getSafeProp(_options, 'encode') || encode;
var serializeFn = utils$1.getSafeProp(_options, 'serialize');
var serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, _options);
} else {
serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
var InterceptorManager = /*#__PURE__*/function () {
function InterceptorManager() {
_classCallCheck(this, InterceptorManager);
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
* @param {Object} options The options for the interceptor, synchronous and runWhen
*
* @return {Number} An ID used to remove interceptor later
*/
return _createClass(InterceptorManager, [{
key: "use",
value: function use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {void}
*/
}, {
key: "eject",
value: function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
}, {
key: "clear",
value: function clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
}, {
key: "forEach",
value: function forEach(fn) {
utils$1.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}]);
}();
var transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false,
legacyInterceptorReqResOrdering: true,
advertiseZstdAcceptEncoding: false,
validateStatusUndefinedResolves: true
};
var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
var platform$1 = {
isBrowser: true,
classes: {
URLSearchParams: URLSearchParams$1,
FormData: FormData$1,
Blob: Blob$1
},
protocols: ['http', 'https', 'file', 'blob', 'url', 'data']
};
var hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
var _navigator = (typeof navigator === "undefined" ? "undefined" : _typeof(navigator)) === 'object' && navigator || undefined;
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
var hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
var hasStandardBrowserWebWorkerEnv = function () {
return typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope && typeof self.importScripts === 'function';
}();
var origin = hasBrowserEnv && window.location.href || 'http://localhost';
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
hasBrowserEnv: hasBrowserEnv,
hasStandardBrowserEnv: hasStandardBrowserEnv,
hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
navigator: _navigator,
origin: origin
});
var platform = _objectSpread2(_objectSpread2({}, utils), platform$1);
function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), _objectSpread2({
visitor: function visitor(value, key, path, helpers) {
if (platform.isNode && utils$1.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
}
}, options));
}
var MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
function throwIfDepthExceeded(index) {
if (index > MAX_DEPTH) {
throw new AxiosError('FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
}
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
var path = [];
var pattern = /\w+|\[(\w*)]/g;
var match;
while ((match = pattern.exec(name)) !== null) {
throwIfDepthExceeded(path.length);
path.push(match[0] === '[]' ? '' : match[1] || match[0]);
}
return path;
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
var obj = {};
var keys = Object.keys(arr);
var i;
var len = keys.length;
var key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
throwIfDepthExceeded(index);
var name = path[index++];
if (name === '__proto__') return true;
var isNumericKey = Number.isFinite(+name);
var isLast = index >= path.length;
name = !name && utils$1.isArray(target) ? target.length : name;
if (isLast) {
if (utils$1.hasOwnProp(target, name)) {
target[name] = utils$1.isArray(target[name]) ? target[name].concat(value) : [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
target[name] = [];
}
var result = buildPath(path, value, target[name], index);
if (result && utils$1.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
var obj = {};
utils$1.forEachEntry(formData, function (name, value) {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
var own = function own(obj, key) {
return obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined;
};
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils$1.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils$1.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [function transformRequest(data, headers) {
var contentType = headers.getContentType() || '';
var hasJSONContentType = contentType.indexOf('application/json') > -1;
var isObjectPayload = utils$1.isObject(data);
if (isObjectPayload && utils$1.isHTMLForm(data)) {
data = new FormData(data);
}
var isFormData = utils$1.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
return data;
}
if (utils$1.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$1.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
var isFileList;
if (isObjectPayload) {
var formSerializer = own(this, 'formSerializer');
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, formSerializer).toString();
}
if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
var env = own(this, 'env');
var _FormData = env && env.FormData;
return toFormData(isFileList ? {
'files[]': data
} : data, _FormData && new _FormData(), formSerializer);
}
}
if (isObjectPayload || hasJSONContentType) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
var transitional = own(this, 'transitional') || defaults.transitional;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var responseType = own(this, 'responseType');
var JSONRequested = responseType === 'json';
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data, own(this, 'parseReviver'));
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
Accept: 'application/json, text/plain, */*',
'Content-Type': undefined
}
}
};
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], function (method) {
defaults.headers[method] = {};
});
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
function transformData(fns, response) {
var config = this || defaults;
var context = response || config;
var headers = AxiosHeaders.from(context.headers);
var data = context.data;
utils$1.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
function isCancel(value) {
return !!(value && value.__CANCEL__);
}
var CanceledError = /*#__PURE__*/function (_AxiosError) {
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
function CanceledError(message, config, request) {
var _this;
_classCallCheck(this, CanceledError);
_this = _callSuper(this, CanceledError, [message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request]);
_this.name = 'CanceledError';
_this.__CANCEL__ = true;
return _this;
}
_inherits(CanceledError, _AxiosError);
return _createClass(CanceledError);
}(AxiosError);
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError('Request failed with status code ' + response.status, response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE, response.config, response.request, response));
}
}
function parseProtocol(url) {
var match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
return match && match[1] || '';
}
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
var bytes = new Array(samplesCount);
var timestamps = new Array(samplesCount);
var head = 0;
var tail = 0;
var firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
var now = Date.now();
var startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
var i = tail;
var bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
var passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
};
}
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
var timestamp = 0;
var threshold = 1000 / freq;
var lastArgs;
var timer;
var invoke = function invoke(args) {
var now = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Date.now();
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn.apply(void 0, _toConsumableArray(args));
};
var throttled = function throttled() {
var now = Date.now();
var passed = now - timestamp;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(function () {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
var flush = function flush() {
return lastArgs && invoke(lastArgs);
};
return [throttled, flush];
}
var progressEventReducer = function progressEventReducer(listener, isDownloadStream) {
var freq = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 3;
var bytesNotified = 0;
var _speedometer = speedometer(50, 250);
return throttle(function (e) {
if (!e || typeof e.loaded !== 'number') {
return;
}
var rawLoaded = e.loaded;
var total = e.lengthComputable ? e.total : undefined;
var loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
var progressBytes = Math.max(0, loaded - bytesNotified);
var rate = _speedometer(progressBytes);
bytesNotified = Math.max(bytesNotified, loaded);
var data = _defineProperty({
loaded: loaded,
total: total,
progress: total ? loaded / total : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null
}, isDownloadStream ? 'download' : 'upload', true);
listener(data);
}, freq);
};
var progressEventDecorator = function progressEventDecorator(total, throttled) {
var lengthComputable = total != null;
return [function (loaded) {
return throttled[0]({
lengthComputable: lengthComputable,
total: total,
loaded: loaded
});
}, throttled[1]];
};
var asyncDecorator = function asyncDecorator(fn) {
return function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return utils$1.asap(function () {
return fn.apply(void 0, args);
});
};
};
var isURLSameOrigin = platform.hasStandardBrowserEnv ? function (origin, isMSIE) {
return function (url) {
url = new URL(url, platform.origin);
return origin.protocol === url.protocol && origin.host === url.host && (isMSIE || origin.port === url.port);
};
}(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : function () {
return true;
};
var cookies = platform.hasStandardBrowserEnv ?
// Standard browser envs support document.cookie
{
write: function write(name, value, expires, path, domain, secure, sameSite) {
if (typeof document === 'undefined') return;
var cookie = ["".concat(name, "=").concat(encodeURIComponent(value))];
if (utils$1.isNumber(expires)) {
cookie.push("expires=".concat(new Date(expires).toUTCString()));
}
if (utils$1.isString(path)) {
cookie.push("path=".concat(path));
}
if (utils$1.isString(domain)) {
cookie.push("domain=".concat(domain));
}
if (secure === true) {
cookie.push('secure');
}
if (utils$1.isString(sameSite)) {
cookie.push("SameSite=".concat(sameSite));
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
if (typeof document === 'undefined') return null;
// Match name=value by splitting on the semicolon separator instead of building a
// RegExp from `name` — interpolating an unescaped string into a RegExp would let
// metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
// match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
// "; ", so ignore optional whitespace before each cookie name.
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].replace(/^\s+/, '');
var eq = cookie.indexOf('=');
if (eq !== -1 && cookie.slice(0, eq) === name) {
try {
return decodeURIComponent(cookie.slice(eq + 1));
} catch (e) {
return cookie.slice(eq + 1);
}
}
}
return null;
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000, '/');
}
} :
// Non-standard browser env (web workers, react-native) lack needed support.
{
write: function write() {},
read: function read() {
return null;
},
remove: function remove() {}
};
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
if (typeof url !== 'string') {
return false;
}
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
function combineURLs(baseURL, relativeURL) {
return relativeURL ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL;
}
var malformedHttpProtocol = /^https?:(?!\/\/)/i;
var httpProtocolControlCharacters = /[\t\n\r]/g;
function stripLeadingC0ControlOrSpace(url) {
var i = 0;
while (i < url.length && url.charCodeAt(i) <= 0x20) {
i++;
}
return url.slice(i);
}
function normalizeURLForProtocolCheck(url) {
return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
}
function assertValidHttpProtocolURL(url, config) {
if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
throw new AxiosError('Invalid URL: missing "//" after protocol', AxiosError.ERR_INVALID_URL, config);
}
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
assertValidHttpProtocolURL(requestedURL, config);
var isRelativeUrl = !isAbsoluteURL(requestedURL);
if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
assertValidHttpProtocolURL(baseURL, config);
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
var headersToObject = function headersToObject(thing) {
return thing instanceof AxiosHeaders ? _objectSpread2({}, thing) : thing;
};
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config1 = config1 || {};
config2 = config2 || {};
// Use a null-prototype object so that downstream reads such as `config.auth`
// or `config.baseURL` cannot inherit polluted values from Object.prototype.
// `hasOwnProperty` is restored as a non-enumerable own slot to preserve
// ergonomics for user code that relies on it.
var config = Object.create(null);
Object.defineProperty(config, 'hasOwnProperty', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: Object.prototype.hasOwnProperty,
enumerable: false,
writable: true,
configurable: true
});
function getMergedValue(target, source, prop, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({
caseless: caseless
}, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(a, b, prop, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, prop, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, prop, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
function getMergedTransitionalOption(prop) {
var transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
if (!utils$1.isUndefined(transitional2)) {
if (utils$1.isPlainObject(transitional2)) {
if (utils$1.hasOwnProp(transitional2, prop)) {
return transitional2[prop];
}
} else {
return undefined;
}
}
var transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
return transitional1[prop];
}
return undefined;
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (utils$1.hasOwnProp(config2, prop)) {
return getMergedValue(a, b);
} else if (utils$1.hasOwnProp(config1, prop)) {
return getMergedValue(undefined, a);
}
}
var mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
allowedSocketPaths: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: function headers(a, b, prop) {
return mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true);
}
};
utils$1.forEach(Object.keys(_objectSpread2(_objectSpread2({}, config1), config2)), function computeConfigValue(prop) {
if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
var merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
var a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
var b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
var configValue = merge(a, b, prop);
utils$1.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue);
});
if (utils$1.hasOwnProp(config2, 'validateStatus') && utils$1.isUndefined(config2.validateStatus) && getMergedTransitionalOption('validateStatusUndefinedResolves') === false) {
if (utils$1.hasOwnProp(config1, 'validateStatus')) {
config.validateStatus = getMergedValue(undefined, config1.validateStatus);
} else {
delete config.validateStatus;
}
}
return config;
}
var FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
function setFormDataHeaders(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders || {}).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
val = _ref2[1];
if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
var encodeUTF8$1 = function encodeUTF8(str) {
return encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, function (_, hex) {
return String.fromCharCode(parseInt(hex, 16));
});
};
function resolveConfig(config) {
var newConfig = mergeConfig({}, config);
// Read only own properties to prevent prototype pollution gadgets
// (e.g. Object.prototype.baseURL = 'https://evil.com').
var own = function own(key) {
return utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined;
};
var data = own('data');
var withXSRFToken = own('withXSRFToken');
var xsrfHeaderName = own('xsrfHeaderName');
var xsrfCookieName = own('xsrfCookieName');
var headers = own('headers');
var auth = own('auth');
var baseURL = own('baseURL');
var allowAbsoluteUrls = own('allowAbsoluteUrls');
var url = own('url');
newConfig.headers = headers = AxiosHeaders.from(headers);
newConfig.url = buildURL(buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig), own('params'), own('paramsSerializer'));
// HTTP basic authentication
if (auth) {
var username = utils$1.getSafeProp(auth, 'username') || '';
var password = utils$1.getSafeProp(auth, 'password') || '';
try {
headers.set('Authorization', 'Basic ' + btoa(username + ':' + (password ? encodeUTF8$1(password) : '')));
} catch (e) {
throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config);
}
}
if (utils$1.isFormData(data)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv || utils$1.isReactNative(data)) {
headers.setContentType(undefined); // browser/web worker/RN handles it
} else if (utils$1.isFunction(data.getHeaders)) {
// Node.js FormData (like form-data package)
setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
if (utils$1.isFunction(withXSRFToken)) {
withXSRFToken = withXSRFToken(newConfig);
}
// Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
// and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
// the XSRF token cross-origin.
var shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
if (shouldSendXSRF) {
var xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
}
var isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
var xhrAdapter = isXHRAdapterSupported && function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var _config = resolveConfig(config);
var requestData = _config.data;
var requestHeaders = AxiosHeaders.from(_config.headers).normalize();
var responseType = _config.responseType,
onUploadProgress = _config.onUploadProgress,
onDownloadProgress = _config.onDownloadProgress;
var onCanceled;
var uploadThrottled, downloadThrottled;
var flushUpload, flushDownload;
function done() {
flushUpload && flushUpload(); // flush events
flushDownload && flushDownload(); // flush events
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener('abort', onCanceled);
}
var request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
var responseHeaders = AxiosHeaders.from('getAllResponseHeaders' in request && request.getAllResponseHeaders());
var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith('file:'))) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
done();
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError(event) {
// Browsers deliver a ProgressEvent in XHR onerror
// (message may be empty; when present, surface it)
// See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
var msg = event && event.message ? event.message : 'Network Error';
var err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
// attach the underlying event for consumers who want details
err.event = event || null;
reject(err);
done();
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request));
done();
// Clean up request
request = null;
};
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = _config.responseType;
}
// Handle progress if needed
if (onDownloadProgress) {
var _progressEventReducer = progressEventReducer(onDownloadProgress, true);
var _progressEventReducer2 = _slicedToArray(_progressEventReducer, 2);
downloadThrottled = _progressEventReducer2[0];
flushDownload = _progressEventReducer2[1];
request.addEventListener('progress', downloadThrottled);
}
// Not all browsers support upload events
if (onUploadProgress && request.upload) {
var _progressEventReducer3 = progressEventReducer(onUploadProgress);
var _progressEventReducer4 = _slicedToArray(_progressEventReducer3, 2);
uploadThrottled = _progressEventReducer4[0];
flushUpload = _progressEventReducer4[1];
request.upload.addEventListener('progress', uploadThrottled);
request.upload.addEventListener('loadend', flushUpload);
}
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function onCanceled(cancel) {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
done();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
}
}
var protocol = parseProtocol(_config.url);
if (protocol && !platform.protocols.includes(protocol)) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
done();
return;
}
// Send the request
request.send(requestData || null);
});
};
var composeSignals = function composeSignals(signals, timeout) {
signals = signals ? signals.filter(Boolean) : [];
if (!timeout && !signals.length) {
return;
}
var controller = new AbortController();
var aborted = false;
var onabort = function onabort(reason) {
if (!aborted) {
aborted = true;
unsubscribe();
var err = reason instanceof Error ? reason : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
}
};
var timer = timeout && setTimeout(function () {
timer = null;
onabort(new AxiosError("timeout of ".concat(timeout, "ms exceeded"), AxiosError.ETIMEDOUT));
}, timeout);
var unsubscribe = function unsubscribe() {
if (!signals) {
return;
}
timer && clearTimeout(timer);
timer = null;
signals.forEach(function (signal) {
signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
});
signals = null;
};
signals.forEach(function (signal) {
return signal.addEventListener('abort', onabort, {
once: true
});
});
var signal = controller.signal;
signal.unsubscribe = function () {
return utils$1.asap(unsubscribe);
};
return signal;
};
var streamChunk = /*#__PURE__*/_regenerator().m(function streamChunk(chunk, chunkSize) {
var len, pos, end;
return _regenerator().w(function (_context) {
while (1) switch (_context.n) {
case 0:
len = chunk.byteLength;
if (!(!chunkSize || len < chunkSize)) {
_context.n = 2;
break;
}
_context.n = 1;
return chunk;
case 1:
return _context.a(2);
case 2:
pos = 0;
case 3:
if (!(pos < len)) {
_context.n = 5;
break;
}
end = pos + chunkSize;
_context.n = 4;
return chunk.slice(pos, end);
case 4:
pos = end;
_context.n = 3;
break;
case 5:
return _context.a(2);
}
}, streamChunk);
});
var readBytes = /*#__PURE__*/function () {
var _ref = _wrapAsyncGenerator(/*#__PURE__*/_regenerator().m(function _callee(iterable, chunkSize) {
var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, chunk, _t;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.p = _context2.n) {
case 0:
_iteratorAbruptCompletion = false;
_didIteratorError = false;
_context2.p = 1;
_iterator = _asyncIterator(readStream(iterable));
case 2:
_context2.n = 3;
return _awaitAsyncGenerator(_iterator.next());
case 3:
if (!(_iteratorAbruptCompletion = !(_step = _context2.v).done)) {
_context2.n = 5;
break;
}
chunk = _step.value;
return _context2.d(_regeneratorValues(_asyncGeneratorDelegate(_asyncIterator(streamChunk(chunk, chunkSize)))), 4);
case 4:
_iteratorAbruptCompletion = false;
_context2.n = 2;
break;
case 5:
_context2.n = 7;
break;
case 6:
_context2.p = 6;
_t = _context2.v;
_didIteratorError = true;
_iteratorError = _t;
case 7:
_context2.p = 7;
_context2.p = 8;
if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) {
_context2.n = 9;
break;
}
_context2.n = 9;
return _awaitAsyncGenerator(_iterator["return"]());
case 9:
_context2.p = 9;
if (!_didIteratorError) {
_context2.n = 10;
break;
}
throw _iteratorError;
case 10:
return _context2.f(9);
case 11:
return _context2.f(7);
case 12:
return _context2.a(2);
}
}, _callee, null, [[8,, 9, 11], [1, 6, 7, 12]]);
}));
return function readBytes(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
var readStream = /*#__PURE__*/function () {
var _ref2 = _wrapAsyncGenerator(/*#__PURE__*/_regenerator().m(function _callee2(stream) {
var reader, _yield$_awaitAsyncGen, done, value;
return _regenerator().w(function (_context3) {
while (1) switch (_context3.p = _context3.n) {
case 0:
if (!stream[Symbol.asyncIterator]) {
_context3.n = 2;
break;
}
return _context3.d(_regeneratorValues(_asyncGeneratorDelegate(_asyncIterator(stream))), 1);
case 1:
return _context3.a(2);
case 2:
reader = stream.getReader();
_context3.p = 3;
case 4:
_context3.n = 5;
return _awaitAsyncGenerator(reader.read());
case 5:
_yield$_awaitAsyncGen = _context3.v;
done = _yield$_awaitAsyncGen.done;
value = _yield$_awaitAsyncGen.value;
if (!done) {
_context3.n = 6;
break;
}
return _context3.a(3, 8);
case 6:
_context3.n = 7;
return value;
case 7:
_context3.n = 4;
break;
case 8:
_context3.p = 8;
_context3.n = 9;
return _awaitAsyncGenerator(reader.cancel());
case 9:
return _context3.f(8);
case 10:
return _context3.a(2);
}
}, _callee2, null, [[3,, 8, 10]]);
}));
return function readStream(_x3) {
return _ref2.apply(this, arguments);
};
}();
var trackStream = function trackStream(stream, chunkSize, onProgress, onFinish) {
var iterator = readBytes(stream, chunkSize);
var bytes = 0;
var done;
var _onFinish = function _onFinish(e) {
if (!done) {
done = true;
onFinish && onFinish(e);
}
};
return new ReadableStream({
pull: function pull(controller) {
return _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
var _yield$iterator$next, _done, value, len, loadedBytes, _t2;
return _regenerator().w(function (_context4) {
while (1) switch (_context4.p = _context4.n) {
case 0:
_context4.p = 0;
_context4.n = 1;
return iterator.next();
case 1:
_yield$iterator$next = _context4.v;
_done = _yield$iterator$next.done;
value = _yield$iterator$next.value;
if (!_done) {
_context4.n = 2;
break;
}
_onFinish();
controller.close();
return _context4.a(2);
case 2:
len = value.byteLength;
if (onProgress) {
loadedBytes = bytes += len;
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
_context4.n = 4;
break;
case 3:
_context4.p = 3;
_t2 = _context4.v;
_onFinish(_t2);
throw _t2;
case 4:
return _context4.a(2);
}
}, _callee3, null, [[0, 3]]);
}))();
},
cancel: function cancel(reason) {
_onFinish(reason);
return iterator["return"]();
}
}, {
highWaterMark: 2
});
};
/**
* Estimate decoded byte length of a data:// URL *without* allocating large buffers.
* - For base64: compute exact decoded size using length and padding;
* handle %XX at the character-count level (no string allocation).
* - For non-base64: compute the exact percent-decoded UTF-8 byte length.
*
* @param {string} url
* @returns {number}
*/
var isHexDigit = function isHexDigit(charCode) {
return charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70 || charCode >= 97 && charCode <= 102;
};
var isPercentEncodedByte = function isPercentEncodedByte(str, i, len) {
return i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
};
function estimateDataURLDecodedBytes(url) {
if (!url || typeof url !== 'string') return 0;
if (!url.startsWith('data:')) return 0;
var comma = url.indexOf(',');
if (comma < 0) return 0;
var meta = url.slice(5, comma);
var body = url.slice(comma + 1);
var isBase64 = /;base64/i.test(meta);
if (isBase64) {
var effectiveLen = body.length;
var len = body.length; // cache length
for (var i = 0; i < len; i++) {
if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
var a = body.charCodeAt(i + 1);
var b = body.charCodeAt(i + 2);
var isHex = isHexDigit(a) && isHexDigit(b);
if (isHex) {
effectiveLen -= 2;
i += 2;
}
}
}
var pad = 0;
var idx = len - 1;
var tailIsPct3D = function tailIsPct3D(j) {
return j >= 2 && body.charCodeAt(j - 2) === 37 &&
// '%'
body.charCodeAt(j - 1) === 51 && (
// '3'
body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100);
}; // 'D' or 'd'
if (idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
idx--;
} else if (tailIsPct3D(idx)) {
pad++;
idx -= 3;
}
}
if (pad === 1 && idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
} else if (tailIsPct3D(idx)) {
pad++;
}
}
var groups = Math.floor(effectiveLen / 4);
var _bytes = groups * 3 - (pad || 0);
return _bytes > 0 ? _bytes : 0;
}
// Compute UTF-8 byte length directly from UTF-16 code units without allocating
// a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
// Valid %XX triplets count as one decoded byte; this matches the bytes that
// decodeURIComponent(body) would produce before Buffer re-encodes the string.
var bytes = 0;
for (var _i = 0, _len = body.length; _i < _len; _i++) {
var c = body.charCodeAt(_i);
if (c === 37 /* '%' */ && isPercentEncodedByte(body, _i, _len)) {
bytes += 1;
_i += 2;
} else if (c < 0x80) {
bytes += 1;
} else if (c < 0x800) {
bytes += 2;
} else if (c >= 0xd800 && c <= 0xdbff && _i + 1 < _len) {
var next = body.charCodeAt(_i + 1);
if (next >= 0xdc00 && next <= 0xdfff) {
bytes += 4;
_i++;
} else {
bytes += 3;
}
} else {
bytes += 3;
}
}
return bytes;
}
var VERSION = "1.18.1";
var DEFAULT_CHUNK_SIZE = 64 * 1024;
var isFunction = utils$1.isFunction;
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
var encodeUTF8 = function encodeUTF8(str) {
return encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, function (_, hex) {
return String.fromCharCode(parseInt(hex, 16));
});
};
// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
// Decode before composing the `auth` option so credentials such as
// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
// original value for malformed input so a bad encoding never throws.
var decodeURIComponentSafe = function decodeURIComponentSafe(value) {
if (!utils$1.isString(value)) {
return value;
}
try {
return decodeURIComponent(value);
} catch (error) {
return value;
}
};
var test = function test(fn) {
try {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return !!fn.apply(void 0, args);
} catch (e) {
return false;
}
};
var maybeWithAuthCredentials = function maybeWithAuthCredentials(url) {
var protocolIndex = url.indexOf('://');
var urlToCheck = url;
if (protocolIndex !== -1) {
urlToCheck = urlToCheck.slice(protocolIndex + 3);
}
return urlToCheck.includes('@') || urlToCheck.includes(':');
};
var factory = function factory(env) {
var globalObject = utils$1.global !== undefined && utils$1.global !== null ? utils$1.global : globalThis;
var ReadableStream = globalObject.ReadableStream,
TextEncoder = globalObject.TextEncoder;
env = utils$1.merge.call({
skipUndefined: true
}, {
Request: globalObject.Request,
Response: globalObject.Response
}, env);
var _env = env,
envFetch = _env.fetch,
Request = _env.Request,
Response = _env.Response;
var isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
var isRequestSupported = isFunction(Request);
var isResponseSupported = isFunction(Response);
if (!isFetchSupported) {
return false;
}
var isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
var encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? function (encoder) {
return function (str) {
return encoder.encode(str);
};
}(new TextEncoder()) : (/*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(str) {
var _t, _t2;
return _regenerator().w(function (_context) {
while (1) switch (_context.n) {
case 0:
_t = Uint8Array;
_context.n = 1;
return new Request(str).arrayBuffer();
case 1:
_t2 = _context.v;
return _context.a(2, new _t(_t2));
}
}, _callee);
}));
return function (_x) {
return _ref.apply(this, arguments);
};
}()));
var supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(function () {
var duplexAccessed = false;
var request = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
}
});
var hasContentType = request.headers.has('Content-Type');
if (request.body != null) {
request.body.cancel();
}
return duplexAccessed && !hasContentType;
});
var supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(function () {
return utils$1.isReadableStream(new Response('').body);
});
var resolvers = {
stream: supportsResponseStream && function (res) {
return res.body;
}
};
isFetchSupported && function () {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(function (type) {
!resolvers[type] && (resolvers[type] = function (res, config) {
var method = res && res[type];
if (method) {
return method.call(res);
}
throw new AxiosError("Response type '".concat(type, "' is not supported"), AxiosError.ERR_NOT_SUPPORT, config);
});
});
}();
var getBodyLength = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(body) {
var _request;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.n) {
case 0:
if (!(body == null)) {
_context2.n = 1;
break;
}
return _context2.a(2, 0);
case 1:
if (!utils$1.isBlob(body)) {
_context2.n = 2;
break;
}
return _context2.a(2, body.size);
case 2:
if (!utils$1.isSpecCompliantForm(body)) {
_context2.n = 4;
break;
}
_request = new Request(platform.origin, {
method: 'POST',
body: body
});
_context2.n = 3;
return _request.arrayBuffer();
case 3:
return _context2.a(2, _context2.v.byteLength);
case 4:
if (!(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body))) {
_context2.n = 5;
break;
}
return _context2.a(2, body.byteLength);
case 5:
if (utils$1.isURLSearchParams(body)) {
body = body + '';
}
if (!utils$1.isString(body)) {
_context2.n = 7;
break;
}
_context2.n = 6;
return encodeText(body);
case 6:
return _context2.a(2, _context2.v.byteLength);
case 7:
return _context2.a(2);
}
}, _callee2);
}));
return function getBodyLength(_x2) {
return _ref2.apply(this, arguments);
};
}();
var resolveBodyLength = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(headers, body) {
var length;
return _regenerator().w(function (_context3) {
while (1) switch (_context3.n) {
case 0:
length = utils$1.toFiniteNumber(headers.getContentLength());
return _context3.a(2, length == null ? getBodyLength(body) : length);
}
}, _callee3);
}));
return function resolveBodyLength(_x3, _x4) {
return _ref3.apply(this, arguments);
};
}();
return /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4(config) {
var _resolveConfig, url, method, data, signal, cancelToken, timeout, onDownloadProgress, onUploadProgress, responseType, headers, _resolveConfig$withCr, withCredentials, fetchOptions, maxContentLength, maxBodyLength, hasMaxContentLength, hasMaxBodyLength, own, _fetch, composedSignal, request, unsubscribe, requestContentLength, pendingBodyError, maxBodyLengthError, auth, configAuth, username, password, parsedURL, urlUsername, urlPassword, estimated, outboundLength, mustEnforceStreamBody, trackRequestStream, _request, contentTypeHeader, _ref5, _ref6, onProgress, flush, isCredentialsSupported, contentType, resolvedOptions, response, responseHeaders, declaredLength, isStreamResponse, options, responseContentLength, _ref7, _ref8, _onProgress, _flush, bytesRead, onChunkProgress, responseData, materializedSize, canceledError, networkError, _t3, _t4;
return _regenerator().w(function (_context4) {
while (1) switch (_context4.p = _context4.n) {
case 0:
_resolveConfig = resolveConfig(config), url = _resolveConfig.url, method = _resolveConfig.method, data = _resolveConfig.data, signal = _resolveConfig.signal, cancelToken = _resolveConfig.cancelToken, timeout = _resolveConfig.timeout, onDownloadProgress = _resolveConfig.onDownloadProgress, onUploadProgress = _resolveConfig.onUploadProgress, responseType = _resolveConfig.responseType, headers = _resolveConfig.headers, _resolveConfig$withCr = _resolveConfig.withCredentials, withCredentials = _resolveConfig$withCr === void 0 ? 'same-origin' : _resolveConfig$withCr, fetchOptions = _resolveConfig.fetchOptions, maxContentLength = _resolveConfig.maxContentLength, maxBodyLength = _resolveConfig.maxBodyLength;
hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
own = function own(key) {
return utils$1.hasOwnProp(config, key) ? config[key] : undefined;
};
_fetch = envFetch || fetch;
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
request = null;
unsubscribe = composedSignal && composedSignal.unsubscribe && function () {
composedSignal.unsubscribe();
};
// AxiosError we raise while the request body is being streamed. Captured
// by identity so the catch block can surface it directly, regardless of
// how the runtime wraps the resulting fetch rejection (undici exposes it
// as `err.cause`; some browsers drop the original error entirely).
pendingBodyError = null;
maxBodyLengthError = function maxBodyLengthError() {
return new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, request);
};
_context4.p = 1;
// HTTP basic authentication
auth = undefined;
configAuth = own('auth');
if (configAuth) {
username = utils$1.getSafeProp(configAuth, 'username') || '';
password = utils$1.getSafeProp(configAuth, 'password') || '';
auth = {
username: username,
password: password
};
}
if (maybeWithAuthCredentials(url)) {
parsedURL = new URL(url, platform.origin);
if (!auth && (parsedURL.username || parsedURL.password)) {
urlUsername = decodeURIComponentSafe(parsedURL.username);
urlPassword = decodeURIComponentSafe(parsedURL.password);
auth = {
username: urlUsername,
password: urlPassword
};
}
if (parsedURL.username || parsedURL.password) {
parsedURL.username = '';
parsedURL.password = '';
url = parsedURL.href;
}
}
if (auth) {
headers["delete"]('authorization');
headers.set('Authorization', 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || ''))));
}
// Enforce maxContentLength for data: URLs up-front so we never materialize
// an oversized payload. The HTTP adapter applies the same check (see http.js
// "if (protocol === 'data:')" branch).
if (!(hasMaxContentLength && typeof url === 'string' && url.startsWith('data:'))) {
_context4.n = 2;
break;
}
estimated = estimateDataURLDecodedBytes(url);
if (!(estimated > maxContentLength)) {
_context4.n = 2;
break;
}
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
case 2:
if (!(hasMaxBodyLength && method !== 'get' && method !== 'head')) {
_context4.n = 4;
break;
}
_context4.n = 3;
return getBodyLength(data);
case 3:
outboundLength = _context4.v;
if (!(typeof outboundLength === 'number' && isFinite(outboundLength))) {
_context4.n = 4;
break;
}
requestContentLength = outboundLength;
if (!(outboundLength > maxBodyLength)) {
_context4.n = 4;
break;
}
throw maxBodyLengthError();
case 4:
// A streamed body under maxBodyLength must be counted as fetch consumes
// it; its size is never trusted from a caller-declared Content-Length.
mustEnforceStreamBody = hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
trackRequestStream = function trackRequestStream(stream, onProgress, flush) {
return trackStream(stream, DEFAULT_CHUNK_SIZE, function (loadedBytes) {
if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
throw pendingBodyError = maxBodyLengthError();
}
onProgress && onProgress(loadedBytes);
}, flush);
};
if (!(supportsRequestStream && method !== 'get' && method !== 'head' && (onUploadProgress || mustEnforceStreamBody))) {
_context4.n = 8;
break;
}
if (!(requestContentLength == null)) {
_context4.n = 6;
break;
}
_context4.n = 5;
return resolveBodyLength(headers, data);
case 5:
_t3 = _context4.v;
_context4.n = 7;
break;
case 6:
_t3 = requestContentLength;
case 7:
requestContentLength = _t3;
// A declared length of 0 is only trusted to skip the wrap when we are
// not enforcing a stream limit (which must not rely on that header).
if (requestContentLength !== 0 || mustEnforceStreamBody) {
_request = new Request(url, {
method: 'POST',
body: data,
duplex: 'half'
});
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
_ref5 = onUploadProgress && progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))) || [], _ref6 = _slicedToArray(_ref5, 2), onProgress = _ref6[0], flush = _ref6[1];
data = trackRequestStream(_request.body, onProgress, flush);
}
}
_context4.n = 10;
break;
case 8:
if (!(mustEnforceStreamBody && !isRequestSupported && isReadableStreamSupported && method !== 'get' && method !== 'head')) {
_context4.n = 9;
break;
}
data = trackRequestStream(data);
_context4.n = 10;
break;
case 9:
if (!(mustEnforceStreamBody && isRequestSupported && !supportsRequestStream && method !== 'get' && method !== 'head')) {
_context4.n = 10;
break;
}
throw new AxiosError('Stream request bodies are not supported by the current fetch implementation', AxiosError.ERR_NOT_SUPPORT, config, request);
case 10:
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype; // If data is FormData and Content-Type is multipart/form-data without boundary,
// delete it so fetch can set it correctly with the boundary
if (utils$1.isFormData(data)) {
contentType = headers.getContentType();
if (contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType)) {
headers["delete"]('content-type');
}
}
// Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
headers.set('User-Agent', 'axios/' + VERSION, false);
resolvedOptions = _objectSpread2(_objectSpread2({}, fetchOptions), {}, {
signal: composedSignal,
method: method.toUpperCase(),
headers: toByteStringHeaderObject(headers.normalize()),
body: data,
duplex: 'half',
credentials: isCredentialsSupported ? withCredentials : undefined
});
request = isRequestSupported && new Request(url, resolvedOptions);
_context4.n = 11;
return isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions);
case 11:
response = _context4.v;
responseHeaders = AxiosHeaders.from(response.headers); // Cheap pre-check: if the server honestly declares a content-length that
// already exceeds the cap, reject before we start streaming.
if (!hasMaxContentLength) {
_context4.n = 12;
break;
}
declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
if (!(declaredLength != null && declaredLength > maxContentLength)) {
_context4.n = 12;
break;
}
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
case 12:
isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
options = {};
['status', 'statusText', 'headers'].forEach(function (prop) {
options[prop] = response[prop];
});
responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
_ref7 = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [], _ref8 = _slicedToArray(_ref7, 2), _onProgress = _ref8[0], _flush = _ref8[1];
bytesRead = 0;
onChunkProgress = function onChunkProgress(loadedBytes) {
if (hasMaxContentLength) {
bytesRead = loadedBytes;
if (bytesRead > maxContentLength) {
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
}
}
_onProgress && _onProgress(loadedBytes);
};
response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, function () {
_flush && _flush();
unsubscribe && unsubscribe();
}), options);
}
responseType = responseType || 'text';
_context4.n = 13;
return resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
case 13:
responseData = _context4.v;
if (!(hasMaxContentLength && !supportsResponseStream && !isStreamResponse)) {
_context4.n = 14;
break;
}
if (responseData != null) {
if (typeof responseData.byteLength === 'number') {
materializedSize = responseData.byteLength;
} else if (typeof responseData.size === 'number') {
materializedSize = responseData.size;
} else if (typeof responseData === 'string') {
materializedSize = typeof TextEncoder === 'function' ? new TextEncoder().encode(responseData).byteLength : responseData.length;
}
}
if (!(typeof materializedSize === 'number' && materializedSize > maxContentLength)) {
_context4.n = 14;
break;
}
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
case 14:
!isStreamResponse && unsubscribe && unsubscribe();
_context4.n = 15;
return new Promise(function (resolve, reject) {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders.from(response.headers),
status: response.status,
statusText: response.statusText,
config: config,
request: request
});
});
case 15:
return _context4.a(2, _context4.v);
case 16:
_context4.p = 16;
_t4 = _context4.v;
unsubscribe && unsubscribe();
// Safari can surface fetch aborts as a DOMException-like object whose
// branded getters throw. Prefer our composed signal reason before reading
// the caught error, preserving timeout vs cancellation semantics.
if (!(composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError)) {
_context4.n = 17;
break;
}
canceledError = composedSignal.reason;
canceledError.config = config;
request && (canceledError.request = request);
if (_t4 !== canceledError) {
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(canceledError, 'cause', {
__proto__: null,
value: _t4,
writable: true,
enumerable: false,
configurable: true
});
}
throw canceledError;
case 17:
if (!pendingBodyError) {
_context4.n = 18;
break;
}
request && !pendingBodyError.request && (pendingBodyError.request = request);
throw pendingBodyError;
case 18:
if (!(_t4 instanceof AxiosError)) {
_context4.n = 19;
break;
}
request && !_t4.request && (_t4.request = request);
throw _t4;
case 19:
if (!(_t4 && _t4.name === 'TypeError' && /Load failed|fetch/i.test(_t4.message))) {
_context4.n = 20;
break;
}
networkError = new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, _t4 && _t4.response); // Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(networkError, 'cause', {
__proto__: null,
value: _t4.cause || _t4,
writable: true,
enumerable: false,
configurable: true
});
throw networkError;
case 20:
throw AxiosError.from(_t4, _t4 && _t4.code, config, request, _t4 && _t4.response);
case 21:
return _context4.a(2);
}
}, _callee4, null, [[1, 16]]);
}));
return function (_x5) {
return _ref4.apply(this, arguments);
};
}();
};
var seedCache = new Map();
var getFetch = function getFetch(config) {
var env = config && config.env || {};
var fetch = env.fetch,
Request = env.Request,
Response = env.Response;
var seeds = [Request, Response, fetch];
var len = seeds.length,
i = len,
seed,
target,
map = seedCache;
while (i--) {
seed = seeds[i];
target = map.get(seed);
target === undefined && map.set(seed, target = i ? new Map() : factory(env));
map = target;
}
return target;
};
getFetch();
/**
* Known adapters mapping.
* Provides environment-specific adapters for Axios:
* - `http` for Node.js
* - `xhr` for browsers
* - `fetch` for fetch API-based requests
*
* @type {Object<string, Function|Object>}
*/
var knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: {
get: getFetch
}
};
// Assign adapter names for easier debugging and identification
utils$1.forEach(knownAdapters, function (fn, value) {
if (fn) {
try {
// Null-proto descriptors so a polluted Object.prototype.get cannot turn
// these data descriptors into accessor descriptors on the way in.
Object.defineProperty(fn, 'name', {
__proto__: null,
value: value
});
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {
__proto__: null,
value: value
});
}
});
/**
* Render a rejection reason string for unknown or unsupported adapters
*
* @param {string} reason
* @returns {string}
*/
var renderReason = function renderReason(reason) {
return "- ".concat(reason);
};
/**
* Check if the adapter is resolved (function, null, or false)
*
* @param {Function|null|false} adapter
* @returns {boolean}
*/
var isResolvedHandle = function isResolvedHandle(adapter) {
return utils$1.isFunction(adapter) || adapter === null || adapter === false;
};
/**
* Get the first suitable adapter from the provided list.
* Tries each adapter in order until a supported one is found.
* Throws an AxiosError if no adapter is suitable.
*
* @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
* @param {Object} config - Axios request configuration
* @throws {AxiosError} If no suitable adapter is available
* @returns {Function} The resolved adapter function
*/
function getAdapter(adapters, config) {
adapters = utils$1.isArray(adapters) ? adapters : [adapters];
var _adapters = adapters,
length = _adapters.length;
var nameOrAdapter;
var adapter;
var rejectedReasons = {};
for (var i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
var id = void 0;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError("Unknown adapter '".concat(id, "'"));
}
}
if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
var reasons = Object.entries(rejectedReasons).map(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
id = _ref2[0],
state = _ref2[1];
return "adapter ".concat(id, " ") + (state === false ? 'is not supported by the environment' : 'is not available in the build');
});
var s = length ? reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0]) : 'as no adapter specified';
throw new AxiosError("There is no suitable adapter to dispatch the request " + s, AxiosError.ERR_NOT_SUPPORT);
}
return adapter;
}
/**
* Exports Axios adapters and utility to resolve an adapter
*/
var adapters = {
/**
* Resolve an adapter from a list of adapter names or functions.
* @type {Function}
*/
getAdapter: getAdapter,
/**
* Exposes all known adapters
* @type {Object<string, Function|Object>}
*/
adapters: knownAdapters
};
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders.from(config.headers);
// Transform request data
config.data = transformData.call(config, config.transformRequest);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
var adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Expose the current response on config so that transformResponse can
// attach it to any AxiosError it throws (e.g. on JSON parse failure).
// We clean it up afterwards to avoid polluting the config object.
config.response = response;
try {
response.data = transformData.call(config, config.transformResponse, response);
} finally {
delete config.response;
}
response.headers = AxiosHeaders.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
config.response = reason.response;
try {
reason.response.data = transformData.call(config, config.transformResponse, reason.response);
} finally {
delete config.response;
}
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
var validators$1 = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function (type, i) {
validators$1[type] = function validator(thing) {
return _typeof(thing) === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators$1.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return function (value, opt, opts) {
if (validator === false) {
throw new AxiosError(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), AxiosError.ERR_DEPRECATED);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future'));
}
return validator ? validator(value, opt, opts) : true;
};
};
validators$1.spelling = function spelling(correctSpelling) {
return function (value, opt) {
// eslint-disable-next-line no-console
console.warn("".concat(opt, " is likely a misspelling of ").concat(correctSpelling));
return true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (_typeof(options) !== 'object' || options === null) {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
var keys = Object.keys(options);
var i = keys.length;
while (i-- > 0) {
var opt = keys[i];
// Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
// a non-function validator and cause a TypeError.
var validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
var validator = {
assertOptions: assertOptions,
validators: validators$1
};
var validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
var Axios = /*#__PURE__*/function () {
function Axios(instanceConfig) {
_classCallCheck(this, Axios);
this.defaults = instanceConfig || {};
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
return _createClass(Axios, [{
key: "request",
value: (function () {
var _request2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(configOrUrl, config) {
var dummy, stack, firstNewlineIndex, secondNewlineIndex, stackWithoutTwoTopLines, _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
_context.n = 1;
return this._request(configOrUrl, config);
case 1:
return _context.a(2, _context.v);
case 2:
_context.p = 2;
_t = _context.v;
if (_t instanceof Error) {
dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
// slice off the Error: ... line
stack = function () {
if (!dummy.stack) {
return '';
}
var firstNewlineIndex = dummy.stack.indexOf('\n');
return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
}();
try {
if (!_t.stack) {
_t.stack = stack;
// match without the 2 top stack lines
} else if (stack) {
firstNewlineIndex = stack.indexOf('\n');
secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
stackWithoutTwoTopLines = secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
if (!String(_t.stack).endsWith(stackWithoutTwoTopLines)) {
_t.stack += '\n' + stack;
}
}
} catch (e) {
// ignore the case where "stack" is an un-writable property
}
}
throw _t;
case 3:
return _context.a(2);
}
}, _callee, this, [[0, 2]]);
}));
function request(_x, _x2) {
return _request2.apply(this, arguments);
}
return request;
}())
}, {
key: "_request",
value: function _request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
var _config = config,
transitional = _config.transitional,
paramsSerializer = _config.paramsSerializer,
headers = _config.headers;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators["boolean"]),
forcedJSONParsing: validators.transitional(validators["boolean"]),
clarifyTimeoutError: validators.transitional(validators["boolean"]),
legacyInterceptorReqResOrdering: validators.transitional(validators["boolean"]),
advertiseZstdAcceptEncoding: validators.transitional(validators["boolean"]),
validateStatusUndefinedResolves: validators.transitional(validators["boolean"])
}, false);
}
if (paramsSerializer != null) {
if (utils$1.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer
};
} else {
validator.assertOptions(paramsSerializer, {
encode: validators["function"],
serialize: validators["function"]
}, true);
}
}
// Set config.allowAbsoluteUrls
if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
} else {
config.allowAbsoluteUrls = true;
}
validator.assertOptions(config, {
baseUrl: validators.spelling('baseURL'),
withXsrfToken: validators.spelling('withXSRFToken')
}, true);
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
var contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
headers && utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], function (method) {
delete headers[method];
});
config.headers = AxiosHeaders.concat(contextHeaders, headers);
// filter out skipped interceptors
var requestInterceptorChain = [];
var synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
var transitional = config.transitional || transitionalDefaults;
var legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering;
if (legacyInterceptorReqResOrdering) {
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
} else {
requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
}
});
var responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
var promise;
var i = 0;
var len;
if (!synchronousRequestInterceptors) {
var chain = [dispatchRequest.bind(this), undefined];
chain.unshift.apply(chain, requestInterceptorChain);
chain.push.apply(chain, responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
var newConfig = config;
while (i < len) {
var onFulfilled = requestInterceptorChain[i++];
var onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
}, {
key: "getUri",
value: function getUri(config) {
config = mergeConfig(this.defaults, config);
var fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}]);
}(); // Provide aliases for supported request methods
utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function (url, config) {
return this.request(mergeConfig(config || {}, {
method: method,
url: url,
data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined
}));
};
});
utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method: method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url: url,
data: data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
// QUERY is a safe/idempotent read method; multipart form bodies don't fit
// its semantics, so no queryForm shorthand is generated.
if (method !== 'query') {
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
}
});
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
var CancelToken = /*#__PURE__*/function () {
function CancelToken(executor) {
_classCallCheck(this, CancelToken);
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
// eslint-disable-next-line func-names
this.promise.then(function (cancel) {
if (!token._listeners) return;
var i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = function (onfulfilled) {
var _resolve;
// eslint-disable-next-line func-names
var promise = new Promise(function (resolve) {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
return _createClass(CancelToken, [{
key: "throwIfRequested",
value: function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
}, {
key: "subscribe",
value: function subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
}, {
key: "unsubscribe",
value: function unsubscribe(listener) {
if (!this._listeners) {
return;
}
var index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
}, {
key: "toAbortSignal",
value: function toAbortSignal() {
var _this = this;
var controller = new AbortController();
var abort = function abort(err) {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = function () {
return _this.unsubscribe(abort);
};
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
}], [{
key: "source",
value: function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
}
}]);
}();
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* const args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
function isAxiosError(payload) {
return utils$1.isObject(payload) && payload.isAxiosError === true;
}
var HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
WebServerIsDown: 521,
ConnectionTimedOut: 522,
OriginIsUnreachable: 523,
TimeoutOccurred: 524,
SslHandshakeFailed: 525,
InvalidSslCertificate: 526
};
Object.entries(HttpStatusCode).forEach(function (_ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
HttpStatusCode[value] = key;
});
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils$1.extend(instance, Axios.prototype, context, {
allOwnKeys: true
});
// Copy context to instance
utils$1.extend(instance, context, null, {
allOwnKeys: true
});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders;
axios.formToJSON = function (thing) {
return formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
};
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode;
axios["default"] = axios;
return axios;
}));
//# sourceMappingURL=axios.js.map
+5
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
+5146
View File
@@ -0,0 +1,5146 @@
/*! Axios v1.18.1 Copyright (c) 2026 Matt Zabriskie and contributors */
'use strict';
/**
* Create a bound version of a function with a specified `this` context
*
* @param {Function} fn - The function to bind
* @param {*} thisArg - The value to be passed as the `this` parameter
* @returns {Function} A new function that will call the original function with the specified `this` context
*/
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// utils is a library of generic helper functions non-specific to axios
const { toString } = Object.prototype;
const { getPrototypeOf } = Object;
const { iterator, toStringTag } = Symbol;
/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (
({ hasOwnProperty }) =>
(obj, prop) =>
hasOwnProperty.call(obj, prop)
)(Object.prototype);
/**
* Walk the prototype chain (excluding the shared Object.prototype) looking for
* an own `prop`. This distinguishes genuine own/inherited members — including
* class accessors and template prototypes — from members injected via
* Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
* live on Object.prototype itself and are therefore never matched.
*
* @param {*} thing The value whose chain to inspect
* @param {string|symbol} prop The property key to look for
*
* @returns {boolean} True when `prop` is owned below Object.prototype
*/
const hasOwnInPrototypeChain = (thing, prop) => {
let obj = thing;
const seen = [];
while (obj != null && obj !== Object.prototype) {
if (seen.indexOf(obj) !== -1) {
return false;
}
seen.push(obj);
if (hasOwnProperty(obj, prop)) {
return true;
}
obj = getPrototypeOf(obj);
}
return false;
};
/**
* Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
* properties and members inherited from a non-Object.prototype source (a class
* instance or template object) are honored; a value reachable only through a
* polluted Object.prototype is ignored and `undefined` is returned.
*
* @param {*} obj The source object
* @param {string|symbol} prop The property key to read
*
* @returns {*} The resolved value, or undefined when unsafe/absent
*/
const getSafeProp = (obj, prop) =>
obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
const kindOf = ((cache) => (thing) => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));
const kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type;
};
const typeOfTest = (type) => (thing) => typeof thing === type;
/**
* Determine if a value is a non-null object
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
const { isArray } = Array;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return (
val !== null &&
!isUndefined(val) &&
val.constructor !== null &&
!isUndefined(val.constructor) &&
isFunction$1(val.constructor.isBuffer) &&
val.constructor.isBuffer(val)
);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
let result;
if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && isArrayBuffer(val.buffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction$1 = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
const isObject = (thing) => thing !== null && typeof thing === 'object';
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = (thing) => thing === true || thing === false;
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
const isPlainObject = (val) => {
if (!isObject(val)) {
return false;
}
const prototype = getPrototypeOf(val);
return (
(prototype === null ||
prototype === Object.prototype ||
getPrototypeOf(prototype) === null) &&
// Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
// Symbol.iterator as evidence the value is a tagged/iterable type rather
// than a plain object, while ignoring keys injected onto Object.prototype.
!hasOwnInPrototypeChain(val, toStringTag) &&
!hasOwnInPrototypeChain(val, iterator)
);
};
/**
* Determine if a value is an empty object (safely handles Buffers)
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an empty object, otherwise false
*/
const isEmptyObject = (val) => {
// Early return for non-objects or Buffers to prevent RangeError
if (!isObject(val) || isBuffer(val)) {
return false;
}
try {
return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
} catch (e) {
// Fallback for any other objects that might cause RangeError with Object.keys()
return false;
}
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFile = kindOfTest('File');
/**
* Determine if a value is a React Native Blob
* React Native "blob": an object with a `uri` attribute. Optionally, it can
* also have a `name` and `type` attribute to specify filename and content type
*
* @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
*
* @param {*} value The value to test
*
* @returns {boolean} True if value is a React Native Blob, otherwise false
*/
const isReactNativeBlob = (value) => {
return !!(value && typeof value.uri !== 'undefined');
};
/**
* Determine if environment is React Native
* ReactNative `FormData` has a non-standard `getParts()` method
*
* @param {*} formData The formData to test
*
* @returns {boolean} True if environment is React Native, otherwise false
*/
const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a FileList, otherwise false
*/
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
function getGlobal() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
return {};
}
const G = getGlobal();
const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
const isFormData = (thing) => {
if (!thing) return false;
if (FormDataCtor && thing instanceof FormDataCtor) return true;
// Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
const proto = getPrototypeOf(thing);
if (!proto || proto === Object.prototype) return false;
if (!isFunction$1(thing.append)) return false;
const kind = kindOf(thing);
return (
kind === 'formdata' ||
// detect form-data instance
(kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
);
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
const [isReadableStream, isRequest, isResponse, isHeaders] = [
'ReadableStream',
'Request',
'Response',
'Headers',
].map(kindOfTest);
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
const trim = (str) => {
return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array<unknown>} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn, { allOwnKeys = false } = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Buffer check
if (isBuffer(obj)) {
return;
}
// Iterate over object keys
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
/**
* Finds a key in an object, case-insensitive, returning the actual key name.
* Returns null if the object is a Buffer or if no match is found.
*
* @param {Object} obj - The object to search.
* @param {string} key - The key to find (case-insensitive).
* @returns {?string} The actual key name if found, otherwise null.
*/
function findKey(obj, key) {
if (isBuffer(obj)) {
return null;
}
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
/*eslint no-undef:0*/
if (typeof globalThis !== 'undefined') return globalThis;
return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* const result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge(...objs) {
const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
const result = {};
const assignValue = (val, key) => {
// Skip dangerous property names to prevent prototype pollution
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return;
}
// findKey lowercases the key, so caseless lookup only applies to strings —
// symbol keys are identity-matched.
const targetKey = (caseless && typeof key === 'string' && findKey(result, key)) || key;
// Read via own-prop only — a bare `result[targetKey]` walks the prototype
// chain, so a polluted Object.prototype value could surface here and get
// copied into the merged result.
const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
if (isPlainObject(existing) && isPlainObject(val)) {
result[targetKey] = merge(existing, val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else if (!skipUndefined || !isUndefined(val)) {
result[targetKey] = val;
}
};
for (let i = 0, l = objs.length; i < l; i++) {
const source = objs[i];
if (!source || isBuffer(source)) {
continue;
}
forEach(source, assignValue);
if (typeof source !== 'object' || isArray(source)) {
continue;
}
const symbols = Object.getOwnPropertySymbols(source);
for (let j = 0; j < symbols.length; j++) {
const symbol = symbols[j];
if (propertyIsEnumerable.call(source, symbol)) {
assignValue(source[symbol], symbol);
}
}
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys]
* @returns {Object} The resulting value of object a
*/
const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
forEach(
b,
(val, key) => {
if (thisArg && isFunction$1(val)) {
Object.defineProperty(a, key, {
// Null-proto descriptor so a polluted Object.prototype.get cannot
// hijack defineProperty's accessor-vs-data resolution.
__proto__: null,
value: bind(val, thisArg),
writable: true,
enumerable: true,
configurable: true,
});
} else {
Object.defineProperty(a, key, {
__proto__: null,
value: val,
writable: true,
enumerable: true,
configurable: true,
});
}
},
{ allOwnKeys }
);
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
const stripBOM = (content) => {
if (content.charCodeAt(0) === 0xfeff) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
const inherits = (constructor, superConstructor, props, descriptors) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
Object.defineProperty(constructor.prototype, 'constructor', {
__proto__: null,
value: constructor,
writable: true,
enumerable: false,
configurable: true,
});
Object.defineProperty(constructor, 'super', {
__proto__: null,
value: superConstructor.prototype,
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
const toArray = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
const isTypedArray = ((TypedArray) => {
// eslint-disable-next-line func-names
return (thing) => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object<any, any>} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
const forEachEntry = (obj, fn) => {
const generator = obj && obj[iterator];
const _iterator = generator.call(obj);
let result;
while ((result = _iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array<boolean>}
*/
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = (str) => {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
});
};
const { propertyIsEnumerable } = Object.prototype;
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
const reduceDescriptors = (obj, reducer) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
const freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
// skip restricted props in strict mode
if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
return false;
}
const value = obj[name];
if (!isFunction$1(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
/**
* Converts an array or a delimited string into an object set with values as keys and true as values.
* Useful for fast membership checks.
*
* @param {Array|string} arrayOrString - The array or string to convert.
* @param {string} delimiter - The delimiter to use if input is a string.
* @returns {Object} An object with keys from the array or string, values set to true.
*/
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach((value) => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop = () => {};
const toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(
thing &&
isFunction$1(thing.append) &&
thing[toStringTag] === 'FormData' &&
thing[iterator]
);
}
/**
* Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
*
* @param {Object} obj - The object to convert.
* @returns {Object} The JSON-compatible object.
*/
const toJSONObject = (obj) => {
const visited = new WeakSet();
const visit = (source) => {
if (isObject(source)) {
if (visited.has(source)) {
return;
}
//Buffer check
if (isBuffer(source)) {
return source;
}
if (!('toJSON' in source)) {
// add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
visited.add(source);
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
visited.delete(source);
return target;
}
}
return source;
};
return visit(obj);
};
/**
* Determines if a value is an async function.
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is an async function, otherwise false.
*/
const isAsyncFn = kindOfTest('AsyncFunction');
/**
* Determines if a value is thenable (has then and catch methods).
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is thenable, otherwise false.
*/
const isThenable = (thing) =>
thing &&
(isObject(thing) || isFunction$1(thing)) &&
isFunction$1(thing.then) &&
isFunction$1(thing.catch);
// original code
// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
/**
* Provides a cross-platform setImmediate implementation.
* Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
*
* @param {boolean} setImmediateSupported - Whether setImmediate is supported.
* @param {boolean} postMessageSupported - Whether postMessage is supported.
* @returns {Function} A function to schedule a callback asynchronously.
*/
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported
? ((token, callbacks) => {
_global.addEventListener(
'message',
({ source, data }) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
},
false
);
return (cb) => {
callbacks.push(cb);
_global.postMessage(token, '*');
};
})(`axios@${Math.random()}`, [])
: (cb) => setTimeout(cb);
})(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
/**
* Schedules a microtask or asynchronous callback as soon as possible.
* Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
*
* @type {Function}
*/
const asap =
typeof queueMicrotask !== 'undefined'
? queueMicrotask.bind(_global)
: (typeof process !== 'undefined' && process.nextTick) || _setImmediate;
// *********************
const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
/**
* Determine if a value is iterable via an iterator that is NOT sourced solely
* from a polluted Object.prototype. Use this instead of `isIterable` whenever
* the iterable comes from untrusted input (e.g. user-supplied header sources),
* so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
* into an attacker-controlled entries iterator.
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value has a non-polluted iterator
*/
const isSafeIterable = (thing) =>
thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
var utils$1 = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isEmptyObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isReactNativeBlob,
isReactNative,
isBlob,
isRegExp,
isFunction: isFunction$1,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
hasOwnInPrototypeChain,
getSafeProp,
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap,
isIterable,
isSafeIterable,
};
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils$1.toObjectSet([
'age',
'authorization',
'content-length',
'content-type',
'etag',
'expires',
'from',
'host',
'if-modified-since',
'if-unmodified-since',
'last-modified',
'location',
'max-forwards',
'proxy-authorization',
'referer',
'retry-after',
'user-agent',
]);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = (rawHeaders) => {
const parsed = {};
let key;
let val;
let i;
rawHeaders &&
rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
function trimSPorHTAB(str) {
let start = 0;
let end = str.length;
while (start < end) {
const code = str.charCodeAt(start);
if (code !== 0x09 && code !== 0x20) {
break;
}
start += 1;
}
while (end > start) {
const code = str.charCodeAt(end - 1);
if (code !== 0x09 && code !== 0x20) {
break;
}
end -= 1;
}
return start === 0 && end === str.length ? str : str.slice(start, end);
}
// The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
// eslint-disable-next-line no-control-regex
const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
// eslint-disable-next-line no-control-regex
const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
function sanitizeValue(value, invalidChars) {
if (utils$1.isArray(value)) {
return value.map((item) => sanitizeValue(item, invalidChars));
}
return trimSPorHTAB(String(value).replace(invalidChars, ''));
}
const sanitizeHeaderValue = (value) =>
sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
const sanitizeByteStringHeaderValue = (value) =>
sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
function toByteStringHeaderObject(headers) {
const byteStringHeaders = Object.create(null);
utils$1.forEach(headers.toJSON(), (value, header) => {
byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
});
return byteStringHeaders;
}
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils$1.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils$1.isString(value)) return;
if (utils$1.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils$1.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header
.trim()
.toLowerCase()
.replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils$1.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach((methodName) => {
Object.defineProperty(obj, methodName + accessorName, {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: function (arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true,
});
});
}
class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
return;
}
const key = utils$1.findKey(self, lHeader);
if (
!key ||
self[key] === undefined ||
_rewrite === true ||
(_rewrite === undefined && self[key] !== false)
) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) =>
utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
let obj = Object.create(null),
dest,
key;
for (const entry of header) {
if (!utils$1.isArray(entry)) {
throw new TypeError('Object iterator must return a key-value pair');
}
key = entry[0];
if (utils$1.hasOwnProp(obj, key)) {
dest = obj[key];
obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
} else {
obj[key] = entry[1];
}
}
setHeaders(obj, valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils$1.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils$1.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
return !!(
key &&
this[key] !== undefined &&
(!matcher || matchHeaderValue(this, this[key], key, matcher))
);
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils$1.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils$1.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils$1.forEach(this, (value, header) => {
const key = utils$1.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils$1.forEach(this, (value, header) => {
value != null &&
value !== false &&
(obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON())
.map(([header, value]) => header + ': ' + value)
.join('\n');
}
getSetCookie() {
return this.get('set-cookie') || [];
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals =
(this[$internals] =
this[$internals] =
{
accessors: {},
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}
AxiosHeaders.accessor([
'Content-Type',
'Content-Length',
'Accept',
'Accept-Encoding',
'User-Agent',
'Authorization',
]);
// reserved names hotfix
utils$1.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
},
};
});
utils$1.freezeMethods(AxiosHeaders);
const REDACTED = '[REDACTED ****]';
function hasOwnOrPrototypeToJSON(source) {
if (utils$1.hasOwnProp(source, 'toJSON')) {
return true;
}
let prototype = Object.getPrototypeOf(source);
while (prototype && prototype !== Object.prototype) {
if (utils$1.hasOwnProp(prototype, 'toJSON')) {
return true;
}
prototype = Object.getPrototypeOf(prototype);
}
return false;
}
// Build a plain-object snapshot of `config` and replace the value of any key
// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
// and AxiosHeaders, and short-circuits on circular references.
function redactConfig(config, redactKeys) {
const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase()));
const seen = [];
const visit = (source) => {
if (source === null || typeof source !== 'object') return source;
if (utils$1.isBuffer(source)) return source;
if (seen.indexOf(source) !== -1) return undefined;
if (source instanceof AxiosHeaders) {
source = source.toJSON();
}
seen.push(source);
let result;
if (utils$1.isArray(source)) {
result = [];
source.forEach((v, i) => {
const reducedValue = visit(v);
if (!utils$1.isUndefined(reducedValue)) {
result[i] = reducedValue;
}
});
} else {
if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
seen.pop();
return source;
}
result = Object.create(null);
for (const [key, value] of Object.entries(source)) {
const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
if (!utils$1.isUndefined(reducedValue)) {
result[key] = reducedValue;
}
}
}
seen.pop();
return result;
};
return visit(config);
}
class AxiosError extends Error {
static from(error, code, config, request, response, customProps) {
const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
// Match native `Error` `cause` semantics: non-enumerable. The wrapped
// error often carries circular internals (sockets, requests, agents), so
// an enumerable `cause` makes structured loggers (pino/winston) and any
// own-property walk throw "Converting circular structure to JSON".
// Regression from #6982; see #7205. `__proto__: null` mirrors the
// `message` descriptor below (prototype-pollution-safe descriptor).
Object.defineProperty(axiosError, 'cause', {
__proto__: null,
value: error,
writable: true,
enumerable: false,
configurable: true,
});
axiosError.name = error.name;
// Preserve status from the original error if not already set from response
if (error.status != null && axiosError.status == null) {
axiosError.status = error.status;
}
customProps && Object.assign(axiosError, customProps);
return axiosError;
}
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
constructor(message, code, config, request, response) {
super(message);
// Make message enumerable to maintain backward compatibility
// The native Error constructor sets message as non-enumerable,
// but axios < v1.13.3 had it as enumerable
Object.defineProperty(this, 'message', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: message,
enumerable: true,
writable: true,
configurable: true,
});
this.name = 'AxiosError';
this.isAxiosError = true;
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
if (response) {
this.response = response;
this.status = response.status;
}
}
toJSON() {
// Opt-in redaction: when the request config carries a `redact` array, the
// value of any matching key (case-insensitive, at any depth) is replaced
// with REDACTED in the serialized snapshot. Undefined or empty leaves the
// existing serialization behavior unchanged.
const config = this.config;
const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
const serializedConfig =
utils$1.isArray(redactKeys) && redactKeys.length > 0
? redactConfig(config, redactKeys)
: utils$1.toJSONObject(config);
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: serializedConfig,
code: this.code,
status: this.status,
};
}
}
// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
AxiosError.ECONNABORTED = 'ECONNABORTED';
AxiosError.ETIMEDOUT = 'ETIMEDOUT';
AxiosError.ECONNREFUSED = 'ECONNREFUSED';
AxiosError.ERR_NETWORK = 'ERR_NETWORK';
AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
AxiosError.ERR_CANCELED = 'ERR_CANCELED';
AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
// eslint-disable-next-line strict
var httpAdapter = null;
// Default nesting limit shared with the inverse transform (formDataToJSON) so
// the FormData <-> JSON round-trip stays symmetric.
const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path
.concat(key)
.map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
})
.join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array<any>} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils$1.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object<any, any>} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object<string, any>} options
*
* @returns
*/
function toFormData(obj, formData, options) {
if (!utils$1.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (FormData)();
// eslint-disable-next-line no-param-reassign
options = utils$1.toFlatObject(
options,
{
metaTokens: true,
dots: false,
indexes: false,
},
false,
function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils$1.isUndefined(source[option]);
}
);
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
const stack = [];
if (!utils$1.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils$1.isDate(value)) {
return value.toISOString();
}
if (utils$1.isBoolean(value)) {
return value.toString();
}
if (!useBlob && utils$1.isBlob(value)) {
throw new AxiosError('Blob is not supported. Use a Buffer instead.');
}
if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
if (useBlob && typeof _Blob === 'function') {
return new _Blob([value]);
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(value);
}
throw new AxiosError('Blob is not supported. Use a Buffer instead.', AxiosError.ERR_NOT_SUPPORT);
}
return value;
}
function throwIfMaxDepthExceeded(depth) {
if (depth > maxDepth) {
throw new AxiosError(
'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth,
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
);
}
}
function stringifyWithDepthLimit(value, depth) {
if (maxDepth === Infinity) {
return JSON.stringify(value);
}
const ancestors = [];
return JSON.stringify(value, function limitDepth(_key, currentValue) {
if (!utils$1.isObject(currentValue)) {
return currentValue;
}
while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
ancestors.pop();
}
ancestors.push(currentValue);
throwIfMaxDepthExceeded(depth + ancestors.length - 1);
return currentValue;
});
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array<String|Number>} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
let arr = value;
if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
if (value && !path && typeof value === 'object') {
if (utils$1.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = stringifyWithDepthLimit(value, 1);
} else if (
(utils$1.isArray(value) && isFlatArray(value)) ||
((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)))
) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils$1.isUndefined(el) || el === null) &&
formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true
? renderKey([key], index, dots)
: indexes === null
? key
: key + '[]',
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable,
});
function build(value, path, depth = 0) {
if (utils$1.isUndefined(value)) return;
throwIfMaxDepthExceeded(depth);
if (stack.indexOf(value) !== -1) {
throw new Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils$1.forEach(value, function each(el, key) {
const result =
!(utils$1.isUndefined(el) || el === null) &&
visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
if (result === true) {
build(el, path ? path.concat(key) : [key], depth + 1);
}
});
stack.pop();
}
if (!utils$1.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode$1(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
};
return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder
? (value) => encoder.call(this, value, encode$1)
: encode$1;
return this._pairs
.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '')
.join('&');
};
/**
* It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
* their plain counterparts (`:`, `$`, `,`, `+`).
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val)
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?(object|Function)} options
*
* @returns {string} The formatted url
*/
function buildURL(url, params, options) {
if (!params) {
return url;
}
url = url || '';
const _options = utils$1.isFunction(options)
? {
serialize: options,
}
: options;
// Read serializer options pollution-safely: own properties and methods on a
// class/template prototype are honored, but values injected onto a polluted
// Object.prototype are ignored.
const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
const serializeFn = utils$1.getSafeProp(_options, 'serialize');
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, _options);
} else {
serializedParams = utils$1.isURLSearchParams(params)
? params.toString()
: new AxiosURLSearchParams(params, _options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
* @param {Object} options The options for the interceptor, synchronous and runWhen
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null,
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {void}
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils$1.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
var transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false,
legacyInterceptorReqResOrdering: true,
advertiseZstdAcceptEncoding: false,
validateStatusUndefinedResolves: true,
};
var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
var platform$1 = {
isBrowser: true,
classes: {
URLSearchParams: URLSearchParams$1,
FormData: FormData$1,
Blob: Blob$1,
},
protocols: ['http', 'https', 'file', 'blob', 'url', 'data'],
};
const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
const _navigator = (typeof navigator === 'object' && navigator) || undefined;
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
const hasStandardBrowserEnv =
hasBrowserEnv &&
(!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
const hasStandardBrowserWebWorkerEnv = (() => {
return (
typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope &&
typeof self.importScripts === 'function'
);
})();
const origin = (hasBrowserEnv && window.location.href) || 'http://localhost';
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
hasBrowserEnv: hasBrowserEnv,
hasStandardBrowserEnv: hasStandardBrowserEnv,
hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
navigator: _navigator,
origin: origin
});
var platform = {
...utils,
...platform$1,
};
function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), {
visitor: function (value, key, path, helpers) {
if (platform.isNode && utils$1.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
},
...options,
});
}
const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
function throwIfDepthExceeded(index) {
if (index > MAX_DEPTH) {
throw new AxiosError(
'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
);
}
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
const path = [];
const pattern = /\w+|\[(\w*)]/g;
let match;
while ((match = pattern.exec(name)) !== null) {
throwIfDepthExceeded(path.length);
path.push(match[0] === '[]' ? '' : match[1] || match[0]);
}
return path;
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
throwIfDepthExceeded(index);
let name = path[index++];
if (name === '__proto__') return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils$1.isArray(target) ? target.length : name;
if (isLast) {
if (utils$1.hasOwnProp(target, name)) {
target[name] = utils$1.isArray(target[name])
? target[name].concat(value)
: [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils$1.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
const obj = {};
utils$1.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
const own = (obj, key) => (obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined);
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils$1.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils$1.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [
function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils$1.isObject(data);
if (isObjectPayload && utils$1.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils$1.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (
utils$1.isArrayBuffer(data) ||
utils$1.isBuffer(data) ||
utils$1.isStream(data) ||
utils$1.isFile(data) ||
utils$1.isBlob(data) ||
utils$1.isReadableStream(data)
) {
return data;
}
if (utils$1.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$1.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
const formSerializer = own(this, 'formSerializer');
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, formSerializer).toString();
}
if (
(isFileList = utils$1.isFileList(data)) ||
contentType.indexOf('multipart/form-data') > -1
) {
const env = own(this, 'env');
const _FormData = env && env.FormData;
return toFormData(
isFileList ? { 'files[]': data } : data,
_FormData && new _FormData(),
formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
},
],
transformResponse: [
function transformResponse(data) {
const transitional = own(this, 'transitional') || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const responseType = own(this, 'responseType');
const JSONRequested = responseType === 'json';
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (
data &&
utils$1.isString(data) &&
((forcedJSONParsing && !responseType) || JSONRequested)
) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data, own(this, 'parseReviver'));
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
}
throw e;
}
}
}
return data;
},
],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob,
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
Accept: 'application/json, text/plain, */*',
'Content-Type': undefined,
},
},
};
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], (method) => {
defaults.headers[method] = {};
});
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders.from(context.headers);
let data = context.data;
utils$1.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
function isCancel(value) {
return !!(value && value.__CANCEL__);
}
class CanceledError extends AxiosError {
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
constructor(message, config, request) {
super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
this.name = 'CanceledError';
this.__CANCEL__ = true;
}
}
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE,
response.config,
response.request,
response
));
}
}
function parseProtocol(url) {
const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
return (match && match[1]) || '';
}
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round((bytesCount * 1000) / passed) : undefined;
};
}
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1000 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn(...args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
return [throttled, flush];
}
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle((e) => {
if (!e || typeof e.loaded !== 'number') {
return;
}
const rawLoaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
const progressBytes = Math.max(0, loaded - bytesNotified);
const rate = _speedometer(progressBytes);
bytesNotified = Math.max(bytesNotified, loaded);
const data = {
loaded,
total,
progress: total ? loaded / total : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null,
[isDownloadStream ? 'download' : 'upload']: true,
};
listener(data);
}, freq);
};
const progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [
(loaded) =>
throttled[0]({
lengthComputable,
total,
loaded,
}),
throttled[1],
];
};
const asyncDecorator =
(fn) =>
(...args) =>
utils$1.asap(() => fn(...args));
var isURLSameOrigin = platform.hasStandardBrowserEnv
? ((origin, isMSIE) => (url) => {
url = new URL(url, platform.origin);
return (
origin.protocol === url.protocol &&
origin.host === url.host &&
(isMSIE || origin.port === url.port)
);
})(
new URL(platform.origin),
platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
)
: () => true;
var cookies = platform.hasStandardBrowserEnv
? // Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure, sameSite) {
if (typeof document === 'undefined') return;
const cookie = [`${name}=${encodeURIComponent(value)}`];
if (utils$1.isNumber(expires)) {
cookie.push(`expires=${new Date(expires).toUTCString()}`);
}
if (utils$1.isString(path)) {
cookie.push(`path=${path}`);
}
if (utils$1.isString(domain)) {
cookie.push(`domain=${domain}`);
}
if (secure === true) {
cookie.push('secure');
}
if (utils$1.isString(sameSite)) {
cookie.push(`SameSite=${sameSite}`);
}
document.cookie = cookie.join('; ');
},
read(name) {
if (typeof document === 'undefined') return null;
// Match name=value by splitting on the semicolon separator instead of building a
// RegExp from `name` — interpolating an unescaped string into a RegExp would let
// metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
// match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
// "; ", so ignore optional whitespace before each cookie name.
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].replace(/^\s+/, '');
const eq = cookie.indexOf('=');
if (eq !== -1 && cookie.slice(0, eq) === name) {
try {
return decodeURIComponent(cookie.slice(eq + 1));
} catch (e) {
return cookie.slice(eq + 1);
}
}
}
return null;
},
remove(name) {
this.write(name, '', Date.now() - 86400000, '/');
},
}
: // Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {},
};
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
if (typeof url !== 'string') {
return false;
}
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
const malformedHttpProtocol = /^https?:(?!\/\/)/i;
const httpProtocolControlCharacters = /[\t\n\r]/g;
function stripLeadingC0ControlOrSpace(url) {
let i = 0;
while (i < url.length && url.charCodeAt(i) <= 0x20) {
i++;
}
return url.slice(i);
}
function normalizeURLForProtocolCheck(url) {
return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
}
function assertValidHttpProtocolURL(url, config) {
if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
throw new AxiosError(
'Invalid URL: missing "//" after protocol',
AxiosError.ERR_INVALID_URL,
config
);
}
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
assertValidHttpProtocolURL(requestedURL, config);
let isRelativeUrl = !isAbsoluteURL(requestedURL);
if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
assertValidHttpProtocolURL(baseURL, config);
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
const headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing);
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config1 = config1 || {};
config2 = config2 || {};
// Use a null-prototype object so that downstream reads such as `config.auth`
// or `config.baseURL` cannot inherit polluted values from Object.prototype.
// `hasOwnProperty` is restored as a non-enumerable own slot to preserve
// ergonomics for user code that relies on it.
const config = Object.create(null);
Object.defineProperty(config, 'hasOwnProperty', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: Object.prototype.hasOwnProperty,
enumerable: false,
writable: true,
configurable: true,
});
function getMergedValue(target, source, prop, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({ caseless }, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(a, b, prop, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, prop, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, prop, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
function getMergedTransitionalOption(prop) {
const transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
if (!utils$1.isUndefined(transitional2)) {
if (utils$1.isPlainObject(transitional2)) {
if (utils$1.hasOwnProp(transitional2, prop)) {
return transitional2[prop];
}
} else {
return undefined;
}
}
const transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
return transitional1[prop];
}
return undefined;
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (utils$1.hasOwnProp(config2, prop)) {
return getMergedValue(a, b);
} else if (utils$1.hasOwnProp(config1, prop)) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
allowedSocketPaths: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b, prop) =>
mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true),
};
utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
const configValue = merge(a, b, prop);
(utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
if (
utils$1.hasOwnProp(config2, 'validateStatus') &&
utils$1.isUndefined(config2.validateStatus) &&
getMergedTransitionalOption('validateStatusUndefinedResolves') === false
) {
if (utils$1.hasOwnProp(config1, 'validateStatus')) {
config.validateStatus = getMergedValue(undefined, config1.validateStatus);
} else {
delete config.validateStatus;
}
}
return config;
}
const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
function setFormDataHeaders(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders || {}).forEach(([key, val]) => {
if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8$1 = (str) =>
encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
function resolveConfig(config) {
const newConfig = mergeConfig({}, config);
// Read only own properties to prevent prototype pollution gadgets
// (e.g. Object.prototype.baseURL = 'https://evil.com').
const own = (key) => (utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined);
const data = own('data');
let withXSRFToken = own('withXSRFToken');
const xsrfHeaderName = own('xsrfHeaderName');
const xsrfCookieName = own('xsrfCookieName');
let headers = own('headers');
const auth = own('auth');
const baseURL = own('baseURL');
const allowAbsoluteUrls = own('allowAbsoluteUrls');
const url = own('url');
newConfig.headers = headers = AxiosHeaders.from(headers);
newConfig.url = buildURL(
buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig),
own('params'),
own('paramsSerializer')
);
// HTTP basic authentication
if (auth) {
const username = utils$1.getSafeProp(auth, 'username') || '';
const password = utils$1.getSafeProp(auth, 'password') || '';
try {
headers.set(
'Authorization',
'Basic ' + btoa(username + ':' + (password ? encodeUTF8$1(password) : ''))
);
} catch (e) {
throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config);
}
}
if (utils$1.isFormData(data)) {
if (
platform.hasStandardBrowserEnv ||
platform.hasStandardBrowserWebWorkerEnv ||
utils$1.isReactNative(data)
) {
headers.setContentType(undefined); // browser/web worker/RN handles it
} else if (utils$1.isFunction(data.getHeaders)) {
// Node.js FormData (like form-data package)
setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
if (utils$1.isFunction(withXSRFToken)) {
withXSRFToken = withXSRFToken(newConfig);
}
// Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
// and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
// the XSRF token cross-origin.
const shouldSendXSRF =
withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url));
if (shouldSendXSRF) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
}
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
var xhrAdapter = isXHRAdapterSupported &&
function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
let { responseType, onUploadProgress, onDownloadProgress } = _config;
let onCanceled;
let uploadThrottled, downloadThrottled;
let flushUpload, flushDownload;
function done() {
flushUpload && flushUpload(); // flush events
flushDownload && flushDownload(); // flush events
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener('abort', onCanceled);
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData =
!responseType || responseType === 'text' || responseType === 'json'
? request.responseText
: request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request,
};
settle(
function _resolve(value) {
resolve(value);
done();
},
function _reject(err) {
reject(err);
done();
},
response
);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (
request.status === 0 &&
!(request.responseURL && request.responseURL.startsWith('file:'))
) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
done();
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError(event) {
// Browsers deliver a ProgressEvent in XHR onerror
// (message may be empty; when present, surface it)
// See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
const msg = event && event.message ? event.message : 'Network Error';
const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
// attach the underlying event for consumers who want details
err.event = event || null;
reject(err);
done();
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout
? 'timeout of ' + _config.timeout + 'ms exceeded'
: 'timeout exceeded';
const transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(
new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
request
)
);
done();
// Clean up request
request = null;
};
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = _config.responseType;
}
// Handle progress if needed
if (onDownloadProgress) {
[downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
request.addEventListener('progress', downloadThrottled);
}
// Not all browsers support upload events
if (onUploadProgress && request.upload) {
[uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
request.upload.addEventListener('progress', uploadThrottled);
request.upload.addEventListener('loadend', flushUpload);
}
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = (cancel) => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
done();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted
? onCanceled()
: _config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(_config.url);
if (protocol && !platform.protocols.includes(protocol)) {
reject(
new AxiosError(
'Unsupported protocol ' + protocol + ':',
AxiosError.ERR_BAD_REQUEST,
config
)
);
done();
return;
}
// Send the request
request.send(requestData || null);
});
};
const composeSignals = (signals, timeout) => {
signals = signals ? signals.filter(Boolean) : [];
if (!timeout && !signals.length) {
return;
}
const controller = new AbortController();
let aborted = false;
const onabort = function (reason) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = reason instanceof Error ? reason : this.reason;
controller.abort(
err instanceof AxiosError
? err
: new CanceledError(err instanceof Error ? err.message : err)
);
}
};
let timer =
timeout &&
setTimeout(() => {
timer = null;
onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (!signals) { return; }
timer && clearTimeout(timer);
timer = null;
signals.forEach((signal) => {
signal.unsubscribe
? signal.unsubscribe(onabort)
: signal.removeEventListener('abort', onabort);
});
signals = null;
};
signals.forEach((signal) => signal.addEventListener('abort', onabort, { once: true }));
const { signal } = controller;
signal.unsubscribe = () => utils$1.asap(unsubscribe);
return signal;
};
const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
};
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
yield* stream;
return;
}
const reader = stream.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) {
break;
}
yield value;
}
} finally {
await reader.cancel();
}
};
const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = (e) => {
if (!done) {
done = true;
onFinish && onFinish(e);
}
};
return new ReadableStream(
{
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = (bytes += len);
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
},
},
{
highWaterMark: 2,
}
);
};
/**
* Estimate decoded byte length of a data:// URL *without* allocating large buffers.
* - For base64: compute exact decoded size using length and padding;
* handle %XX at the character-count level (no string allocation).
* - For non-base64: compute the exact percent-decoded UTF-8 byte length.
*
* @param {string} url
* @returns {number}
*/
const isHexDigit = (charCode) =>
(charCode >= 48 && charCode <= 57) ||
(charCode >= 65 && charCode <= 70) ||
(charCode >= 97 && charCode <= 102);
const isPercentEncodedByte = (str, i, len) =>
i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
function estimateDataURLDecodedBytes(url) {
if (!url || typeof url !== 'string') return 0;
if (!url.startsWith('data:')) return 0;
const comma = url.indexOf(',');
if (comma < 0) return 0;
const meta = url.slice(5, comma);
const body = url.slice(comma + 1);
const isBase64 = /;base64/i.test(meta);
if (isBase64) {
let effectiveLen = body.length;
const len = body.length; // cache length
for (let i = 0; i < len; i++) {
if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
const a = body.charCodeAt(i + 1);
const b = body.charCodeAt(i + 2);
const isHex = isHexDigit(a) && isHexDigit(b);
if (isHex) {
effectiveLen -= 2;
i += 2;
}
}
}
let pad = 0;
let idx = len - 1;
const tailIsPct3D = (j) =>
j >= 2 &&
body.charCodeAt(j - 2) === 37 && // '%'
body.charCodeAt(j - 1) === 51 && // '3'
(body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'
if (idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
idx--;
} else if (tailIsPct3D(idx)) {
pad++;
idx -= 3;
}
}
if (pad === 1 && idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
} else if (tailIsPct3D(idx)) {
pad++;
}
}
const groups = Math.floor(effectiveLen / 4);
const bytes = groups * 3 - (pad || 0);
return bytes > 0 ? bytes : 0;
}
// Compute UTF-8 byte length directly from UTF-16 code units without allocating
// a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
// Valid %XX triplets count as one decoded byte; this matches the bytes that
// decodeURIComponent(body) would produce before Buffer re-encodes the string.
let bytes = 0;
for (let i = 0, len = body.length; i < len; i++) {
const c = body.charCodeAt(i);
if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
bytes += 1;
i += 2;
} else if (c < 0x80) {
bytes += 1;
} else if (c < 0x800) {
bytes += 2;
} else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
const next = body.charCodeAt(i + 1);
if (next >= 0xdc00 && next <= 0xdfff) {
bytes += 4;
i++;
} else {
bytes += 3;
}
} else {
bytes += 3;
}
}
return bytes;
}
const VERSION = "1.18.1";
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const { isFunction } = utils$1;
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8 = (str) =>
encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
// Decode before composing the `auth` option so credentials such as
// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
// original value for malformed input so a bad encoding never throws.
const decodeURIComponentSafe = (value) => {
if (!utils$1.isString(value)) {
return value;
}
try {
return decodeURIComponent(value);
} catch (error) {
return value;
}
};
const test = (fn, ...args) => {
try {
return !!fn(...args);
} catch (e) {
return false;
}
};
const maybeWithAuthCredentials = (url) => {
const protocolIndex = url.indexOf('://');
let urlToCheck = url;
if (protocolIndex !== -1) {
urlToCheck = urlToCheck.slice(protocolIndex + 3);
}
return urlToCheck.includes('@') || urlToCheck.includes(':');
};
const factory = (env) => {
const globalObject =
utils$1.global !== undefined && utils$1.global !== null
? utils$1.global
: globalThis;
const { ReadableStream, TextEncoder } = globalObject;
env = utils$1.merge.call(
{
skipUndefined: true,
},
{
Request: globalObject.Request,
Response: globalObject.Response,
},
env
);
const { fetch: envFetch, Request, Response } = env;
const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
const isRequestSupported = isFunction(Request);
const isResponseSupported = isFunction(Response);
if (!isFetchSupported) {
return false;
}
const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
const encodeText =
isFetchSupported &&
(typeof TextEncoder === 'function'
? (
(encoder) => (str) =>
encoder.encode(str)
)(new TextEncoder())
: async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
const supportsRequestStream =
isRequestSupported &&
isReadableStreamSupported &&
test(() => {
let duplexAccessed = false;
const request = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
});
const hasContentType = request.headers.has('Content-Type');
if (request.body != null) {
request.body.cancel();
}
return duplexAccessed && !hasContentType;
});
const supportsResponseStream =
isResponseSupported &&
isReadableStreamSupported &&
test(() => utils$1.isReadableStream(new Response('').body));
const resolvers = {
stream: supportsResponseStream && ((res) => res.body),
};
isFetchSupported &&
(() => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {
!resolvers[type] &&
(resolvers[type] = (res, config) => {
let method = res && res[type];
if (method) {
return method.call(res);
}
throw new AxiosError(
`Response type '${type}' is not supported`,
AxiosError.ERR_NOT_SUPPORT,
config
);
});
});
})();
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if (utils$1.isBlob(body)) {
return body.size;
}
if (utils$1.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: 'POST',
body,
});
return (await _request.arrayBuffer()).byteLength;
}
if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
return body.byteLength;
}
if (utils$1.isURLSearchParams(body)) {
body = body + '';
}
if (utils$1.isString(body)) {
return (await encodeText(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils$1.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
return async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions,
maxContentLength,
maxBodyLength,
} = resolveConfig(config);
const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
const own = (key) => (utils$1.hasOwnProp(config, key) ? config[key] : undefined);
let _fetch = envFetch || fetch;
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let composedSignal = composeSignals(
[signal, cancelToken && cancelToken.toAbortSignal()],
timeout
);
let request = null;
const unsubscribe =
composedSignal &&
composedSignal.unsubscribe &&
(() => {
composedSignal.unsubscribe();
});
let requestContentLength;
// AxiosError we raise while the request body is being streamed. Captured
// by identity so the catch block can surface it directly, regardless of
// how the runtime wraps the resulting fetch rejection (undici exposes it
// as `err.cause`; some browsers drop the original error entirely).
let pendingBodyError = null;
const maxBodyLengthError = () =>
new AxiosError(
'Request body larger than maxBodyLength limit',
AxiosError.ERR_BAD_REQUEST,
config,
request
);
try {
// HTTP basic authentication
let auth = undefined;
const configAuth = own('auth');
if (configAuth) {
const username = utils$1.getSafeProp(configAuth, 'username') || '';
const password = utils$1.getSafeProp(configAuth, 'password') || '';
auth = {
username,
password
};
}
if (maybeWithAuthCredentials(url)) {
const parsedURL = new URL(url, platform.origin);
if (!auth && (parsedURL.username || parsedURL.password)) {
const urlUsername = decodeURIComponentSafe(parsedURL.username);
const urlPassword = decodeURIComponentSafe(parsedURL.password);
auth = {
username: urlUsername,
password: urlPassword
};
}
if (parsedURL.username || parsedURL.password) {
parsedURL.username = '';
parsedURL.password = '';
url = parsedURL.href;
}
}
if (auth) {
headers.delete('authorization');
headers.set(
'Authorization',
'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || '')))
);
}
// Enforce maxContentLength for data: URLs up-front so we never materialize
// an oversized payload. The HTTP adapter applies the same check (see http.js
// "if (protocol === 'data:')" branch).
if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
const estimated = estimateDataURLDecodedBytes(url);
if (estimated > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
// Enforce maxBodyLength against known-size bodies before dispatch using
// the body's *actual* size — never a caller-declared Content-Length,
// which could under-report to slip an oversized body past the check.
// Unknown-size streams return undefined here and are counted per-chunk
// below as fetch consumes them.
if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
const outboundLength = await getBodyLength(data);
if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
requestContentLength = outboundLength;
if (outboundLength > maxBodyLength) {
throw maxBodyLengthError();
}
}
}
// A streamed body under maxBodyLength must be counted as fetch consumes
// it; its size is never trusted from a caller-declared Content-Length.
const mustEnforceStreamBody =
hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
const trackRequestStream = (stream, onProgress, flush) =>
trackStream(
stream,
DEFAULT_CHUNK_SIZE,
(loadedBytes) => {
if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
throw (pendingBodyError = maxBodyLengthError());
}
onProgress && onProgress(loadedBytes);
},
flush
);
if (
supportsRequestStream &&
method !== 'get' &&
method !== 'head' &&
(onUploadProgress || mustEnforceStreamBody)
) {
requestContentLength =
requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
// A declared length of 0 is only trusted to skip the wrap when we are
// not enforcing a stream limit (which must not rely on that header).
if (requestContentLength !== 0 || mustEnforceStreamBody) {
let _request = new Request(url, {
method: 'POST',
body: data,
duplex: 'half',
});
let contentTypeHeader;
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
const [onProgress, flush] =
(onUploadProgress &&
progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
)) ||
[];
data = trackRequestStream(_request.body, onProgress, flush);
}
}
} else if (
mustEnforceStreamBody &&
!isRequestSupported &&
isReadableStreamSupported &&
method !== 'get' &&
method !== 'head'
) {
data = trackRequestStream(data);
} else if (
mustEnforceStreamBody &&
isRequestSupported &&
!supportsRequestStream &&
method !== 'get' &&
method !== 'head'
) {
throw new AxiosError(
'Stream request bodies are not supported by the current fetch implementation',
AxiosError.ERR_NOT_SUPPORT,
config,
request
);
}
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
// If data is FormData and Content-Type is multipart/form-data without boundary,
// delete it so fetch can set it correctly with the boundary
if (utils$1.isFormData(data)) {
const contentType = headers.getContentType();
if (
contentType &&
/^multipart\/form-data/i.test(contentType) &&
!/boundary=/i.test(contentType)
) {
headers.delete('content-type');
}
}
// Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
headers.set('User-Agent', 'axios/' + VERSION, false);
const resolvedOptions = {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: toByteStringHeaderObject(headers.normalize()),
body: data,
duplex: 'half',
credentials: isCredentialsSupported ? withCredentials : undefined,
};
request = isRequestSupported && new Request(url, resolvedOptions);
let response = await (isRequestSupported
? _fetch(request, fetchOptions)
: _fetch(url, resolvedOptions));
const responseHeaders = AxiosHeaders.from(response.headers);
// Cheap pre-check: if the server honestly declares a content-length that
// already exceeds the cap, reject before we start streaming.
if (hasMaxContentLength) {
const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
if (declaredLength != null && declaredLength > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
const isStreamResponse =
supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (
supportsResponseStream &&
response.body &&
(onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe))
) {
const options = {};
['status', 'statusText', 'headers'].forEach((prop) => {
options[prop] = response[prop];
});
const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
const [onProgress, flush] =
(onDownloadProgress &&
progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
)) ||
[];
let bytesRead = 0;
const onChunkProgress = (loadedBytes) => {
if (hasMaxContentLength) {
bytesRead = loadedBytes;
if (bytesRead > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
onProgress && onProgress(loadedBytes);
};
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](
response,
config
);
// Fallback enforcement for environments without ReadableStream support
// (legacy runtimes). Detect materialized size from typed output; skip
// streams/Response passthrough since the user will read those themselves.
if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
let materializedSize;
if (responseData != null) {
if (typeof responseData.byteLength === 'number') {
materializedSize = responseData.byteLength;
} else if (typeof responseData.size === 'number') {
materializedSize = responseData.size;
} else if (typeof responseData === 'string') {
materializedSize =
typeof TextEncoder === 'function'
? new TextEncoder().encode(responseData).byteLength
: responseData.length;
}
}
if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request,
});
});
} catch (err) {
unsubscribe && unsubscribe();
// Safari can surface fetch aborts as a DOMException-like object whose
// branded getters throw. Prefer our composed signal reason before reading
// the caught error, preserving timeout vs cancellation semantics.
if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
const canceledError = composedSignal.reason;
canceledError.config = config;
request && (canceledError.request = request);
if (err !== canceledError) {
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(canceledError, 'cause', {
__proto__: null,
value: err,
writable: true,
enumerable: false,
configurable: true,
});
}
throw canceledError;
}
// Surface a maxBodyLength violation we raised while the request body was
// being streamed. Matching by identity (rather than reading
// `err.cause.isAxiosError`) keeps the error deterministic across runtimes
// and avoids both prototype-pollution reads and mis-attributing a foreign
// AxiosError that merely happened to land in `err.cause`.
if (pendingBodyError) {
request && !pendingBodyError.request && (pendingBodyError.request = request);
throw pendingBodyError;
}
// Re-throw AxiosErrors we raised synchronously (data: URL / content-length
// pre-checks, response size enforcement) without re-wrapping them.
if (err instanceof AxiosError) {
request && !err.request && (err.request = request);
throw err;
}
if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
const networkError = new AxiosError(
'Network Error',
AxiosError.ERR_NETWORK,
config,
request,
err && err.response
);
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(networkError, 'cause', {
__proto__: null,
value: err.cause || err,
writable: true,
enumerable: false,
configurable: true,
});
throw networkError;
}
throw AxiosError.from(err, err && err.code, config, request, err && err.response);
}
};
};
const seedCache = new Map();
const getFetch = (config) => {
let env = (config && config.env) || {};
const { fetch, Request, Response } = env;
const seeds = [Request, Response, fetch];
let len = seeds.length,
i = len,
seed,
target,
map = seedCache;
while (i--) {
seed = seeds[i];
target = map.get(seed);
target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));
map = target;
}
return target;
};
getFetch();
/**
* Known adapters mapping.
* Provides environment-specific adapters for Axios:
* - `http` for Node.js
* - `xhr` for browsers
* - `fetch` for fetch API-based requests
*
* @type {Object<string, Function|Object>}
*/
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: {
get: getFetch,
},
};
// Assign adapter names for easier debugging and identification
utils$1.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
// Null-proto descriptors so a polluted Object.prototype.get cannot turn
// these data descriptors into accessor descriptors on the way in.
Object.defineProperty(fn, 'name', { __proto__: null, value });
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', { __proto__: null, value });
}
});
/**
* Render a rejection reason string for unknown or unsupported adapters
*
* @param {string} reason
* @returns {string}
*/
const renderReason = (reason) => `- ${reason}`;
/**
* Check if the adapter is resolved (function, null, or false)
*
* @param {Function|null|false} adapter
* @returns {boolean}
*/
const isResolvedHandle = (adapter) =>
utils$1.isFunction(adapter) || adapter === null || adapter === false;
/**
* Get the first suitable adapter from the provided list.
* Tries each adapter in order until a supported one is found.
* Throws an AxiosError if no adapter is suitable.
*
* @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
* @param {Object} config - Axios request configuration
* @throws {AxiosError} If no suitable adapter is available
* @returns {Function} The resolved adapter function
*/
function getAdapter(adapters, config) {
adapters = utils$1.isArray(adapters) ? adapters : [adapters];
const { length } = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
}
if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons).map(
([id, state]) =>
`adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
let s = length
? reasons.length > 1
? 'since :\n' + reasons.map(renderReason).join('\n')
: ' ' + renderReason(reasons[0])
: 'as no adapter specified';
throw new AxiosError(
`There is no suitable adapter to dispatch the request ` + s,
AxiosError.ERR_NOT_SUPPORT
);
}
return adapter;
}
/**
* Exports Axios adapters and utility to resolve an adapter
*/
var adapters = {
/**
* Resolve an adapter from a list of adapter names or functions.
* @type {Function}
*/
getAdapter,
/**
* Exposes all known adapters
* @type {Object<string, Function|Object>}
*/
adapters: knownAdapters,
};
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders.from(config.headers);
// Transform request data
config.data = transformData.call(config, config.transformRequest);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
return adapter(config).then(
function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Expose the current response on config so that transformResponse can
// attach it to any AxiosError it throws (e.g. on JSON parse failure).
// We clean it up afterwards to avoid polluting the config object.
config.response = response;
try {
response.data = transformData.call(config, config.transformResponse, response);
} finally {
delete config.response;
}
response.headers = AxiosHeaders.from(response.headers);
return response;
},
function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
config.response = reason.response;
try {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
} finally {
delete config.response;
}
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}
return Promise.reject(reason);
}
);
}
const validators$1 = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators$1[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
const deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators$1.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return (
'[Axios v' +
VERSION +
"] Transitional option '" +
opt +
"'" +
desc +
(message ? '. ' + message : '')
);
}
// eslint-disable-next-line func-names
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
validators$1.spelling = function spelling(correctSpelling) {
return (value, opt) => {
// eslint-disable-next-line no-console
console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
return true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object' || options === null) {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
// Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
// a non-function validator and cause a TypeError.
const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
if (validator) {
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError(
'option ' + opt + ' must be ' + result,
AxiosError.ERR_BAD_OPTION_VALUE
);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
var validator = {
assertOptions,
validators: validators$1,
};
const validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig || {};
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager(),
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
// slice off the Error: ... line
const stack = (() => {
if (!dummy.stack) {
return '';
}
const firstNewlineIndex = dummy.stack.indexOf('\n');
return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
})();
try {
if (!err.stack) {
err.stack = stack;
// match without the 2 top stack lines
} else if (stack) {
const firstNewlineIndex = stack.indexOf('\n');
const secondNewlineIndex =
firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
const stackWithoutTwoTopLines =
secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
err.stack += '\n' + stack;
}
}
} catch (e) {
// ignore the case where "stack" is an un-writable property
}
}
throw err;
}
}
_request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
const { transitional, paramsSerializer, headers } = config;
if (transitional !== undefined) {
validator.assertOptions(
transitional,
{
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean),
legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
validateStatusUndefinedResolves: validators.transitional(validators.boolean),
},
false
);
}
if (paramsSerializer != null) {
if (utils$1.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer,
};
} else {
validator.assertOptions(
paramsSerializer,
{
encode: validators.function,
serialize: validators.function,
},
true
);
}
}
// Set config.allowAbsoluteUrls
if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
} else {
config.allowAbsoluteUrls = true;
}
validator.assertOptions(
config,
{
baseUrl: validators.spelling('baseURL'),
withXsrfToken: validators.spelling('withXSRFToken'),
},
true
);
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
headers &&
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => {
delete headers[method];
});
config.headers = AxiosHeaders.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
const transitional = config.transitional || transitionalDefaults;
const legacyInterceptorReqResOrdering =
transitional && transitional.legacyInterceptorReqResOrdering;
if (legacyInterceptorReqResOrdering) {
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
} else {
requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
}
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift(...requestInterceptorChain);
chain.push(...responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}
// Provide aliases for supported request methods
utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function (url, config) {
return this.request(
mergeConfig(config || {}, {
method,
url,
data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined,
})
);
};
});
utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(
mergeConfig(config || {}, {
method,
headers: isForm
? {
'Content-Type': 'multipart/form-data',
}
: {},
url,
data,
})
);
};
}
Axios.prototype[method] = generateHTTPMethod();
// QUERY is a safe/idempotent read method; multipart form bodies don't fit
// its semantics, so no queryForm shorthand is generated.
if (method !== 'query') {
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
}
});
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then((cancel) => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = (onfulfilled) => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise((resolve) => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
toAbortSignal() {
const controller = new AbortController();
const abort = (err) => {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel,
};
}
}
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* const args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
function isAxiosError(payload) {
return utils$1.isObject(payload) && payload.isAxiosError === true;
}
const HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
WebServerIsDown: 521,
ConnectionTimedOut: 522,
OriginIsUnreachable: 523,
TimeoutOccurred: 524,
SslHandshakeFailed: 525,
InvalidSslCertificate: 526,
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios(defaultConfig);
const instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils$1.extend(instance, Axios.prototype, context, { allOwnKeys: true });
// Copy context to instance
utils$1.extend(instance, context, null, { allOwnKeys: true });
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders;
axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode;
axios.default = axios;
module.exports = axios;
//# sourceMappingURL=axios.cjs.map
+5167
View File
@@ -0,0 +1,5167 @@
/*! Axios v1.18.1 Copyright (c) 2026 Matt Zabriskie and contributors */
/**
* Create a bound version of a function with a specified `this` context
*
* @param {Function} fn - The function to bind
* @param {*} thisArg - The value to be passed as the `this` parameter
* @returns {Function} A new function that will call the original function with the specified `this` context
*/
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// utils is a library of generic helper functions non-specific to axios
const { toString } = Object.prototype;
const { getPrototypeOf } = Object;
const { iterator, toStringTag } = Symbol;
/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (
({ hasOwnProperty }) =>
(obj, prop) =>
hasOwnProperty.call(obj, prop)
)(Object.prototype);
/**
* Walk the prototype chain (excluding the shared Object.prototype) looking for
* an own `prop`. This distinguishes genuine own/inherited members — including
* class accessors and template prototypes — from members injected via
* Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
* live on Object.prototype itself and are therefore never matched.
*
* @param {*} thing The value whose chain to inspect
* @param {string|symbol} prop The property key to look for
*
* @returns {boolean} True when `prop` is owned below Object.prototype
*/
const hasOwnInPrototypeChain = (thing, prop) => {
let obj = thing;
const seen = [];
while (obj != null && obj !== Object.prototype) {
if (seen.indexOf(obj) !== -1) {
return false;
}
seen.push(obj);
if (hasOwnProperty(obj, prop)) {
return true;
}
obj = getPrototypeOf(obj);
}
return false;
};
/**
* Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
* properties and members inherited from a non-Object.prototype source (a class
* instance or template object) are honored; a value reachable only through a
* polluted Object.prototype is ignored and `undefined` is returned.
*
* @param {*} obj The source object
* @param {string|symbol} prop The property key to read
*
* @returns {*} The resolved value, or undefined when unsafe/absent
*/
const getSafeProp = (obj, prop) =>
obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
const kindOf = ((cache) => (thing) => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));
const kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type;
};
const typeOfTest = (type) => (thing) => typeof thing === type;
/**
* Determine if a value is a non-null object
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
const { isArray } = Array;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return (
val !== null &&
!isUndefined(val) &&
val.constructor !== null &&
!isUndefined(val.constructor) &&
isFunction$1(val.constructor.isBuffer) &&
val.constructor.isBuffer(val)
);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
let result;
if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && isArrayBuffer(val.buffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction$1 = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
const isObject = (thing) => thing !== null && typeof thing === 'object';
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = (thing) => thing === true || thing === false;
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
const isPlainObject = (val) => {
if (!isObject(val)) {
return false;
}
const prototype = getPrototypeOf(val);
return (
(prototype === null ||
prototype === Object.prototype ||
getPrototypeOf(prototype) === null) &&
// Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
// Symbol.iterator as evidence the value is a tagged/iterable type rather
// than a plain object, while ignoring keys injected onto Object.prototype.
!hasOwnInPrototypeChain(val, toStringTag) &&
!hasOwnInPrototypeChain(val, iterator)
);
};
/**
* Determine if a value is an empty object (safely handles Buffers)
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an empty object, otherwise false
*/
const isEmptyObject = (val) => {
// Early return for non-objects or Buffers to prevent RangeError
if (!isObject(val) || isBuffer(val)) {
return false;
}
try {
return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
} catch (e) {
// Fallback for any other objects that might cause RangeError with Object.keys()
return false;
}
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFile = kindOfTest('File');
/**
* Determine if a value is a React Native Blob
* React Native "blob": an object with a `uri` attribute. Optionally, it can
* also have a `name` and `type` attribute to specify filename and content type
*
* @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
*
* @param {*} value The value to test
*
* @returns {boolean} True if value is a React Native Blob, otherwise false
*/
const isReactNativeBlob = (value) => {
return !!(value && typeof value.uri !== 'undefined');
};
/**
* Determine if environment is React Native
* ReactNative `FormData` has a non-standard `getParts()` method
*
* @param {*} formData The formData to test
*
* @returns {boolean} True if environment is React Native, otherwise false
*/
const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a FileList, otherwise false
*/
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
const isStream = (val) => isObject(val) && isFunction$1(val.pipe);
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
function getGlobal() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
return {};
}
const G = getGlobal();
const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
const isFormData = (thing) => {
if (!thing) return false;
if (FormDataCtor && thing instanceof FormDataCtor) return true;
// Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
const proto = getPrototypeOf(thing);
if (!proto || proto === Object.prototype) return false;
if (!isFunction$1(thing.append)) return false;
const kind = kindOf(thing);
return (
kind === 'formdata' ||
// detect form-data instance
(kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]')
);
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
const [isReadableStream, isRequest, isResponse, isHeaders] = [
'ReadableStream',
'Request',
'Response',
'Headers',
].map(kindOfTest);
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
const trim = (str) => {
return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array<unknown>} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn, { allOwnKeys = false } = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Buffer check
if (isBuffer(obj)) {
return;
}
// Iterate over object keys
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
/**
* Finds a key in an object, case-insensitive, returning the actual key name.
* Returns null if the object is a Buffer or if no match is found.
*
* @param {Object} obj - The object to search.
* @param {string} key - The key to find (case-insensitive).
* @returns {?string} The actual key name if found, otherwise null.
*/
function findKey(obj, key) {
if (isBuffer(obj)) {
return null;
}
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
/*eslint no-undef:0*/
if (typeof globalThis !== 'undefined') return globalThis;
return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* const result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge(...objs) {
const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
const result = {};
const assignValue = (val, key) => {
// Skip dangerous property names to prevent prototype pollution
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return;
}
// findKey lowercases the key, so caseless lookup only applies to strings —
// symbol keys are identity-matched.
const targetKey = (caseless && typeof key === 'string' && findKey(result, key)) || key;
// Read via own-prop only — a bare `result[targetKey]` walks the prototype
// chain, so a polluted Object.prototype value could surface here and get
// copied into the merged result.
const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
if (isPlainObject(existing) && isPlainObject(val)) {
result[targetKey] = merge(existing, val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else if (!skipUndefined || !isUndefined(val)) {
result[targetKey] = val;
}
};
for (let i = 0, l = objs.length; i < l; i++) {
const source = objs[i];
if (!source || isBuffer(source)) {
continue;
}
forEach(source, assignValue);
if (typeof source !== 'object' || isArray(source)) {
continue;
}
const symbols = Object.getOwnPropertySymbols(source);
for (let j = 0; j < symbols.length; j++) {
const symbol = symbols[j];
if (propertyIsEnumerable.call(source, symbol)) {
assignValue(source[symbol], symbol);
}
}
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys]
* @returns {Object} The resulting value of object a
*/
const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
forEach(
b,
(val, key) => {
if (thisArg && isFunction$1(val)) {
Object.defineProperty(a, key, {
// Null-proto descriptor so a polluted Object.prototype.get cannot
// hijack defineProperty's accessor-vs-data resolution.
__proto__: null,
value: bind(val, thisArg),
writable: true,
enumerable: true,
configurable: true,
});
} else {
Object.defineProperty(a, key, {
__proto__: null,
value: val,
writable: true,
enumerable: true,
configurable: true,
});
}
},
{ allOwnKeys }
);
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
const stripBOM = (content) => {
if (content.charCodeAt(0) === 0xfeff) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
const inherits = (constructor, superConstructor, props, descriptors) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
Object.defineProperty(constructor.prototype, 'constructor', {
__proto__: null,
value: constructor,
writable: true,
enumerable: false,
configurable: true,
});
Object.defineProperty(constructor, 'super', {
__proto__: null,
value: superConstructor.prototype,
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
const toArray = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
const isTypedArray = ((TypedArray) => {
// eslint-disable-next-line func-names
return (thing) => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object<any, any>} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
const forEachEntry = (obj, fn) => {
const generator = obj && obj[iterator];
const _iterator = generator.call(obj);
let result;
while ((result = _iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array<boolean>}
*/
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = (str) => {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
});
};
const { propertyIsEnumerable } = Object.prototype;
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
const reduceDescriptors = (obj, reducer) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
const freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
// skip restricted props in strict mode
if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
return false;
}
const value = obj[name];
if (!isFunction$1(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
/**
* Converts an array or a delimited string into an object set with values as keys and true as values.
* Useful for fast membership checks.
*
* @param {Array|string} arrayOrString - The array or string to convert.
* @param {string} delimiter - The delimiter to use if input is a string.
* @returns {Object} An object with keys from the array or string, values set to true.
*/
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach((value) => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop = () => {};
const toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(
thing &&
isFunction$1(thing.append) &&
thing[toStringTag] === 'FormData' &&
thing[iterator]
);
}
/**
* Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
*
* @param {Object} obj - The object to convert.
* @returns {Object} The JSON-compatible object.
*/
const toJSONObject = (obj) => {
const visited = new WeakSet();
const visit = (source) => {
if (isObject(source)) {
if (visited.has(source)) {
return;
}
//Buffer check
if (isBuffer(source)) {
return source;
}
if (!('toJSON' in source)) {
// add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
visited.add(source);
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
visited.delete(source);
return target;
}
}
return source;
};
return visit(obj);
};
/**
* Determines if a value is an async function.
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is an async function, otherwise false.
*/
const isAsyncFn = kindOfTest('AsyncFunction');
/**
* Determines if a value is thenable (has then and catch methods).
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is thenable, otherwise false.
*/
const isThenable = (thing) =>
thing &&
(isObject(thing) || isFunction$1(thing)) &&
isFunction$1(thing.then) &&
isFunction$1(thing.catch);
// original code
// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
/**
* Provides a cross-platform setImmediate implementation.
* Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
*
* @param {boolean} setImmediateSupported - Whether setImmediate is supported.
* @param {boolean} postMessageSupported - Whether postMessage is supported.
* @returns {Function} A function to schedule a callback asynchronously.
*/
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported
? ((token, callbacks) => {
_global.addEventListener(
'message',
({ source, data }) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
},
false
);
return (cb) => {
callbacks.push(cb);
_global.postMessage(token, '*');
};
})(`axios@${Math.random()}`, [])
: (cb) => setTimeout(cb);
})(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
/**
* Schedules a microtask or asynchronous callback as soon as possible.
* Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
*
* @type {Function}
*/
const asap =
typeof queueMicrotask !== 'undefined'
? queueMicrotask.bind(_global)
: (typeof process !== 'undefined' && process.nextTick) || _setImmediate;
// *********************
const isIterable = (thing) => thing != null && isFunction$1(thing[iterator]);
/**
* Determine if a value is iterable via an iterator that is NOT sourced solely
* from a polluted Object.prototype. Use this instead of `isIterable` whenever
* the iterable comes from untrusted input (e.g. user-supplied header sources),
* so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
* into an attacker-controlled entries iterator.
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value has a non-polluted iterator
*/
const isSafeIterable = (thing) =>
thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
var utils$1 = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isEmptyObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isReactNativeBlob,
isReactNative,
isBlob,
isRegExp,
isFunction: isFunction$1,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
hasOwnInPrototypeChain,
getSafeProp,
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap,
isIterable,
isSafeIterable,
};
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils$1.toObjectSet([
'age',
'authorization',
'content-length',
'content-type',
'etag',
'expires',
'from',
'host',
'if-modified-since',
'if-unmodified-since',
'last-modified',
'location',
'max-forwards',
'proxy-authorization',
'referer',
'retry-after',
'user-agent',
]);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = (rawHeaders) => {
const parsed = {};
let key;
let val;
let i;
rawHeaders &&
rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
function trimSPorHTAB(str) {
let start = 0;
let end = str.length;
while (start < end) {
const code = str.charCodeAt(start);
if (code !== 0x09 && code !== 0x20) {
break;
}
start += 1;
}
while (end > start) {
const code = str.charCodeAt(end - 1);
if (code !== 0x09 && code !== 0x20) {
break;
}
end -= 1;
}
return start === 0 && end === str.length ? str : str.slice(start, end);
}
// The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
// eslint-disable-next-line no-control-regex
const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
// eslint-disable-next-line no-control-regex
const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
function sanitizeValue(value, invalidChars) {
if (utils$1.isArray(value)) {
return value.map((item) => sanitizeValue(item, invalidChars));
}
return trimSPorHTAB(String(value).replace(invalidChars, ''));
}
const sanitizeHeaderValue = (value) =>
sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
const sanitizeByteStringHeaderValue = (value) =>
sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
function toByteStringHeaderObject(headers) {
const byteStringHeaders = Object.create(null);
utils$1.forEach(headers.toJSON(), (value, header) => {
byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
});
return byteStringHeaders;
}
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils$1.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils$1.isString(value)) return;
if (utils$1.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils$1.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header
.trim()
.toLowerCase()
.replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils$1.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach((methodName) => {
Object.defineProperty(obj, methodName + accessorName, {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: function (arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true,
});
});
}
let AxiosHeaders$1 = class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
return;
}
const key = utils$1.findKey(self, lHeader);
if (
!key ||
self[key] === undefined ||
_rewrite === true ||
(_rewrite === undefined && self[key] !== false)
) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) =>
utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
let obj = Object.create(null),
dest,
key;
for (const entry of header) {
if (!utils$1.isArray(entry)) {
throw new TypeError('Object iterator must return a key-value pair');
}
key = entry[0];
if (utils$1.hasOwnProp(obj, key)) {
dest = obj[key];
obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
} else {
obj[key] = entry[1];
}
}
setHeaders(obj, valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils$1.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils$1.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
return !!(
key &&
this[key] !== undefined &&
(!matcher || matchHeaderValue(this, this[key], key, matcher))
);
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils$1.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils$1.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils$1.forEach(this, (value, header) => {
const key = utils$1.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils$1.forEach(this, (value, header) => {
value != null &&
value !== false &&
(obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON())
.map(([header, value]) => header + ': ' + value)
.join('\n');
}
getSetCookie() {
return this.get('set-cookie') || [];
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals =
(this[$internals] =
this[$internals] =
{
accessors: {},
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
};
AxiosHeaders$1.accessor([
'Content-Type',
'Content-Length',
'Accept',
'Accept-Encoding',
'User-Agent',
'Authorization',
]);
// reserved names hotfix
utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({ value }, key) => {
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
},
};
});
utils$1.freezeMethods(AxiosHeaders$1);
const REDACTED = '[REDACTED ****]';
function hasOwnOrPrototypeToJSON(source) {
if (utils$1.hasOwnProp(source, 'toJSON')) {
return true;
}
let prototype = Object.getPrototypeOf(source);
while (prototype && prototype !== Object.prototype) {
if (utils$1.hasOwnProp(prototype, 'toJSON')) {
return true;
}
prototype = Object.getPrototypeOf(prototype);
}
return false;
}
// Build a plain-object snapshot of `config` and replace the value of any key
// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
// and AxiosHeaders, and short-circuits on circular references.
function redactConfig(config, redactKeys) {
const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase()));
const seen = [];
const visit = (source) => {
if (source === null || typeof source !== 'object') return source;
if (utils$1.isBuffer(source)) return source;
if (seen.indexOf(source) !== -1) return undefined;
if (source instanceof AxiosHeaders$1) {
source = source.toJSON();
}
seen.push(source);
let result;
if (utils$1.isArray(source)) {
result = [];
source.forEach((v, i) => {
const reducedValue = visit(v);
if (!utils$1.isUndefined(reducedValue)) {
result[i] = reducedValue;
}
});
} else {
if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
seen.pop();
return source;
}
result = Object.create(null);
for (const [key, value] of Object.entries(source)) {
const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
if (!utils$1.isUndefined(reducedValue)) {
result[key] = reducedValue;
}
}
}
seen.pop();
return result;
};
return visit(config);
}
let AxiosError$1 = class AxiosError extends Error {
static from(error, code, config, request, response, customProps) {
const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
// Match native `Error` `cause` semantics: non-enumerable. The wrapped
// error often carries circular internals (sockets, requests, agents), so
// an enumerable `cause` makes structured loggers (pino/winston) and any
// own-property walk throw "Converting circular structure to JSON".
// Regression from #6982; see #7205. `__proto__: null` mirrors the
// `message` descriptor below (prototype-pollution-safe descriptor).
Object.defineProperty(axiosError, 'cause', {
__proto__: null,
value: error,
writable: true,
enumerable: false,
configurable: true,
});
axiosError.name = error.name;
// Preserve status from the original error if not already set from response
if (error.status != null && axiosError.status == null) {
axiosError.status = error.status;
}
customProps && Object.assign(axiosError, customProps);
return axiosError;
}
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
constructor(message, code, config, request, response) {
super(message);
// Make message enumerable to maintain backward compatibility
// The native Error constructor sets message as non-enumerable,
// but axios < v1.13.3 had it as enumerable
Object.defineProperty(this, 'message', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: message,
enumerable: true,
writable: true,
configurable: true,
});
this.name = 'AxiosError';
this.isAxiosError = true;
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
if (response) {
this.response = response;
this.status = response.status;
}
}
toJSON() {
// Opt-in redaction: when the request config carries a `redact` array, the
// value of any matching key (case-insensitive, at any depth) is replaced
// with REDACTED in the serialized snapshot. Undefined or empty leaves the
// existing serialization behavior unchanged.
const config = this.config;
const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
const serializedConfig =
utils$1.isArray(redactKeys) && redactKeys.length > 0
? redactConfig(config, redactKeys)
: utils$1.toJSONObject(config);
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: serializedConfig,
code: this.code,
status: this.status,
};
}
};
// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
AxiosError$1.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
AxiosError$1.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
AxiosError$1.ECONNABORTED = 'ECONNABORTED';
AxiosError$1.ETIMEDOUT = 'ETIMEDOUT';
AxiosError$1.ECONNREFUSED = 'ECONNREFUSED';
AxiosError$1.ERR_NETWORK = 'ERR_NETWORK';
AxiosError$1.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
AxiosError$1.ERR_DEPRECATED = 'ERR_DEPRECATED';
AxiosError$1.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
AxiosError$1.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
AxiosError$1.ERR_CANCELED = 'ERR_CANCELED';
AxiosError$1.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
AxiosError$1.ERR_INVALID_URL = 'ERR_INVALID_URL';
AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
// eslint-disable-next-line strict
var httpAdapter = null;
// Default nesting limit shared with the inverse transform (formDataToJSON) so
// the FormData <-> JSON round-trip stays symmetric.
const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path
.concat(key)
.map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
})
.join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array<any>} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils$1.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object<any, any>} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object<string, any>} options
*
* @returns
*/
function toFormData$1(obj, formData, options) {
if (!utils$1.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (FormData)();
// eslint-disable-next-line no-param-reassign
options = utils$1.toFlatObject(
options,
{
metaTokens: true,
dots: false,
indexes: false,
},
false,
function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils$1.isUndefined(source[option]);
}
);
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
const stack = [];
if (!utils$1.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils$1.isDate(value)) {
return value.toISOString();
}
if (utils$1.isBoolean(value)) {
return value.toString();
}
if (!useBlob && utils$1.isBlob(value)) {
throw new AxiosError$1('Blob is not supported. Use a Buffer instead.');
}
if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
if (useBlob && typeof _Blob === 'function') {
return new _Blob([value]);
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(value);
}
throw new AxiosError$1('Blob is not supported. Use a Buffer instead.', AxiosError$1.ERR_NOT_SUPPORT);
}
return value;
}
function throwIfMaxDepthExceeded(depth) {
if (depth > maxDepth) {
throw new AxiosError$1(
'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth,
AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED
);
}
}
function stringifyWithDepthLimit(value, depth) {
if (maxDepth === Infinity) {
return JSON.stringify(value);
}
const ancestors = [];
return JSON.stringify(value, function limitDepth(_key, currentValue) {
if (!utils$1.isObject(currentValue)) {
return currentValue;
}
while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
ancestors.pop();
}
ancestors.push(currentValue);
throwIfMaxDepthExceeded(depth + ancestors.length - 1);
return currentValue;
});
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array<String|Number>} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
let arr = value;
if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
if (value && !path && typeof value === 'object') {
if (utils$1.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = stringifyWithDepthLimit(value, 1);
} else if (
(utils$1.isArray(value) && isFlatArray(value)) ||
((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)))
) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils$1.isUndefined(el) || el === null) &&
formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true
? renderKey([key], index, dots)
: indexes === null
? key
: key + '[]',
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable,
});
function build(value, path, depth = 0) {
if (utils$1.isUndefined(value)) return;
throwIfMaxDepthExceeded(depth);
if (stack.indexOf(value) !== -1) {
throw new Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils$1.forEach(value, function each(el, key) {
const result =
!(utils$1.isUndefined(el) || el === null) &&
visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
if (result === true) {
build(el, path ? path.concat(key) : [key], depth + 1);
}
});
stack.pop();
}
if (!utils$1.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode$1(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
};
return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData$1(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder
? (value) => encoder.call(this, value, encode$1)
: encode$1;
return this._pairs
.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '')
.join('&');
};
/**
* It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
* their plain counterparts (`:`, `$`, `,`, `+`).
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val)
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?(object|Function)} options
*
* @returns {string} The formatted url
*/
function buildURL(url, params, options) {
if (!params) {
return url;
}
url = url || '';
const _options = utils$1.isFunction(options)
? {
serialize: options,
}
: options;
// Read serializer options pollution-safely: own properties and methods on a
// class/template prototype are honored, but values injected onto a polluted
// Object.prototype are ignored.
const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
const serializeFn = utils$1.getSafeProp(_options, 'serialize');
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, _options);
} else {
serializedParams = utils$1.isURLSearchParams(params)
? params.toString()
: new AxiosURLSearchParams(params, _options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
* @param {Object} options The options for the interceptor, synchronous and runWhen
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null,
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {void}
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils$1.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
var transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false,
legacyInterceptorReqResOrdering: true,
advertiseZstdAcceptEncoding: false,
validateStatusUndefinedResolves: true,
};
var URLSearchParams$1 = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
var FormData$1 = typeof FormData !== 'undefined' ? FormData : null;
var Blob$1 = typeof Blob !== 'undefined' ? Blob : null;
var platform$1 = {
isBrowser: true,
classes: {
URLSearchParams: URLSearchParams$1,
FormData: FormData$1,
Blob: Blob$1,
},
protocols: ['http', 'https', 'file', 'blob', 'url', 'data'],
};
const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
const _navigator = (typeof navigator === 'object' && navigator) || undefined;
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
const hasStandardBrowserEnv =
hasBrowserEnv &&
(!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
const hasStandardBrowserWebWorkerEnv = (() => {
return (
typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope &&
typeof self.importScripts === 'function'
);
})();
const origin = (hasBrowserEnv && window.location.href) || 'http://localhost';
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
hasBrowserEnv: hasBrowserEnv,
hasStandardBrowserEnv: hasStandardBrowserEnv,
hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
navigator: _navigator,
origin: origin
});
var platform = {
...utils,
...platform$1,
};
function toURLEncodedForm(data, options) {
return toFormData$1(data, new platform.classes.URLSearchParams(), {
visitor: function (value, key, path, helpers) {
if (platform.isNode && utils$1.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
},
...options,
});
}
const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
function throwIfDepthExceeded(index) {
if (index > MAX_DEPTH) {
throw new AxiosError$1(
'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,
AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED
);
}
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
const path = [];
const pattern = /\w+|\[(\w*)]/g;
let match;
while ((match = pattern.exec(name)) !== null) {
throwIfDepthExceeded(path.length);
path.push(match[0] === '[]' ? '' : match[1] || match[0]);
}
return path;
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
throwIfDepthExceeded(index);
let name = path[index++];
if (name === '__proto__') return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils$1.isArray(target) ? target.length : name;
if (isLast) {
if (utils$1.hasOwnProp(target, name)) {
target[name] = utils$1.isArray(target[name])
? target[name].concat(value)
: [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils$1.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
const obj = {};
utils$1.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
const own = (obj, key) => (obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined);
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils$1.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils$1.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [
function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils$1.isObject(data);
if (isObjectPayload && utils$1.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils$1.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (
utils$1.isArrayBuffer(data) ||
utils$1.isBuffer(data) ||
utils$1.isStream(data) ||
utils$1.isFile(data) ||
utils$1.isBlob(data) ||
utils$1.isReadableStream(data)
) {
return data;
}
if (utils$1.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$1.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
const formSerializer = own(this, 'formSerializer');
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, formSerializer).toString();
}
if (
(isFileList = utils$1.isFileList(data)) ||
contentType.indexOf('multipart/form-data') > -1
) {
const env = own(this, 'env');
const _FormData = env && env.FormData;
return toFormData$1(
isFileList ? { 'files[]': data } : data,
_FormData && new _FormData(),
formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
},
],
transformResponse: [
function transformResponse(data) {
const transitional = own(this, 'transitional') || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const responseType = own(this, 'responseType');
const JSONRequested = responseType === 'json';
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (
data &&
utils$1.isString(data) &&
((forcedJSONParsing && !responseType) || JSONRequested)
) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data, own(this, 'parseReviver'));
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
}
throw e;
}
}
}
return data;
},
],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob,
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
Accept: 'application/json, text/plain, */*',
'Content-Type': undefined,
},
},
};
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], (method) => {
defaults.headers[method] = {};
});
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders$1.from(context.headers);
let data = context.data;
utils$1.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
function isCancel$1(value) {
return !!(value && value.__CANCEL__);
}
let CanceledError$1 = class CanceledError extends AxiosError$1 {
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
constructor(message, config, request) {
super(message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request);
this.name = 'CanceledError';
this.__CANCEL__ = true;
}
};
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError$1(
'Request failed with status code ' + response.status,
response.status >= 400 && response.status < 500 ? AxiosError$1.ERR_BAD_REQUEST : AxiosError$1.ERR_BAD_RESPONSE,
response.config,
response.request,
response
));
}
}
function parseProtocol(url) {
const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
return (match && match[1]) || '';
}
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round((bytesCount * 1000) / passed) : undefined;
};
}
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1000 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn(...args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
return [throttled, flush];
}
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle((e) => {
if (!e || typeof e.loaded !== 'number') {
return;
}
const rawLoaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
const progressBytes = Math.max(0, loaded - bytesNotified);
const rate = _speedometer(progressBytes);
bytesNotified = Math.max(bytesNotified, loaded);
const data = {
loaded,
total,
progress: total ? loaded / total : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null,
[isDownloadStream ? 'download' : 'upload']: true,
};
listener(data);
}, freq);
};
const progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [
(loaded) =>
throttled[0]({
lengthComputable,
total,
loaded,
}),
throttled[1],
];
};
const asyncDecorator =
(fn) =>
(...args) =>
utils$1.asap(() => fn(...args));
var isURLSameOrigin = platform.hasStandardBrowserEnv
? ((origin, isMSIE) => (url) => {
url = new URL(url, platform.origin);
return (
origin.protocol === url.protocol &&
origin.host === url.host &&
(isMSIE || origin.port === url.port)
);
})(
new URL(platform.origin),
platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
)
: () => true;
var cookies = platform.hasStandardBrowserEnv
? // Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure, sameSite) {
if (typeof document === 'undefined') return;
const cookie = [`${name}=${encodeURIComponent(value)}`];
if (utils$1.isNumber(expires)) {
cookie.push(`expires=${new Date(expires).toUTCString()}`);
}
if (utils$1.isString(path)) {
cookie.push(`path=${path}`);
}
if (utils$1.isString(domain)) {
cookie.push(`domain=${domain}`);
}
if (secure === true) {
cookie.push('secure');
}
if (utils$1.isString(sameSite)) {
cookie.push(`SameSite=${sameSite}`);
}
document.cookie = cookie.join('; ');
},
read(name) {
if (typeof document === 'undefined') return null;
// Match name=value by splitting on the semicolon separator instead of building a
// RegExp from `name` — interpolating an unescaped string into a RegExp would let
// metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
// match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
// "; ", so ignore optional whitespace before each cookie name.
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].replace(/^\s+/, '');
const eq = cookie.indexOf('=');
if (eq !== -1 && cookie.slice(0, eq) === name) {
try {
return decodeURIComponent(cookie.slice(eq + 1));
} catch (e) {
return cookie.slice(eq + 1);
}
}
}
return null;
},
remove(name) {
this.write(name, '', Date.now() - 86400000, '/');
},
}
: // Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {},
};
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
if (typeof url !== 'string') {
return false;
}
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
const malformedHttpProtocol = /^https?:(?!\/\/)/i;
const httpProtocolControlCharacters = /[\t\n\r]/g;
function stripLeadingC0ControlOrSpace(url) {
let i = 0;
while (i < url.length && url.charCodeAt(i) <= 0x20) {
i++;
}
return url.slice(i);
}
function normalizeURLForProtocolCheck(url) {
return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
}
function assertValidHttpProtocolURL(url, config) {
if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
throw new AxiosError$1(
'Invalid URL: missing "//" after protocol',
AxiosError$1.ERR_INVALID_URL,
config
);
}
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
assertValidHttpProtocolURL(requestedURL, config);
let isRelativeUrl = !isAbsoluteURL(requestedURL);
if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
assertValidHttpProtocolURL(baseURL, config);
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
const headersToObject = (thing) => (thing instanceof AxiosHeaders$1 ? { ...thing } : thing);
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig$1(config1, config2) {
// eslint-disable-next-line no-param-reassign
config1 = config1 || {};
config2 = config2 || {};
// Use a null-prototype object so that downstream reads such as `config.auth`
// or `config.baseURL` cannot inherit polluted values from Object.prototype.
// `hasOwnProperty` is restored as a non-enumerable own slot to preserve
// ergonomics for user code that relies on it.
const config = Object.create(null);
Object.defineProperty(config, 'hasOwnProperty', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: Object.prototype.hasOwnProperty,
enumerable: false,
writable: true,
configurable: true,
});
function getMergedValue(target, source, prop, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({ caseless }, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(a, b, prop, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, prop, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, prop, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
function getMergedTransitionalOption(prop) {
const transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
if (!utils$1.isUndefined(transitional2)) {
if (utils$1.isPlainObject(transitional2)) {
if (utils$1.hasOwnProp(transitional2, prop)) {
return transitional2[prop];
}
} else {
return undefined;
}
}
const transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
return transitional1[prop];
}
return undefined;
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (utils$1.hasOwnProp(config2, prop)) {
return getMergedValue(a, b);
} else if (utils$1.hasOwnProp(config1, prop)) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
allowedSocketPaths: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b, prop) =>
mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true),
};
utils$1.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
const configValue = merge(a, b, prop);
(utils$1.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
if (
utils$1.hasOwnProp(config2, 'validateStatus') &&
utils$1.isUndefined(config2.validateStatus) &&
getMergedTransitionalOption('validateStatusUndefinedResolves') === false
) {
if (utils$1.hasOwnProp(config1, 'validateStatus')) {
config.validateStatus = getMergedValue(undefined, config1.validateStatus);
} else {
delete config.validateStatus;
}
}
return config;
}
const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
function setFormDataHeaders(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders || {}).forEach(([key, val]) => {
if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8$1 = (str) =>
encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
function resolveConfig(config) {
const newConfig = mergeConfig$1({}, config);
// Read only own properties to prevent prototype pollution gadgets
// (e.g. Object.prototype.baseURL = 'https://evil.com').
const own = (key) => (utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined);
const data = own('data');
let withXSRFToken = own('withXSRFToken');
const xsrfHeaderName = own('xsrfHeaderName');
const xsrfCookieName = own('xsrfCookieName');
let headers = own('headers');
const auth = own('auth');
const baseURL = own('baseURL');
const allowAbsoluteUrls = own('allowAbsoluteUrls');
const url = own('url');
newConfig.headers = headers = AxiosHeaders$1.from(headers);
newConfig.url = buildURL(
buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig),
own('params'),
own('paramsSerializer')
);
// HTTP basic authentication
if (auth) {
const username = utils$1.getSafeProp(auth, 'username') || '';
const password = utils$1.getSafeProp(auth, 'password') || '';
try {
headers.set(
'Authorization',
'Basic ' + btoa(username + ':' + (password ? encodeUTF8$1(password) : ''))
);
} catch (e) {
throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_OPTION_VALUE, config);
}
}
if (utils$1.isFormData(data)) {
if (
platform.hasStandardBrowserEnv ||
platform.hasStandardBrowserWebWorkerEnv ||
utils$1.isReactNative(data)
) {
headers.setContentType(undefined); // browser/web worker/RN handles it
} else if (utils$1.isFunction(data.getHeaders)) {
// Node.js FormData (like form-data package)
setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
if (utils$1.isFunction(withXSRFToken)) {
withXSRFToken = withXSRFToken(newConfig);
}
// Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
// and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
// the XSRF token cross-origin.
const shouldSendXSRF =
withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url));
if (shouldSendXSRF) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
}
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
var xhrAdapter = isXHRAdapterSupported &&
function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders$1.from(_config.headers).normalize();
let { responseType, onUploadProgress, onDownloadProgress } = _config;
let onCanceled;
let uploadThrottled, downloadThrottled;
let flushUpload, flushDownload;
function done() {
flushUpload && flushUpload(); // flush events
flushDownload && flushDownload(); // flush events
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener('abort', onCanceled);
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders$1.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData =
!responseType || responseType === 'text' || responseType === 'json'
? request.responseText
: request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request,
};
settle(
function _resolve(value) {
resolve(value);
done();
},
function _reject(err) {
reject(err);
done();
},
response
);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (
request.status === 0 &&
!(request.responseURL && request.responseURL.startsWith('file:'))
) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request));
done();
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError(event) {
// Browsers deliver a ProgressEvent in XHR onerror
// (message may be empty; when present, surface it)
// See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
const msg = event && event.message ? event.message : 'Network Error';
const err = new AxiosError$1(msg, AxiosError$1.ERR_NETWORK, config, request);
// attach the underlying event for consumers who want details
err.event = event || null;
reject(err);
done();
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout
? 'timeout of ' + _config.timeout + 'ms exceeded'
: 'timeout exceeded';
const transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(
new AxiosError$1(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED,
config,
request
)
);
done();
// Clean up request
request = null;
};
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = _config.responseType;
}
// Handle progress if needed
if (onDownloadProgress) {
[downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
request.addEventListener('progress', downloadThrottled);
}
// Not all browsers support upload events
if (onUploadProgress && request.upload) {
[uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
request.upload.addEventListener('progress', uploadThrottled);
request.upload.addEventListener('loadend', flushUpload);
}
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = (cancel) => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel);
request.abort();
done();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted
? onCanceled()
: _config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(_config.url);
if (protocol && !platform.protocols.includes(protocol)) {
reject(
new AxiosError$1(
'Unsupported protocol ' + protocol + ':',
AxiosError$1.ERR_BAD_REQUEST,
config
)
);
done();
return;
}
// Send the request
request.send(requestData || null);
});
};
const composeSignals = (signals, timeout) => {
signals = signals ? signals.filter(Boolean) : [];
if (!timeout && !signals.length) {
return;
}
const controller = new AbortController();
let aborted = false;
const onabort = function (reason) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = reason instanceof Error ? reason : this.reason;
controller.abort(
err instanceof AxiosError$1
? err
: new CanceledError$1(err instanceof Error ? err.message : err)
);
}
};
let timer =
timeout &&
setTimeout(() => {
timer = null;
onabort(new AxiosError$1(`timeout of ${timeout}ms exceeded`, AxiosError$1.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (!signals) { return; }
timer && clearTimeout(timer);
timer = null;
signals.forEach((signal) => {
signal.unsubscribe
? signal.unsubscribe(onabort)
: signal.removeEventListener('abort', onabort);
});
signals = null;
};
signals.forEach((signal) => signal.addEventListener('abort', onabort, { once: true }));
const { signal } = controller;
signal.unsubscribe = () => utils$1.asap(unsubscribe);
return signal;
};
const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
};
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
yield* stream;
return;
}
const reader = stream.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) {
break;
}
yield value;
}
} finally {
await reader.cancel();
}
};
const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = (e) => {
if (!done) {
done = true;
onFinish && onFinish(e);
}
};
return new ReadableStream(
{
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = (bytes += len);
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
},
},
{
highWaterMark: 2,
}
);
};
/**
* Estimate decoded byte length of a data:// URL *without* allocating large buffers.
* - For base64: compute exact decoded size using length and padding;
* handle %XX at the character-count level (no string allocation).
* - For non-base64: compute the exact percent-decoded UTF-8 byte length.
*
* @param {string} url
* @returns {number}
*/
const isHexDigit = (charCode) =>
(charCode >= 48 && charCode <= 57) ||
(charCode >= 65 && charCode <= 70) ||
(charCode >= 97 && charCode <= 102);
const isPercentEncodedByte = (str, i, len) =>
i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
function estimateDataURLDecodedBytes(url) {
if (!url || typeof url !== 'string') return 0;
if (!url.startsWith('data:')) return 0;
const comma = url.indexOf(',');
if (comma < 0) return 0;
const meta = url.slice(5, comma);
const body = url.slice(comma + 1);
const isBase64 = /;base64/i.test(meta);
if (isBase64) {
let effectiveLen = body.length;
const len = body.length; // cache length
for (let i = 0; i < len; i++) {
if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
const a = body.charCodeAt(i + 1);
const b = body.charCodeAt(i + 2);
const isHex = isHexDigit(a) && isHexDigit(b);
if (isHex) {
effectiveLen -= 2;
i += 2;
}
}
}
let pad = 0;
let idx = len - 1;
const tailIsPct3D = (j) =>
j >= 2 &&
body.charCodeAt(j - 2) === 37 && // '%'
body.charCodeAt(j - 1) === 51 && // '3'
(body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'
if (idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
idx--;
} else if (tailIsPct3D(idx)) {
pad++;
idx -= 3;
}
}
if (pad === 1 && idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
} else if (tailIsPct3D(idx)) {
pad++;
}
}
const groups = Math.floor(effectiveLen / 4);
const bytes = groups * 3 - (pad || 0);
return bytes > 0 ? bytes : 0;
}
// Compute UTF-8 byte length directly from UTF-16 code units without allocating
// a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
// Valid %XX triplets count as one decoded byte; this matches the bytes that
// decodeURIComponent(body) would produce before Buffer re-encodes the string.
let bytes = 0;
for (let i = 0, len = body.length; i < len; i++) {
const c = body.charCodeAt(i);
if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
bytes += 1;
i += 2;
} else if (c < 0x80) {
bytes += 1;
} else if (c < 0x800) {
bytes += 2;
} else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
const next = body.charCodeAt(i + 1);
if (next >= 0xdc00 && next <= 0xdfff) {
bytes += 4;
i++;
} else {
bytes += 3;
}
} else {
bytes += 3;
}
}
return bytes;
}
const VERSION$1 = "1.18.1";
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const { isFunction } = utils$1;
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8 = (str) =>
encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
// Decode before composing the `auth` option so credentials such as
// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
// original value for malformed input so a bad encoding never throws.
const decodeURIComponentSafe = (value) => {
if (!utils$1.isString(value)) {
return value;
}
try {
return decodeURIComponent(value);
} catch (error) {
return value;
}
};
const test = (fn, ...args) => {
try {
return !!fn(...args);
} catch (e) {
return false;
}
};
const maybeWithAuthCredentials = (url) => {
const protocolIndex = url.indexOf('://');
let urlToCheck = url;
if (protocolIndex !== -1) {
urlToCheck = urlToCheck.slice(protocolIndex + 3);
}
return urlToCheck.includes('@') || urlToCheck.includes(':');
};
const factory = (env) => {
const globalObject =
utils$1.global !== undefined && utils$1.global !== null
? utils$1.global
: globalThis;
const { ReadableStream, TextEncoder } = globalObject;
env = utils$1.merge.call(
{
skipUndefined: true,
},
{
Request: globalObject.Request,
Response: globalObject.Response,
},
env
);
const { fetch: envFetch, Request, Response } = env;
const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
const isRequestSupported = isFunction(Request);
const isResponseSupported = isFunction(Response);
if (!isFetchSupported) {
return false;
}
const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
const encodeText =
isFetchSupported &&
(typeof TextEncoder === 'function'
? (
(encoder) => (str) =>
encoder.encode(str)
)(new TextEncoder())
: async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
const supportsRequestStream =
isRequestSupported &&
isReadableStreamSupported &&
test(() => {
let duplexAccessed = false;
const request = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
});
const hasContentType = request.headers.has('Content-Type');
if (request.body != null) {
request.body.cancel();
}
return duplexAccessed && !hasContentType;
});
const supportsResponseStream =
isResponseSupported &&
isReadableStreamSupported &&
test(() => utils$1.isReadableStream(new Response('').body));
const resolvers = {
stream: supportsResponseStream && ((res) => res.body),
};
isFetchSupported &&
(() => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {
!resolvers[type] &&
(resolvers[type] = (res, config) => {
let method = res && res[type];
if (method) {
return method.call(res);
}
throw new AxiosError$1(
`Response type '${type}' is not supported`,
AxiosError$1.ERR_NOT_SUPPORT,
config
);
});
});
})();
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if (utils$1.isBlob(body)) {
return body.size;
}
if (utils$1.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: 'POST',
body,
});
return (await _request.arrayBuffer()).byteLength;
}
if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
return body.byteLength;
}
if (utils$1.isURLSearchParams(body)) {
body = body + '';
}
if (utils$1.isString(body)) {
return (await encodeText(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils$1.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
return async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions,
maxContentLength,
maxBodyLength,
} = resolveConfig(config);
const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
const own = (key) => (utils$1.hasOwnProp(config, key) ? config[key] : undefined);
let _fetch = envFetch || fetch;
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let composedSignal = composeSignals(
[signal, cancelToken && cancelToken.toAbortSignal()],
timeout
);
let request = null;
const unsubscribe =
composedSignal &&
composedSignal.unsubscribe &&
(() => {
composedSignal.unsubscribe();
});
let requestContentLength;
// AxiosError we raise while the request body is being streamed. Captured
// by identity so the catch block can surface it directly, regardless of
// how the runtime wraps the resulting fetch rejection (undici exposes it
// as `err.cause`; some browsers drop the original error entirely).
let pendingBodyError = null;
const maxBodyLengthError = () =>
new AxiosError$1(
'Request body larger than maxBodyLength limit',
AxiosError$1.ERR_BAD_REQUEST,
config,
request
);
try {
// HTTP basic authentication
let auth = undefined;
const configAuth = own('auth');
if (configAuth) {
const username = utils$1.getSafeProp(configAuth, 'username') || '';
const password = utils$1.getSafeProp(configAuth, 'password') || '';
auth = {
username,
password
};
}
if (maybeWithAuthCredentials(url)) {
const parsedURL = new URL(url, platform.origin);
if (!auth && (parsedURL.username || parsedURL.password)) {
const urlUsername = decodeURIComponentSafe(parsedURL.username);
const urlPassword = decodeURIComponentSafe(parsedURL.password);
auth = {
username: urlUsername,
password: urlPassword
};
}
if (parsedURL.username || parsedURL.password) {
parsedURL.username = '';
parsedURL.password = '';
url = parsedURL.href;
}
}
if (auth) {
headers.delete('authorization');
headers.set(
'Authorization',
'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || '')))
);
}
// Enforce maxContentLength for data: URLs up-front so we never materialize
// an oversized payload. The HTTP adapter applies the same check (see http.js
// "if (protocol === 'data:')" branch).
if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
const estimated = estimateDataURLDecodedBytes(url);
if (estimated > maxContentLength) {
throw new AxiosError$1(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError$1.ERR_BAD_RESPONSE,
config,
request
);
}
}
// Enforce maxBodyLength against known-size bodies before dispatch using
// the body's *actual* size — never a caller-declared Content-Length,
// which could under-report to slip an oversized body past the check.
// Unknown-size streams return undefined here and are counted per-chunk
// below as fetch consumes them.
if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
const outboundLength = await getBodyLength(data);
if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
requestContentLength = outboundLength;
if (outboundLength > maxBodyLength) {
throw maxBodyLengthError();
}
}
}
// A streamed body under maxBodyLength must be counted as fetch consumes
// it; its size is never trusted from a caller-declared Content-Length.
const mustEnforceStreamBody =
hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
const trackRequestStream = (stream, onProgress, flush) =>
trackStream(
stream,
DEFAULT_CHUNK_SIZE,
(loadedBytes) => {
if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
throw (pendingBodyError = maxBodyLengthError());
}
onProgress && onProgress(loadedBytes);
},
flush
);
if (
supportsRequestStream &&
method !== 'get' &&
method !== 'head' &&
(onUploadProgress || mustEnforceStreamBody)
) {
requestContentLength =
requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
// A declared length of 0 is only trusted to skip the wrap when we are
// not enforcing a stream limit (which must not rely on that header).
if (requestContentLength !== 0 || mustEnforceStreamBody) {
let _request = new Request(url, {
method: 'POST',
body: data,
duplex: 'half',
});
let contentTypeHeader;
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
const [onProgress, flush] =
(onUploadProgress &&
progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
)) ||
[];
data = trackRequestStream(_request.body, onProgress, flush);
}
}
} else if (
mustEnforceStreamBody &&
!isRequestSupported &&
isReadableStreamSupported &&
method !== 'get' &&
method !== 'head'
) {
data = trackRequestStream(data);
} else if (
mustEnforceStreamBody &&
isRequestSupported &&
!supportsRequestStream &&
method !== 'get' &&
method !== 'head'
) {
throw new AxiosError$1(
'Stream request bodies are not supported by the current fetch implementation',
AxiosError$1.ERR_NOT_SUPPORT,
config,
request
);
}
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
// If data is FormData and Content-Type is multipart/form-data without boundary,
// delete it so fetch can set it correctly with the boundary
if (utils$1.isFormData(data)) {
const contentType = headers.getContentType();
if (
contentType &&
/^multipart\/form-data/i.test(contentType) &&
!/boundary=/i.test(contentType)
) {
headers.delete('content-type');
}
}
// Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
headers.set('User-Agent', 'axios/' + VERSION$1, false);
const resolvedOptions = {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: toByteStringHeaderObject(headers.normalize()),
body: data,
duplex: 'half',
credentials: isCredentialsSupported ? withCredentials : undefined,
};
request = isRequestSupported && new Request(url, resolvedOptions);
let response = await (isRequestSupported
? _fetch(request, fetchOptions)
: _fetch(url, resolvedOptions));
const responseHeaders = AxiosHeaders$1.from(response.headers);
// Cheap pre-check: if the server honestly declares a content-length that
// already exceeds the cap, reject before we start streaming.
if (hasMaxContentLength) {
const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
if (declaredLength != null && declaredLength > maxContentLength) {
throw new AxiosError$1(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError$1.ERR_BAD_RESPONSE,
config,
request
);
}
}
const isStreamResponse =
supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (
supportsResponseStream &&
response.body &&
(onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe))
) {
const options = {};
['status', 'statusText', 'headers'].forEach((prop) => {
options[prop] = response[prop];
});
const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
const [onProgress, flush] =
(onDownloadProgress &&
progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
)) ||
[];
let bytesRead = 0;
const onChunkProgress = (loadedBytes) => {
if (hasMaxContentLength) {
bytesRead = loadedBytes;
if (bytesRead > maxContentLength) {
throw new AxiosError$1(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError$1.ERR_BAD_RESPONSE,
config,
request
);
}
}
onProgress && onProgress(loadedBytes);
};
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](
response,
config
);
// Fallback enforcement for environments without ReadableStream support
// (legacy runtimes). Detect materialized size from typed output; skip
// streams/Response passthrough since the user will read those themselves.
if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
let materializedSize;
if (responseData != null) {
if (typeof responseData.byteLength === 'number') {
materializedSize = responseData.byteLength;
} else if (typeof responseData.size === 'number') {
materializedSize = responseData.size;
} else if (typeof responseData === 'string') {
materializedSize =
typeof TextEncoder === 'function'
? new TextEncoder().encode(responseData).byteLength
: responseData.length;
}
}
if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
throw new AxiosError$1(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError$1.ERR_BAD_RESPONSE,
config,
request
);
}
}
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders$1.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request,
});
});
} catch (err) {
unsubscribe && unsubscribe();
// Safari can surface fetch aborts as a DOMException-like object whose
// branded getters throw. Prefer our composed signal reason before reading
// the caught error, preserving timeout vs cancellation semantics.
if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError$1) {
const canceledError = composedSignal.reason;
canceledError.config = config;
request && (canceledError.request = request);
if (err !== canceledError) {
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(canceledError, 'cause', {
__proto__: null,
value: err,
writable: true,
enumerable: false,
configurable: true,
});
}
throw canceledError;
}
// Surface a maxBodyLength violation we raised while the request body was
// being streamed. Matching by identity (rather than reading
// `err.cause.isAxiosError`) keeps the error deterministic across runtimes
// and avoids both prototype-pollution reads and mis-attributing a foreign
// AxiosError that merely happened to land in `err.cause`.
if (pendingBodyError) {
request && !pendingBodyError.request && (pendingBodyError.request = request);
throw pendingBodyError;
}
// Re-throw AxiosErrors we raised synchronously (data: URL / content-length
// pre-checks, response size enforcement) without re-wrapping them.
if (err instanceof AxiosError$1) {
request && !err.request && (err.request = request);
throw err;
}
if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
const networkError = new AxiosError$1(
'Network Error',
AxiosError$1.ERR_NETWORK,
config,
request,
err && err.response
);
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(networkError, 'cause', {
__proto__: null,
value: err.cause || err,
writable: true,
enumerable: false,
configurable: true,
});
throw networkError;
}
throw AxiosError$1.from(err, err && err.code, config, request, err && err.response);
}
};
};
const seedCache = new Map();
const getFetch = (config) => {
let env = (config && config.env) || {};
const { fetch, Request, Response } = env;
const seeds = [Request, Response, fetch];
let len = seeds.length,
i = len,
seed,
target,
map = seedCache;
while (i--) {
seed = seeds[i];
target = map.get(seed);
target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));
map = target;
}
return target;
};
getFetch();
/**
* Known adapters mapping.
* Provides environment-specific adapters for Axios:
* - `http` for Node.js
* - `xhr` for browsers
* - `fetch` for fetch API-based requests
*
* @type {Object<string, Function|Object>}
*/
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: {
get: getFetch,
},
};
// Assign adapter names for easier debugging and identification
utils$1.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
// Null-proto descriptors so a polluted Object.prototype.get cannot turn
// these data descriptors into accessor descriptors on the way in.
Object.defineProperty(fn, 'name', { __proto__: null, value });
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', { __proto__: null, value });
}
});
/**
* Render a rejection reason string for unknown or unsupported adapters
*
* @param {string} reason
* @returns {string}
*/
const renderReason = (reason) => `- ${reason}`;
/**
* Check if the adapter is resolved (function, null, or false)
*
* @param {Function|null|false} adapter
* @returns {boolean}
*/
const isResolvedHandle = (adapter) =>
utils$1.isFunction(adapter) || adapter === null || adapter === false;
/**
* Get the first suitable adapter from the provided list.
* Tries each adapter in order until a supported one is found.
* Throws an AxiosError if no adapter is suitable.
*
* @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
* @param {Object} config - Axios request configuration
* @throws {AxiosError} If no suitable adapter is available
* @returns {Function} The resolved adapter function
*/
function getAdapter$1(adapters, config) {
adapters = utils$1.isArray(adapters) ? adapters : [adapters];
const { length } = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError$1(`Unknown adapter '${id}'`);
}
}
if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons).map(
([id, state]) =>
`adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
let s = length
? reasons.length > 1
? 'since :\n' + reasons.map(renderReason).join('\n')
: ' ' + renderReason(reasons[0])
: 'as no adapter specified';
throw new AxiosError$1(
`There is no suitable adapter to dispatch the request ` + s,
AxiosError$1.ERR_NOT_SUPPORT
);
}
return adapter;
}
/**
* Exports Axios adapters and utility to resolve an adapter
*/
var adapters = {
/**
* Resolve an adapter from a list of adapter names or functions.
* @type {Function}
*/
getAdapter: getAdapter$1,
/**
* Exposes all known adapters
* @type {Object<string, Function|Object>}
*/
adapters: knownAdapters,
};
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError$1(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders$1.from(config.headers);
// Transform request data
config.data = transformData.call(config, config.transformRequest);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
return adapter(config).then(
function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Expose the current response on config so that transformResponse can
// attach it to any AxiosError it throws (e.g. on JSON parse failure).
// We clean it up afterwards to avoid polluting the config object.
config.response = response;
try {
response.data = transformData.call(config, config.transformResponse, response);
} finally {
delete config.response;
}
response.headers = AxiosHeaders$1.from(response.headers);
return response;
},
function onAdapterRejection(reason) {
if (!isCancel$1(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
config.response = reason.response;
try {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
} finally {
delete config.response;
}
reason.response.headers = AxiosHeaders$1.from(reason.response.headers);
}
}
return Promise.reject(reason);
}
);
}
const validators$1 = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators$1[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
const deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators$1.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return (
'[Axios v' +
VERSION$1 +
"] Transitional option '" +
opt +
"'" +
desc +
(message ? '. ' + message : '')
);
}
// eslint-disable-next-line func-names
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError$1(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError$1.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
validators$1.spelling = function spelling(correctSpelling) {
return (value, opt) => {
// eslint-disable-next-line no-console
console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
return true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object' || options === null) {
throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
// Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
// a non-function validator and cause a TypeError.
const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
if (validator) {
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError$1(
'option ' + opt + ' must be ' + result,
AxiosError$1.ERR_BAD_OPTION_VALUE
);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION);
}
}
}
var validator = {
assertOptions,
validators: validators$1,
};
const validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
let Axios$1 = class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig || {};
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager(),
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
// slice off the Error: ... line
const stack = (() => {
if (!dummy.stack) {
return '';
}
const firstNewlineIndex = dummy.stack.indexOf('\n');
return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
})();
try {
if (!err.stack) {
err.stack = stack;
// match without the 2 top stack lines
} else if (stack) {
const firstNewlineIndex = stack.indexOf('\n');
const secondNewlineIndex =
firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
const stackWithoutTwoTopLines =
secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
err.stack += '\n' + stack;
}
}
} catch (e) {
// ignore the case where "stack" is an un-writable property
}
}
throw err;
}
}
_request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig$1(this.defaults, config);
const { transitional, paramsSerializer, headers } = config;
if (transitional !== undefined) {
validator.assertOptions(
transitional,
{
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean),
legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
validateStatusUndefinedResolves: validators.transitional(validators.boolean),
},
false
);
}
if (paramsSerializer != null) {
if (utils$1.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer,
};
} else {
validator.assertOptions(
paramsSerializer,
{
encode: validators.function,
serialize: validators.function,
},
true
);
}
}
// Set config.allowAbsoluteUrls
if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
} else {
config.allowAbsoluteUrls = true;
}
validator.assertOptions(
config,
{
baseUrl: validators.spelling('baseURL'),
withXsrfToken: validators.spelling('withXSRFToken'),
},
true
);
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
headers &&
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => {
delete headers[method];
});
config.headers = AxiosHeaders$1.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
const transitional = config.transitional || transitionalDefaults;
const legacyInterceptorReqResOrdering =
transitional && transitional.legacyInterceptorReqResOrdering;
if (legacyInterceptorReqResOrdering) {
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
} else {
requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
}
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift(...requestInterceptorChain);
chain.push(...responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig$1(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
};
// Provide aliases for supported request methods
utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios$1.prototype[method] = function (url, config) {
return this.request(
mergeConfig$1(config || {}, {
method,
url,
data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined,
})
);
};
});
utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(
mergeConfig$1(config || {}, {
method,
headers: isForm
? {
'Content-Type': 'multipart/form-data',
}
: {},
url,
data,
})
);
};
}
Axios$1.prototype[method] = generateHTTPMethod();
// QUERY is a safe/idempotent read method; multipart form bodies don't fit
// its semantics, so no queryForm shorthand is generated.
if (method !== 'query') {
Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true);
}
});
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
let CancelToken$1 = class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then((cancel) => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = (onfulfilled) => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise((resolve) => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError$1(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
toAbortSignal() {
const controller = new AbortController();
const abort = (err) => {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel,
};
}
};
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* const args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
function spread$1(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
function isAxiosError$1(payload) {
return utils$1.isObject(payload) && payload.isAxiosError === true;
}
const HttpStatusCode$1 = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
WebServerIsDown: 521,
ConnectionTimedOut: 522,
OriginIsUnreachable: 523,
TimeoutOccurred: 524,
SslHandshakeFailed: 525,
InvalidSslCertificate: 526,
};
Object.entries(HttpStatusCode$1).forEach(([key, value]) => {
HttpStatusCode$1[value] = key;
});
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios$1(defaultConfig);
const instance = bind(Axios$1.prototype.request, context);
// Copy axios.prototype to instance
utils$1.extend(instance, Axios$1.prototype, context, { allOwnKeys: true });
// Copy context to instance
utils$1.extend(instance, context, null, { allOwnKeys: true });
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig$1(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios$1;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError$1;
axios.CancelToken = CancelToken$1;
axios.isCancel = isCancel$1;
axios.VERSION = VERSION$1;
axios.toFormData = toFormData$1;
// Expose AxiosError class
axios.AxiosError = AxiosError$1;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread$1;
// Expose isAxiosError
axios.isAxiosError = isAxiosError$1;
// Expose mergeConfig
axios.mergeConfig = mergeConfig$1;
axios.AxiosHeaders = AxiosHeaders$1;
axios.formToJSON = (thing) => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode$1;
axios.default = axios;
// This module is intended to unwrap Axios default export as named.
// Keep top-level export same with static properties
// so that it can keep same with es module or cjs
const {
Axios,
AxiosError,
CanceledError,
isCancel,
CancelToken,
VERSION,
all,
Cancel,
isAxiosError,
spread,
toFormData,
AxiosHeaders,
HttpStatusCode,
formToJSON,
getAdapter,
mergeConfig,
create,
} = axios;
export { Axios, AxiosError, AxiosHeaders, Cancel, CancelToken, CanceledError, HttpStatusCode, VERSION, all, create, axios as default, formToJSON, getAdapter, isAxiosError, isCancel, mergeConfig, spread, toFormData };
//# sourceMappingURL=axios.js.map
+3
View File
File diff suppressed because one or more lines are too long
+1
View File
File diff suppressed because one or more lines are too long
+5996
View File
@@ -0,0 +1,5996 @@
/*! Axios v1.18.1 Copyright (c) 2026 Matt Zabriskie and contributors */
'use strict';
var FormData$1 = require('form-data');
var crypto = require('crypto');
var url = require('url');
var HttpsProxyAgent = require('https-proxy-agent');
var http = require('http');
var https = require('https');
var http2 = require('http2');
var util = require('util');
var path = require('path');
var followRedirects = require('follow-redirects');
var zlib = require('zlib');
var stream = require('stream');
var events = require('events');
/**
* Create a bound version of a function with a specified `this` context
*
* @param {Function} fn - The function to bind
* @param {*} thisArg - The value to be passed as the `this` parameter
* @returns {Function} A new function that will call the original function with the specified `this` context
*/
function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
// utils is a library of generic helper functions non-specific to axios
const {
toString
} = Object.prototype;
const {
getPrototypeOf
} = Object;
const {
iterator,
toStringTag
} = Symbol;
/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (({
hasOwnProperty
}) => (obj, prop) => hasOwnProperty.call(obj, prop))(Object.prototype);
/**
* Walk the prototype chain (excluding the shared Object.prototype) looking for
* an own `prop`. This distinguishes genuine own/inherited members — including
* class accessors and template prototypes — from members injected via
* Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
* live on Object.prototype itself and are therefore never matched.
*
* @param {*} thing The value whose chain to inspect
* @param {string|symbol} prop The property key to look for
*
* @returns {boolean} True when `prop` is owned below Object.prototype
*/
const hasOwnInPrototypeChain = (thing, prop) => {
let obj = thing;
const seen = [];
while (obj != null && obj !== Object.prototype) {
if (seen.indexOf(obj) !== -1) {
return false;
}
seen.push(obj);
if (hasOwnProperty(obj, prop)) {
return true;
}
obj = getPrototypeOf(obj);
}
return false;
};
/**
* Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
* properties and members inherited from a non-Object.prototype source (a class
* instance or template object) are honored; a value reachable only through a
* polluted Object.prototype is ignored and `undefined` is returned.
*
* @param {*} obj The source object
* @param {string|symbol} prop The property key to read
*
* @returns {*} The resolved value, or undefined when unsafe/absent
*/
const getSafeProp = (obj, prop) => obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
const kindOf = (cache => thing => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));
const kindOfTest = type => {
type = type.toLowerCase();
return thing => kindOf(thing) === type;
};
const typeOfTest = type => thing => typeof thing === type;
/**
* Determine if a value is a non-null object
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
const {
isArray
} = Array;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction$1(val.constructor.isBuffer) && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
let result;
if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && isArrayBuffer(val.buffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction$1 = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
const isObject = thing => thing !== null && typeof thing === 'object';
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = thing => thing === true || thing === false;
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
const isPlainObject = val => {
if (!isObject(val)) {
return false;
}
const prototype = getPrototypeOf(val);
return (prototype === null || prototype === Object.prototype || getPrototypeOf(prototype) === null) &&
// Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
// Symbol.iterator as evidence the value is a tagged/iterable type rather
// than a plain object, while ignoring keys injected onto Object.prototype.
!hasOwnInPrototypeChain(val, toStringTag) && !hasOwnInPrototypeChain(val, iterator);
};
/**
* Determine if a value is an empty object (safely handles Buffers)
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an empty object, otherwise false
*/
const isEmptyObject = val => {
// Early return for non-objects or Buffers to prevent RangeError
if (!isObject(val) || isBuffer(val)) {
return false;
}
try {
return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
} catch (e) {
// Fallback for any other objects that might cause RangeError with Object.keys()
return false;
}
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFile = kindOfTest('File');
/**
* Determine if a value is a React Native Blob
* React Native "blob": an object with a `uri` attribute. Optionally, it can
* also have a `name` and `type` attribute to specify filename and content type
*
* @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
*
* @param {*} value The value to test
*
* @returns {boolean} True if value is a React Native Blob, otherwise false
*/
const isReactNativeBlob = value => {
return !!(value && typeof value.uri !== 'undefined');
};
/**
* Determine if environment is React Native
* ReactNative `FormData` has a non-standard `getParts()` method
*
* @param {*} formData The formData to test
*
* @returns {boolean} True if environment is React Native, otherwise false
*/
const isReactNative = formData => formData && typeof formData.getParts !== 'undefined';
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a FileList, otherwise false
*/
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
const isStream = val => isObject(val) && isFunction$1(val.pipe);
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
function getGlobal() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
return {};
}
const G = getGlobal();
const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
const isFormData = thing => {
if (!thing) return false;
if (FormDataCtor && thing instanceof FormDataCtor) return true;
// Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
const proto = getPrototypeOf(thing);
if (!proto || proto === Object.prototype) return false;
if (!isFunction$1(thing.append)) return false;
const kind = kindOf(thing);
return kind === 'formdata' ||
// detect form-data instance
kind === 'object' && isFunction$1(thing.toString) && thing.toString() === '[object FormData]';
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
const [isReadableStream, isRequest, isResponse, isHeaders] = ['ReadableStream', 'Request', 'Response', 'Headers'].map(kindOfTest);
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
const trim = str => {
return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array<unknown>} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn, {
allOwnKeys = false
} = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Buffer check
if (isBuffer(obj)) {
return;
}
// Iterate over object keys
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
/**
* Finds a key in an object, case-insensitive, returning the actual key name.
* Returns null if the object is a Buffer or if no match is found.
*
* @param {Object} obj - The object to search.
* @param {string} key - The key to find (case-insensitive).
* @returns {?string} The actual key name if found, otherwise null.
*/
function findKey(obj, key) {
if (isBuffer(obj)) {
return null;
}
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
/*eslint no-undef:0*/
if (typeof globalThis !== 'undefined') return globalThis;
return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
})();
const isContextDefined = context => !isUndefined(context) && context !== _global;
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* const result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge(...objs) {
const {
caseless,
skipUndefined
} = isContextDefined(this) && this || {};
const result = {};
const assignValue = (val, key) => {
// Skip dangerous property names to prevent prototype pollution
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return;
}
// findKey lowercases the key, so caseless lookup only applies to strings —
// symbol keys are identity-matched.
const targetKey = caseless && typeof key === 'string' && findKey(result, key) || key;
// Read via own-prop only — a bare `result[targetKey]` walks the prototype
// chain, so a polluted Object.prototype value could surface here and get
// copied into the merged result.
const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
if (isPlainObject(existing) && isPlainObject(val)) {
result[targetKey] = merge(existing, val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else if (!skipUndefined || !isUndefined(val)) {
result[targetKey] = val;
}
};
for (let i = 0, l = objs.length; i < l; i++) {
const source = objs[i];
if (!source || isBuffer(source)) {
continue;
}
forEach(source, assignValue);
if (typeof source !== 'object' || isArray(source)) {
continue;
}
const symbols = Object.getOwnPropertySymbols(source);
for (let j = 0; j < symbols.length; j++) {
const symbol = symbols[j];
if (propertyIsEnumerable.call(source, symbol)) {
assignValue(source[symbol], symbol);
}
}
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys]
* @returns {Object} The resulting value of object a
*/
const extend = (a, b, thisArg, {
allOwnKeys
} = {}) => {
forEach(b, (val, key) => {
if (thisArg && isFunction$1(val)) {
Object.defineProperty(a, key, {
// Null-proto descriptor so a polluted Object.prototype.get cannot
// hijack defineProperty's accessor-vs-data resolution.
__proto__: null,
value: bind(val, thisArg),
writable: true,
enumerable: true,
configurable: true
});
} else {
Object.defineProperty(a, key, {
__proto__: null,
value: val,
writable: true,
enumerable: true,
configurable: true
});
}
}, {
allOwnKeys
});
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
const stripBOM = content => {
if (content.charCodeAt(0) === 0xfeff) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
const inherits = (constructor, superConstructor, props, descriptors) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
Object.defineProperty(constructor.prototype, 'constructor', {
__proto__: null,
value: constructor,
writable: true,
enumerable: false,
configurable: true
});
Object.defineProperty(constructor, 'super', {
__proto__: null,
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
const toArray = thing => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
const isTypedArray = (TypedArray => {
// eslint-disable-next-line func-names
return thing => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object<any, any>} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
const forEachEntry = (obj, fn) => {
const generator = obj && obj[iterator];
const _iterator = generator.call(obj);
let result;
while ((result = _iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array<boolean>}
*/
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = str => {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
});
};
const {
propertyIsEnumerable
} = Object.prototype;
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
const reduceDescriptors = (obj, reducer) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
const freezeMethods = obj => {
reduceDescriptors(obj, (descriptor, name) => {
// skip restricted props in strict mode
if (isFunction$1(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
return false;
}
const value = obj[name];
if (!isFunction$1(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
/**
* Converts an array or a delimited string into an object set with values as keys and true as values.
* Useful for fast membership checks.
*
* @param {Array|string} arrayOrString - The array or string to convert.
* @param {string} delimiter - The delimiter to use if input is a string.
* @returns {Object} An object with keys from the array or string, values set to true.
*/
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = arr => {
arr.forEach(value => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop = () => {};
const toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite(value = +value) ? value : defaultValue;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(thing && isFunction$1(thing.append) && thing[toStringTag] === 'FormData' && thing[iterator]);
}
/**
* Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
*
* @param {Object} obj - The object to convert.
* @returns {Object} The JSON-compatible object.
*/
const toJSONObject = obj => {
const visited = new WeakSet();
const visit = source => {
if (isObject(source)) {
if (visited.has(source)) {
return;
}
//Buffer check
if (isBuffer(source)) {
return source;
}
if (!('toJSON' in source)) {
// add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
visited.add(source);
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
visited.delete(source);
return target;
}
}
return source;
};
return visit(obj);
};
/**
* Determines if a value is an async function.
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is an async function, otherwise false.
*/
const isAsyncFn = kindOfTest('AsyncFunction');
/**
* Determines if a value is thenable (has then and catch methods).
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is thenable, otherwise false.
*/
const isThenable = thing => thing && (isObject(thing) || isFunction$1(thing)) && isFunction$1(thing.then) && isFunction$1(thing.catch);
// original code
// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
/**
* Provides a cross-platform setImmediate implementation.
* Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
*
* @param {boolean} setImmediateSupported - Whether setImmediate is supported.
* @param {boolean} postMessageSupported - Whether postMessage is supported.
* @returns {Function} A function to schedule a callback asynchronously.
*/
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported ? ((token, callbacks) => {
_global.addEventListener('message', ({
source,
data
}) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
}, false);
return cb => {
callbacks.push(cb);
_global.postMessage(token, '*');
};
})(`axios@${Math.random()}`, []) : cb => setTimeout(cb);
})(typeof setImmediate === 'function', isFunction$1(_global.postMessage));
/**
* Schedules a microtask or asynchronous callback as soon as possible.
* Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
*
* @type {Function}
*/
const asap = typeof queueMicrotask !== 'undefined' ? queueMicrotask.bind(_global) : typeof process !== 'undefined' && process.nextTick || _setImmediate;
// *********************
const isIterable = thing => thing != null && isFunction$1(thing[iterator]);
/**
* Determine if a value is iterable via an iterator that is NOT sourced solely
* from a polluted Object.prototype. Use this instead of `isIterable` whenever
* the iterable comes from untrusted input (e.g. user-supplied header sources),
* so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
* into an attacker-controlled entries iterator.
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value has a non-polluted iterator
*/
const isSafeIterable = thing => thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
var utils$1 = {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isEmptyObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isReactNativeBlob,
isReactNative,
isBlob,
isRegExp,
isFunction: isFunction$1,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty,
// an alias to avoid ESLint no-prototype-builtins detection
hasOwnInPrototypeChain,
getSafeProp,
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap,
isIterable,
isSafeIterable
};
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils$1.toObjectSet(['age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent']);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
var parseHeaders = rawHeaders => {
const parsed = {};
let key;
let val;
let i;
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || parsed[key] && ignoreDuplicateOf[key]) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
function trimSPorHTAB(str) {
let start = 0;
let end = str.length;
while (start < end) {
const code = str.charCodeAt(start);
if (code !== 0x09 && code !== 0x20) {
break;
}
start += 1;
}
while (end > start) {
const code = str.charCodeAt(end - 1);
if (code !== 0x09 && code !== 0x20) {
break;
}
end -= 1;
}
return start === 0 && end === str.length ? str : str.slice(start, end);
}
// The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
// eslint-disable-next-line no-control-regex
const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
// eslint-disable-next-line no-control-regex
const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
function sanitizeValue(value, invalidChars) {
if (utils$1.isArray(value)) {
return value.map(item => sanitizeValue(item, invalidChars));
}
return trimSPorHTAB(String(value).replace(invalidChars, ''));
}
const sanitizeHeaderValue = value => sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
const sanitizeByteStringHeaderValue = value => sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
function toByteStringHeaderObject(headers) {
const byteStringHeaders = Object.create(null);
utils$1.forEach(headers.toJSON(), (value, header) => {
byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
});
return byteStringHeaders;
}
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils$1.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while (match = tokensRE.exec(str)) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = str => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils$1.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils$1.isString(value)) return;
if (utils$1.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils$1.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils$1.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(methodName => {
Object.defineProperty(obj, methodName + accessorName, {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: function (arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
return;
}
const key = utils$1.findKey(self, lHeader);
if (!key || self[key] === undefined || _rewrite === true || _rewrite === undefined && self[key] !== false) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) => utils$1.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils$1.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if (utils$1.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils$1.isObject(header) && utils$1.isSafeIterable(header)) {
let obj = Object.create(null),
dest,
key;
for (const entry of header) {
if (!utils$1.isArray(entry)) {
throw new TypeError('Object iterator must return a key-value pair');
}
key = entry[0];
if (utils$1.hasOwnProp(obj, key)) {
dest = obj[key];
obj[key] = utils$1.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
} else {
obj[key] = entry[1];
}
}
setHeaders(obj, valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils$1.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils$1.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils$1.findKey(this, header);
return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils$1.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils$1.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils$1.forEach(this, (value, header) => {
const key = utils$1.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils$1.forEach(this, (value, header) => {
value != null && value !== false && (obj[header] = asStrings && utils$1.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
}
getSetCookie() {
return this.get('set-cookie') || [];
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach(target => computed.set(target));
return computed;
}
static accessor(header) {
const internals = this[$internals] = this[$internals] = {
accessors: {}
};
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils$1.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']);
// reserved names hotfix
utils$1.reduceDescriptors(AxiosHeaders.prototype, ({
value
}, key) => {
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
}
};
});
utils$1.freezeMethods(AxiosHeaders);
const REDACTED = '[REDACTED ****]';
function hasOwnOrPrototypeToJSON(source) {
if (utils$1.hasOwnProp(source, 'toJSON')) {
return true;
}
let prototype = Object.getPrototypeOf(source);
while (prototype && prototype !== Object.prototype) {
if (utils$1.hasOwnProp(prototype, 'toJSON')) {
return true;
}
prototype = Object.getPrototypeOf(prototype);
}
return false;
}
// Build a plain-object snapshot of `config` and replace the value of any key
// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
// and AxiosHeaders, and short-circuits on circular references.
function redactConfig(config, redactKeys) {
const lowerKeys = new Set(redactKeys.map(k => String(k).toLowerCase()));
const seen = [];
const visit = source => {
if (source === null || typeof source !== 'object') return source;
if (utils$1.isBuffer(source)) return source;
if (seen.indexOf(source) !== -1) return undefined;
if (source instanceof AxiosHeaders) {
source = source.toJSON();
}
seen.push(source);
let result;
if (utils$1.isArray(source)) {
result = [];
source.forEach((v, i) => {
const reducedValue = visit(v);
if (!utils$1.isUndefined(reducedValue)) {
result[i] = reducedValue;
}
});
} else {
if (!utils$1.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
seen.pop();
return source;
}
result = Object.create(null);
for (const [key, value] of Object.entries(source)) {
const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
if (!utils$1.isUndefined(reducedValue)) {
result[key] = reducedValue;
}
}
}
seen.pop();
return result;
};
return visit(config);
}
class AxiosError extends Error {
static from(error, code, config, request, response, customProps) {
const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
// Match native `Error` `cause` semantics: non-enumerable. The wrapped
// error often carries circular internals (sockets, requests, agents), so
// an enumerable `cause` makes structured loggers (pino/winston) and any
// own-property walk throw "Converting circular structure to JSON".
// Regression from #6982; see #7205. `__proto__: null` mirrors the
// `message` descriptor below (prototype-pollution-safe descriptor).
Object.defineProperty(axiosError, 'cause', {
__proto__: null,
value: error,
writable: true,
enumerable: false,
configurable: true
});
axiosError.name = error.name;
// Preserve status from the original error if not already set from response
if (error.status != null && axiosError.status == null) {
axiosError.status = error.status;
}
customProps && Object.assign(axiosError, customProps);
return axiosError;
}
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
constructor(message, code, config, request, response) {
super(message);
// Make message enumerable to maintain backward compatibility
// The native Error constructor sets message as non-enumerable,
// but axios < v1.13.3 had it as enumerable
Object.defineProperty(this, 'message', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: message,
enumerable: true,
writable: true,
configurable: true
});
this.name = 'AxiosError';
this.isAxiosError = true;
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
if (response) {
this.response = response;
this.status = response.status;
}
}
toJSON() {
// Opt-in redaction: when the request config carries a `redact` array, the
// value of any matching key (case-insensitive, at any depth) is replaced
// with REDACTED in the serialized snapshot. Undefined or empty leaves the
// existing serialization behavior unchanged.
const config = this.config;
const redactKeys = config && utils$1.hasOwnProp(config, 'redact') ? config.redact : undefined;
const serializedConfig = utils$1.isArray(redactKeys) && redactKeys.length > 0 ? redactConfig(config, redactKeys) : utils$1.toJSONObject(config);
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: serializedConfig,
code: this.code,
status: this.status
};
}
}
// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
AxiosError.ECONNABORTED = 'ECONNABORTED';
AxiosError.ETIMEDOUT = 'ETIMEDOUT';
AxiosError.ECONNREFUSED = 'ECONNREFUSED';
AxiosError.ERR_NETWORK = 'ERR_NETWORK';
AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
AxiosError.ERR_CANCELED = 'ERR_CANCELED';
AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
// Default nesting limit shared with the inverse transform (formDataToJSON) so
// the FormData <-> JSON round-trip stays symmetric.
const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils$1.isPlainObject(thing) || utils$1.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path.concat(key).map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
}).join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array<any>} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils$1.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object<any, any>} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object<string, any>} options
*
* @returns
*/
function toFormData(obj, formData, options) {
if (!utils$1.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (FormData$1 || FormData)();
// eslint-disable-next-line no-param-reassign
options = utils$1.toFlatObject(options, {
metaTokens: true,
dots: false,
indexes: false
}, false, function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils$1.isUndefined(source[option]);
});
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
const useBlob = _Blob && utils$1.isSpecCompliantForm(formData);
const stack = [];
if (!utils$1.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils$1.isDate(value)) {
return value.toISOString();
}
if (utils$1.isBoolean(value)) {
return value.toString();
}
if (!useBlob && utils$1.isBlob(value)) {
throw new AxiosError('Blob is not supported. Use a Buffer instead.');
}
if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) {
if (useBlob && typeof _Blob === 'function') {
return new _Blob([value]);
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(value);
}
throw new AxiosError('Blob is not supported. Use a Buffer instead.', AxiosError.ERR_NOT_SUPPORT);
}
return value;
}
function throwIfMaxDepthExceeded(depth) {
if (depth > maxDepth) {
throw new AxiosError('Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
}
}
function stringifyWithDepthLimit(value, depth) {
if (maxDepth === Infinity) {
return JSON.stringify(value);
}
const ancestors = [];
return JSON.stringify(value, function limitDepth(_key, currentValue) {
if (!utils$1.isObject(currentValue)) {
return currentValue;
}
while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
ancestors.pop();
}
ancestors.push(currentValue);
throwIfMaxDepthExceeded(depth + ancestors.length - 1);
return currentValue;
});
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array<String|Number>} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
let arr = value;
if (utils$1.isReactNative(formData) && utils$1.isReactNativeBlob(value)) {
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
if (value && !path && typeof value === 'object') {
if (utils$1.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = stringifyWithDepthLimit(value, 1);
} else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value))) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils$1.isUndefined(el) || el === null) && formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + '[]', convertValue(el));
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path, depth = 0) {
if (utils$1.isUndefined(value)) return;
throwIfMaxDepthExceeded(depth);
if (stack.indexOf(value) !== -1) {
throw new Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils$1.forEach(value, function each(el, key) {
const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers);
if (result === true) {
build(el, path ? path.concat(key) : [key], depth + 1);
}
});
stack.pop();
}
if (!utils$1.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode$1(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+'
};
return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder ? value => encoder.call(this, value, encode$1) : encode$1;
return this._pairs.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '').join('&');
};
/**
* It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
* their plain counterparts (`:`, `$`, `,`, `+`).
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
function encode(val) {
return encodeURIComponent(val).replace(/%3A/gi, ':').replace(/%24/g, '$').replace(/%2C/gi, ',').replace(/%20/g, '+');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?(object|Function)} options
*
* @returns {string} The formatted url
*/
function buildURL(url, params, options) {
if (!params) {
return url;
}
url = url || '';
const _options = utils$1.isFunction(options) ? {
serialize: options
} : options;
// Read serializer options pollution-safely: own properties and methods on a
// class/template prototype are honored, but values injected onto a polluted
// Object.prototype are ignored.
const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
const serializeFn = utils$1.getSafeProp(_options, 'serialize');
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, _options);
} else {
serializedParams = utils$1.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams(params, _options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
* @param {Object} options The options for the interceptor, synchronous and runWhen
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {void}
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils$1.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
var transitionalDefaults = {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false,
legacyInterceptorReqResOrdering: true,
advertiseZstdAcceptEncoding: false,
validateStatusUndefinedResolves: true
};
var URLSearchParams = url.URLSearchParams;
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
const DIGIT = '0123456789';
const ALPHABET = {
DIGIT,
ALPHA,
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT
};
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
let str = '';
const {
length
} = alphabet;
const randomValues = new Uint32Array(size);
crypto.randomFillSync(randomValues);
for (let i = 0; i < size; i++) {
str += alphabet[randomValues[i] % length];
}
return str;
};
var platform$1 = {
isNode: true,
classes: {
URLSearchParams,
FormData: FormData$1,
Blob: typeof Blob !== 'undefined' && Blob || null
},
ALPHABET,
generateString,
protocols: ['http', 'https', 'file', 'data']
};
const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
const _navigator = typeof navigator === 'object' && navigator || undefined;
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
const hasStandardBrowserEnv = hasBrowserEnv && (!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
const hasStandardBrowserWebWorkerEnv = (() => {
return typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope && typeof self.importScripts === 'function';
})();
const origin = hasBrowserEnv && window.location.href || 'http://localhost';
var utils = /*#__PURE__*/Object.freeze({
__proto__: null,
hasBrowserEnv: hasBrowserEnv,
hasStandardBrowserEnv: hasStandardBrowserEnv,
hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv,
navigator: _navigator,
origin: origin
});
var platform = {
...utils,
...platform$1
};
function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), {
visitor: function (value, key, path, helpers) {
if (platform.isNode && utils$1.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
},
...options
});
}
const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
function throwIfDepthExceeded(index) {
if (index > MAX_DEPTH) {
throw new AxiosError('FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH, AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED);
}
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
const path = [];
const pattern = /\w+|\[(\w*)]/g;
let match;
while ((match = pattern.exec(name)) !== null) {
throwIfDepthExceeded(path.length);
path.push(match[0] === '[]' ? '' : match[1] || match[0]);
}
return path;
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
throwIfDepthExceeded(index);
let name = path[index++];
if (name === '__proto__') return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils$1.isArray(target) ? target.length : name;
if (isLast) {
if (utils$1.hasOwnProp(target, name)) {
target[name] = utils$1.isArray(target[name]) ? target[name].concat(value) : [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!utils$1.hasOwnProp(target, name) || !utils$1.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils$1.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils$1.isFormData(formData) && utils$1.isFunction(formData.entries)) {
const obj = {};
utils$1.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
const own = (obj, key) => obj != null && utils$1.hasOwnProp(obj, key) ? obj[key] : undefined;
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils$1.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils$1.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils$1.isObject(data);
if (isObjectPayload && utils$1.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils$1.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (utils$1.isArrayBuffer(data) || utils$1.isBuffer(data) || utils$1.isStream(data) || utils$1.isFile(data) || utils$1.isBlob(data) || utils$1.isReadableStream(data)) {
return data;
}
if (utils$1.isArrayBufferView(data)) {
return data.buffer;
}
if (utils$1.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
const formSerializer = own(this, 'formSerializer');
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, formSerializer).toString();
}
if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
const env = own(this, 'env');
const _FormData = env && env.FormData;
return toFormData(isFileList ? {
'files[]': data
} : data, _FormData && new _FormData(), formSerializer);
}
}
if (isObjectPayload || hasJSONContentType) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
const transitional = own(this, 'transitional') || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const responseType = own(this, 'responseType');
const JSONRequested = responseType === 'json';
if (utils$1.isResponse(data) || utils$1.isReadableStream(data)) {
return data;
}
if (data && utils$1.isString(data) && (forcedJSONParsing && !responseType || JSONRequested)) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data, own(this, 'parseReviver'));
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
}
throw e;
}
}
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
Accept: 'application/json, text/plain, */*',
'Content-Type': undefined
}
}
};
utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], method => {
defaults.headers[method] = {};
});
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders.from(context.headers);
let data = context.data;
utils$1.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
function isCancel(value) {
return !!(value && value.__CANCEL__);
}
class CanceledError extends AxiosError {
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
constructor(message, config, request) {
super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
this.name = 'CanceledError';
this.__CANCEL__ = true;
}
}
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError('Request failed with status code ' + response.status, response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE, response.config, response.request, response));
}
}
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
if (typeof url !== 'string') {
return false;
}
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
function combineURLs(baseURL, relativeURL) {
return relativeURL ? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL;
}
const malformedHttpProtocol = /^https?:(?!\/\/)/i;
const httpProtocolControlCharacters = /[\t\n\r]/g;
function stripLeadingC0ControlOrSpace(url) {
let i = 0;
while (i < url.length && url.charCodeAt(i) <= 0x20) {
i++;
}
return url.slice(i);
}
function normalizeURLForProtocolCheck(url) {
return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
}
function assertValidHttpProtocolURL(url, config) {
if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
throw new AxiosError('Invalid URL: missing "//" after protocol', AxiosError.ERR_INVALID_URL, config);
}
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
assertValidHttpProtocolURL(requestedURL, config);
let isRelativeUrl = !isAbsoluteURL(requestedURL);
if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
assertValidHttpProtocolURL(baseURL, config);
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
var DEFAULT_PORTS$1 = {
ftp: 21,
gopher: 70,
http: 80,
https: 443,
ws: 80,
wss: 443
};
function parseUrl(urlString) {
try {
return new URL(urlString);
} catch {
return null;
}
}
/**
* @param {string|object|URL} url - The URL as a string or URL instance, or a
* compatible object (such as the result from legacy url.parse).
* @return {string} The URL of the proxy that should handle the request to the
* given URL. If no proxy is set, this will be an empty string.
*/
function getProxyForUrl(url) {
var parsedUrl = (typeof url === 'string' ? parseUrl(url) : url) || {};
var proto = parsedUrl.protocol;
var hostname = parsedUrl.host;
var port = parsedUrl.port;
if (typeof hostname !== 'string' || !hostname || typeof proto !== 'string') {
return ''; // Don't proxy URLs without a valid scheme or host.
}
proto = proto.split(':', 1)[0];
// Stripping ports in this way instead of using parsedUrl.hostname to make
// sure that the brackets around IPv6 addresses are kept.
hostname = hostname.replace(/:\d*$/, '');
port = parseInt(port) || DEFAULT_PORTS$1[proto] || 0;
if (!shouldProxy(hostname, port)) {
return ''; // Don't proxy URLs that match NO_PROXY.
}
var proxy = getEnv(proto + '_proxy') || getEnv('all_proxy');
if (proxy && proxy.indexOf('://') === -1) {
// Missing scheme in proxy, default to the requested URL's scheme.
proxy = proto + '://' + proxy;
}
return proxy;
}
/**
* Determines whether a given URL should be proxied.
*
* @param {string} hostname - The host name of the URL.
* @param {number} port - The effective port of the URL.
* @returns {boolean} Whether the given URL should be proxied.
* @private
*/
function shouldProxy(hostname, port) {
var NO_PROXY = getEnv('no_proxy').toLowerCase();
if (!NO_PROXY) {
return true; // Always proxy if NO_PROXY is not set.
}
if (NO_PROXY === '*') {
return false; // Never proxy if wildcard is set.
}
return NO_PROXY.split(/[,\s]/).every(function (proxy) {
if (!proxy) {
return true; // Skip zero-length hosts.
}
var parsedProxy = proxy.match(/^(.+):(\d+)$/);
var parsedProxyHostname = parsedProxy ? parsedProxy[1] : proxy;
var parsedProxyPort = parsedProxy ? parseInt(parsedProxy[2]) : 0;
if (parsedProxyPort && parsedProxyPort !== port) {
return true; // Skip if ports don't match.
}
if (!/^[.*]/.test(parsedProxyHostname)) {
// No wildcards, so stop proxying if there is an exact match.
return hostname !== parsedProxyHostname;
}
if (parsedProxyHostname.charAt(0) === '*') {
// Remove leading wildcard.
parsedProxyHostname = parsedProxyHostname.slice(1);
}
// Stop proxying if the hostname ends with the no_proxy host.
return !hostname.endsWith(parsedProxyHostname);
});
}
/**
* Get the value for an environment variable.
*
* @param {string} key - The name of the environment variable.
* @return {string} The value of the environment variable.
* @private
*/
function getEnv(key) {
return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
}
const VERSION = "1.18.1";
function parseProtocol(url) {
const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
return match && match[1] || '';
}
// RFC 2397: data:[<mediatype>][;base64],<data>
// mediatype = type/subtype followed by optional ;name=value parameters
const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
/**
* Parse data uri to a Buffer or Blob
*
* @param {String} uri
* @param {?Boolean} asBlob
* @param {?Object} options
* @param {?Function} options.Blob
*
* @returns {Buffer|Blob}
*/
function fromDataURI(uri, asBlob, options) {
const _Blob = options && options.Blob || platform.classes.Blob;
const protocol = parseProtocol(uri);
if (asBlob === undefined && _Blob) {
asBlob = true;
}
if (protocol === 'data') {
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
const match = DATA_URL_PATTERN.exec(uri);
if (!match) {
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
}
const type = match[1];
const params = match[2];
const encoding = match[3] ? 'base64' : 'utf8';
const body = match[4];
// RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
// Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
let mime = '';
if (type) {
mime = params ? type + params : type;
} else if (params) {
mime = 'text/plain' + params;
}
const buffer = encoding === 'base64' ? Buffer.from(body, 'base64') : Buffer.from(decodeURIComponent(body), encoding);
if (asBlob) {
if (!_Blob) {
throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
}
return new _Blob([buffer], {
type: mime
});
}
return buffer;
}
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
}
const kInternals = Symbol('internals');
class AxiosTransformStream extends stream.Transform {
constructor(options) {
options = utils$1.toFlatObject(options, {
maxRate: 0,
chunkSize: 64 * 1024,
minChunkSize: 100,
timeWindow: 500,
ticksRate: 2,
samplesCount: 15
}, null, (prop, source) => {
return !utils$1.isUndefined(source[prop]);
});
super({
readableHighWaterMark: options.chunkSize
});
const internals = this[kInternals] = {
timeWindow: options.timeWindow,
chunkSize: options.chunkSize,
maxRate: options.maxRate,
minChunkSize: options.minChunkSize,
bytesSeen: 0,
isCaptured: false,
notifiedBytesLoaded: 0,
ts: Date.now(),
bytes: 0,
onReadCallback: null
};
this.on('newListener', event => {
if (event === 'progress') {
if (!internals.isCaptured) {
internals.isCaptured = true;
}
}
});
}
_read(size) {
const internals = this[kInternals];
if (internals.onReadCallback) {
internals.onReadCallback();
}
return super._read(size);
}
_transform(chunk, encoding, callback) {
const internals = this[kInternals];
const maxRate = internals.maxRate;
const readableHighWaterMark = this.readableHighWaterMark;
const timeWindow = internals.timeWindow;
const divider = 1000 / timeWindow;
const bytesThreshold = maxRate / divider;
const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
const pushChunk = (_chunk, _callback) => {
const bytes = Buffer.byteLength(_chunk);
internals.bytesSeen += bytes;
internals.bytes += bytes;
internals.isCaptured && this.emit('progress', internals.bytesSeen);
if (this.push(_chunk)) {
process.nextTick(_callback);
} else {
internals.onReadCallback = () => {
internals.onReadCallback = null;
process.nextTick(_callback);
};
}
};
const transformChunk = (_chunk, _callback) => {
const chunkSize = Buffer.byteLength(_chunk);
let chunkRemainder = null;
let maxChunkSize = readableHighWaterMark;
let bytesLeft;
let passed = 0;
if (maxRate) {
const now = Date.now();
if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
internals.ts = now;
bytesLeft = bytesThreshold - internals.bytes;
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
passed = 0;
}
bytesLeft = bytesThreshold - internals.bytes;
}
if (maxRate) {
if (bytesLeft <= 0) {
// next time window
return setTimeout(() => {
_callback(null, _chunk);
}, timeWindow - passed);
}
if (bytesLeft < maxChunkSize) {
maxChunkSize = bytesLeft;
}
}
if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
chunkRemainder = _chunk.subarray(maxChunkSize);
_chunk = _chunk.subarray(0, maxChunkSize);
}
pushChunk(_chunk, chunkRemainder ? () => {
process.nextTick(_callback, null, chunkRemainder);
} : _callback);
};
transformChunk(chunk, function transformNextChunk(err, _chunk) {
if (err) {
return callback(err);
}
if (_chunk) {
transformChunk(_chunk, transformNextChunk);
} else {
callback(null);
}
});
}
}
const {
asyncIterator
} = Symbol;
const readBlob = async function* (blob) {
if (blob.stream) {
yield* blob.stream();
} else if (blob.arrayBuffer) {
yield await blob.arrayBuffer();
} else if (blob[asyncIterator]) {
yield* blob[asyncIterator]();
} else {
yield blob;
}
};
const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_';
const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder();
const CRLF = '\r\n';
const CRLF_BYTES = textEncoder.encode(CRLF);
const CRLF_BYTES_COUNT = 2;
class FormDataPart {
constructor(name, value) {
const {
escapeName
} = this.constructor;
const isStringValue = utils$1.isString(value);
let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''}${CRLF}`;
if (isStringValue) {
value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
} else {
const safeType = String(value.type || 'application/octet-stream').replace(/[\r\n]/g, '');
headers += `Content-Type: ${safeType}${CRLF}`;
}
this.headers = textEncoder.encode(headers + CRLF);
this.contentLength = isStringValue ? value.byteLength : value.size;
this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
this.name = name;
this.value = value;
}
async *encode() {
yield this.headers;
const {
value
} = this;
if (utils$1.isTypedArray(value)) {
yield value;
} else {
yield* readBlob(value);
}
yield CRLF_BYTES;
}
static escapeName(name) {
return String(name).replace(/[\r\n"]/g, match => ({
'\r': '%0D',
'\n': '%0A',
'"': '%22'
})[match]);
}
}
const formDataToStream = (form, headersHandler, options) => {
const {
tag = 'form-data-boundary',
size = 25,
boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET)
} = options || {};
if (!utils$1.isFormData(form)) {
throw new TypeError('FormData instance required');
}
if (boundary.length < 1 || boundary.length > 70) {
throw new Error('boundary must be 1-70 characters long');
}
const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF);
let contentLength = footerBytes.byteLength;
const parts = Array.from(form.entries()).map(([name, value]) => {
const part = new FormDataPart(name, value);
contentLength += part.size;
return part;
});
contentLength += boundaryBytes.byteLength * parts.length;
contentLength = utils$1.toFiniteNumber(contentLength);
const computedHeaders = {
'Content-Type': `multipart/form-data; boundary=${boundary}`
};
if (Number.isFinite(contentLength)) {
computedHeaders['Content-Length'] = contentLength;
}
headersHandler && headersHandler(computedHeaders);
return stream.Readable.from(async function* () {
for (const part of parts) {
yield boundaryBytes;
yield* part.encode();
}
yield footerBytes;
}());
};
class ZlibHeaderTransformStream extends stream.Transform {
__transform(chunk, encoding, callback) {
this.push(chunk);
callback();
}
_transform(chunk, encoding, callback) {
if (chunk.length !== 0) {
this._transform = this.__transform;
// Add Default Compression headers if no zlib headers are present
if (chunk[0] !== 120) {
// Hex: 78
const header = Buffer.alloc(2);
header[0] = 120; // Hex: 78
header[1] = 156; // Hex: 9C
this.push(header, encoding);
}
}
this.__transform(chunk, encoding, callback);
}
}
class Http2Sessions {
constructor() {
this.sessions = Object.create(null);
}
getSession(authority, options) {
options = Object.assign({
sessionTimeout: 1000
}, options);
let authoritySessions = this.sessions[authority];
if (authoritySessions) {
let len = authoritySessions.length;
for (let i = 0; i < len; i++) {
const [sessionHandle, sessionOptions] = authoritySessions[i];
if (!sessionHandle.destroyed && !sessionHandle.closed && util.isDeepStrictEqual(sessionOptions, options)) {
return sessionHandle;
}
}
}
const session = http2.connect(authority, options);
let removed;
let timer;
const removeSession = () => {
if (removed) {
return;
}
removed = true;
if (timer) {
clearTimeout(timer);
timer = null;
}
let entries = authoritySessions,
len = entries.length,
i = len;
while (i--) {
if (entries[i][0] === session) {
if (len === 1) {
delete this.sessions[authority];
} else {
entries.splice(i, 1);
}
if (!session.closed) {
session.close();
}
return;
}
}
};
const originalRequestFn = session.request;
const {
sessionTimeout
} = options;
if (sessionTimeout != null) {
let streamsCount = 0;
session.request = function () {
const stream = originalRequestFn.apply(this, arguments);
streamsCount++;
if (timer) {
clearTimeout(timer);
timer = null;
}
stream.once('close', () => {
if (! --streamsCount) {
timer = setTimeout(() => {
timer = null;
removeSession();
}, sessionTimeout);
}
});
return stream;
};
}
session.once('close', removeSession);
let entry = [session, options];
authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry];
return session;
}
}
const callbackify = (fn, reducer) => {
return utils$1.isAsyncFn(fn) ? function (...args) {
const cb = args.pop();
fn.apply(this, args).then(value => {
try {
reducer ? cb(null, ...reducer(value)) : cb(null, value);
} catch (err) {
cb(err);
}
}, cb);
} : fn;
};
const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']);
const isIPv4Loopback = host => {
const parts = host.split('.');
if (parts.length !== 4) return false;
if (parts[0] !== '127') return false;
return parts.every(p => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
};
const isIPv6ZeroGroup = group => /^0{1,4}$/.test(group);
// The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host
// for outbound connections, so treat it as loopback-equivalent for NO_PROXY
// matching. 0.0.0.0 is covered by LOOPBACK_HOSTNAMES; this handles compressed
// and full IPv6 all-zero forms so both families bypass symmetrically.
const isIPv6Unspecified = host => {
if (host === '::') return true;
const compressionIndex = host.indexOf('::');
if (compressionIndex !== -1) {
if (compressionIndex !== host.lastIndexOf('::')) return false;
const left = host.slice(0, compressionIndex);
const right = host.slice(compressionIndex + 2);
const leftGroups = left ? left.split(':') : [];
const rightGroups = right ? right.split(':') : [];
const explicitGroups = leftGroups.length + rightGroups.length;
return explicitGroups < 8 && leftGroups.every(isIPv6ZeroGroup) && rightGroups.every(isIPv6ZeroGroup);
}
const groups = host.split(':');
return groups.length === 8 && groups.every(isIPv6ZeroGroup);
};
const isIPv6Loopback = host => {
// Collapse all-zero groups: any form of ::1 / 0:0:...:0:1
// First, strip any leading "::" by normalising with Set lookup of common forms,
// then fall back to structural check.
if (host === '::1') return true;
// Check IPv4-mapped IPv6 loopback: ::ffff:<v4-loopback> or ::ffff:<hex-v4-loopback>
// Node's URL parser normalises ::ffff:127.0.0.1 → ::ffff:7f00:1
const v4MappedDotted = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
if (v4MappedDotted) return isIPv4Loopback(v4MappedDotted[1]);
const v4MappedHex = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
if (v4MappedHex) {
const high = parseInt(v4MappedHex[1], 16);
// High 16 bits must start with 127 (0x7f) — i.e. 0x7f00..0x7fff
return high >= 0x7f00 && high <= 0x7fff;
}
// Full-form ::1 variants: any number of zero groups followed by trailing 1
// e.g. 0:0:0:0:0:0:0:1, 0000:...:0001
const groups = host.split(':');
if (groups.length === 8) {
for (let i = 0; i < 7; i++) {
if (!/^0+$/.test(groups[i])) return false;
}
return /^0*1$/.test(groups[7]);
}
return false;
};
const isLoopback = host => {
if (!host) return false;
if (LOOPBACK_HOSTNAMES.has(host)) return true;
if (isIPv4Loopback(host)) return true;
if (isIPv6Unspecified(host)) return true;
return isIPv6Loopback(host);
};
const DEFAULT_PORTS = {
http: 80,
https: 443,
ws: 80,
wss: 443,
ftp: 21
};
const parseNoProxyEntry = entry => {
let entryHost = entry;
let entryPort = 0;
if (entryHost.charAt(0) === '[') {
const bracketIndex = entryHost.indexOf(']');
if (bracketIndex !== -1) {
const host = entryHost.slice(1, bracketIndex);
const rest = entryHost.slice(bracketIndex + 1);
if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) {
entryPort = Number.parseInt(rest.slice(1), 10);
}
return [host, entryPort];
}
}
const firstColon = entryHost.indexOf(':');
const lastColon = entryHost.lastIndexOf(':');
if (firstColon !== -1 && firstColon === lastColon && /^\d+$/.test(entryHost.slice(lastColon + 1))) {
entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
entryHost = entryHost.slice(0, lastColon);
}
return [entryHost, entryPort];
};
// Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both
// sides of a NO_PROXY comparison see the same canonical address. Without this,
// `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/`
// (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa,
// allowing the proxy-bypass policy to be circumvented by using the alternate
// representation. Returns the input unchanged when not IPv4-mapped.
const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i;
const IPV4_MAPPED_HEX_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
const unmapIPv4MappedIPv6 = host => {
if (typeof host !== 'string' || host.indexOf(':') === -1) return host;
const dotted = host.match(IPV4_MAPPED_DOTTED_RE);
if (dotted) return dotted[1];
const hex = host.match(IPV4_MAPPED_HEX_RE);
if (hex) {
const high = parseInt(hex[1], 16);
const low = parseInt(hex[2], 16);
return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
}
return host;
};
const normalizeNoProxyHost = hostname => {
if (!hostname) {
return hostname;
}
if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
hostname = hostname.slice(1, -1);
}
return unmapIPv4MappedIPv6(hostname.replace(/\.+$/, ''));
};
function shouldBypassProxy(location) {
let parsed;
try {
parsed = new URL(location);
} catch (_err) {
return false;
}
const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase();
if (!noProxy) {
return false;
}
if (noProxy === '*') {
return true;
}
const port = Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0;
const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
return noProxy.split(/[\s,]+/).some(entry => {
if (!entry) {
return false;
}
let [entryHost, entryPort] = parseNoProxyEntry(entry);
entryHost = normalizeNoProxyHost(entryHost);
if (!entryHost) {
return false;
}
if (entryPort && entryPort !== port) {
return false;
}
if (entryHost.charAt(0) === '*') {
entryHost = entryHost.slice(1);
}
if (entryHost.charAt(0) === '.') {
return hostname.endsWith(entryHost);
}
return hostname === entryHost || isLoopback(hostname) && isLoopback(entryHost);
});
}
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
};
}
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1000 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn(...args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
return [throttled, flush];
}
const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle(e => {
if (!e || typeof e.loaded !== 'number') {
return;
}
const rawLoaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
const progressBytes = Math.max(0, loaded - bytesNotified);
const rate = _speedometer(progressBytes);
bytesNotified = Math.max(bytesNotified, loaded);
const data = {
loaded,
total,
progress: total ? loaded / total : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null,
[isDownloadStream ? 'download' : 'upload']: true
};
listener(data);
}, freq);
};
const progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [loaded => throttled[0]({
lengthComputable,
total,
loaded
}), throttled[1]];
};
const asyncDecorator = fn => (...args) => utils$1.asap(() => fn(...args));
/**
* Estimate decoded byte length of a data:// URL *without* allocating large buffers.
* - For base64: compute exact decoded size using length and padding;
* handle %XX at the character-count level (no string allocation).
* - For non-base64: compute the exact percent-decoded UTF-8 byte length.
*
* @param {string} url
* @returns {number}
*/
const isHexDigit = charCode => charCode >= 48 && charCode <= 57 || charCode >= 65 && charCode <= 70 || charCode >= 97 && charCode <= 102;
const isPercentEncodedByte = (str, i, len) => i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
function estimateDataURLDecodedBytes(url) {
if (!url || typeof url !== 'string') return 0;
if (!url.startsWith('data:')) return 0;
const comma = url.indexOf(',');
if (comma < 0) return 0;
const meta = url.slice(5, comma);
const body = url.slice(comma + 1);
const isBase64 = /;base64/i.test(meta);
if (isBase64) {
let effectiveLen = body.length;
const len = body.length; // cache length
for (let i = 0; i < len; i++) {
if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
const a = body.charCodeAt(i + 1);
const b = body.charCodeAt(i + 2);
const isHex = isHexDigit(a) && isHexDigit(b);
if (isHex) {
effectiveLen -= 2;
i += 2;
}
}
}
let pad = 0;
let idx = len - 1;
const tailIsPct3D = j => j >= 2 && body.charCodeAt(j - 2) === 37 &&
// '%'
body.charCodeAt(j - 1) === 51 && (
// '3'
body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'
if (idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
idx--;
} else if (tailIsPct3D(idx)) {
pad++;
idx -= 3;
}
}
if (pad === 1 && idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
} else if (tailIsPct3D(idx)) {
pad++;
}
}
const groups = Math.floor(effectiveLen / 4);
const bytes = groups * 3 - (pad || 0);
return bytes > 0 ? bytes : 0;
}
// Compute UTF-8 byte length directly from UTF-16 code units without allocating
// a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
// Valid %XX triplets count as one decoded byte; this matches the bytes that
// decodeURIComponent(body) would produce before Buffer re-encodes the string.
let bytes = 0;
for (let i = 0, len = body.length; i < len; i++) {
const c = body.charCodeAt(i);
if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
bytes += 1;
i += 2;
} else if (c < 0x80) {
bytes += 1;
} else if (c < 0x800) {
bytes += 2;
} else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
const next = body.charCodeAt(i + 1);
if (next >= 0xdc00 && next <= 0xdfff) {
bytes += 4;
i++;
} else {
bytes += 3;
}
} else {
bytes += 3;
}
}
return bytes;
}
const zlibOptions = {
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH
};
const brotliOptions = {
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH
};
const zstdOptions = {
flush: zlib.constants.ZSTD_e_flush,
finishFlush: zlib.constants.ZSTD_e_flush
};
const isBrotliSupported = utils$1.isFunction(zlib.createBrotliDecompress);
const isZstdSupported = utils$1.isFunction(zlib.createZstdDecompress);
const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : '');
const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : '');
const {
http: httpFollow,
https: httpsFollow
} = followRedirects;
const isHttps = /https:?/;
const FORM_DATA_CONTENT_HEADERS$1 = ['content-type', 'content-length'];
function setFormDataHeaders$1(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders).forEach(([key, val]) => {
if (FORM_DATA_CONTENT_HEADERS$1.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
// Symbols used to bind a single 'error' listener to a pooled socket and track
// the request currently owning that socket across keep-alive reuse (issue #10780).
const kAxiosSocketListener = Symbol('axios.http.socketListener');
const kAxiosCurrentReq = Symbol('axios.http.currentReq');
// Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
// can strip them without clobbering a user-supplied agent that happens to be
// an HttpsProxyAgent.
const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
// Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
// through the same proxy reuse a single agent (and its socket pool). The
// keyspace is bounded by the set of distinct proxy configs the process uses,
// so unbounded growth is not a concern in practice.
const tunnelingAgentCache = new Map();
const tunnelingAgentCacheUser = new WeakMap();
// Minimum minor versions where Node's HTTP Agent supports native proxyEnv
// handling. Checking the selected agent below also covers startup modes such
// as NODE_OPTIONS=--use-env-proxy and --no-use-env-proxy precedence.
const NODE_NATIVE_ENV_PROXY_SUPPORT = {
22: 21,
24: 5
};
function isNodeNativeEnvProxySupported(nodeVersion = process.versions && process.versions.node) {
if (!nodeVersion) {
return false;
}
const [major, minor] = nodeVersion.split('.').map(part => Number(part));
if (!Number.isInteger(major) || !Number.isInteger(minor)) {
return false;
}
if (major > 24) {
return true;
}
return NODE_NATIVE_ENV_PROXY_SUPPORT[major] != null && minor >= NODE_NATIVE_ENV_PROXY_SUPPORT[major];
}
function isNodeEnvProxyEnabled(agent, nodeVersion = process.versions && process.versions.node) {
if (!isNodeNativeEnvProxySupported(nodeVersion)) {
return false;
}
const agentOptions = agent && agent.options;
return Boolean(agentOptions && utils$1.hasOwnProp(agentOptions, 'proxyEnv') && agentOptions.proxyEnv != null);
}
function getProxyEnvAgent(options, configHttpAgent, configHttpsAgent) {
return isHttps.test(options.protocol) ? configHttpsAgent || https.globalAgent : configHttpAgent || http.globalAgent;
}
function getTunnelingAgent(agentOptions, userHttpsAgent) {
const key = agentOptions.protocol + '//' + agentOptions.hostname + ':' + (agentOptions.port || '') + '#' + (agentOptions.auth || '');
const cache = userHttpsAgent ? tunnelingAgentCacheUser.get(userHttpsAgent) || tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent) : tunnelingAgentCache;
let agent = cache.get(key);
if (agent) return agent;
// Forward the user's TLS options (custom CA, rejectUnauthorized, client cert,
// etc.) into the tunneling agent so they apply to the origin TLS upgrade
// performed after CONNECT. Our proxy fields take precedence on conflict.
const merged = userHttpsAgent && userHttpsAgent.options ? {
...userHttpsAgent.options,
...agentOptions
} : agentOptions;
agent = new HttpsProxyAgent(merged);
if (userHttpsAgent && userHttpsAgent.options) {
const originTLSOptions = {
...userHttpsAgent.options
};
const callback = agent.callback;
agent.callback = function axiosTunnelingAgentCallback(req, opts) {
// HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade.
return callback.call(this, req, {
...originTLSOptions,
...opts
});
};
}
agent[kAxiosInstalledTunnel] = true;
cache.set(key, agent);
return agent;
}
const supportedProtocols = platform.protocols.map(protocol => {
return protocol + ':';
});
// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
// Decode before composing the `auth` option so credentials such as
// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
// original value for malformed input so a bad encoding never throws.
const decodeURIComponentSafe$1 = value => {
if (!utils$1.isString(value)) {
return value;
}
try {
return decodeURIComponent(value);
} catch (error) {
return value;
}
};
const flushOnFinish = (stream, [throttled, flush]) => {
stream.on('end', flush).on('error', flush);
return throttled;
};
const http2Sessions = new Http2Sessions();
/**
* If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
* call them with the options object.
*
* @param {Object<string, any>} options - The options object that was passed to the request.
*
* @returns {Object<string, any>}
*/
function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
if (options.beforeRedirects.proxy) {
options.beforeRedirects.proxy(options);
}
if (options.beforeRedirects.auth) {
options.beforeRedirects.auth(options);
}
if (options.beforeRedirects.sensitiveHeaders) {
options.beforeRedirects.sensitiveHeaders(options, requestDetails);
}
if (options.beforeRedirects.config) {
options.beforeRedirects.config(options, responseDetails, requestDetails);
}
}
function stripMatchingHeaders(headers, sensitiveSet) {
if (!headers) {
return;
}
Object.keys(headers).forEach(header => {
if (sensitiveSet.has(header.toLowerCase())) {
delete headers[header];
}
});
}
function isSameOriginRedirect(redirectOptions, requestDetails) {
if (!requestDetails) {
return false;
}
try {
return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
} catch (e) {
// If origin comparison fails, treat the redirect as unsafe.
return false;
}
}
/**
* If the proxy or config afterRedirects functions are defined, call them with the options
*
* @param {http.ClientRequestArgs} options
* @param {AxiosProxyConfig} configProxy configuration from Axios options object
* @param {string} location
*
* @returns {http.ClientRequestArgs}
*/
function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent) {
let proxy = configProxy;
const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent);
if (!proxy && proxy !== false && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
const proxyUrl = getProxyForUrl(location);
if (proxyUrl) {
if (!shouldBypassProxy(location)) {
proxy = new URL(proxyUrl);
}
}
}
// On redirect re-invocation, strip any stale Proxy-Authorization header carried
// over from the prior request (e.g. new target no longer uses a proxy, or uses
// a different proxy). Skip on the initial request so user-supplied headers are
// preserved. Header names are case-insensitive, so remove every case variant.
if (isRedirect && options.headers) {
for (const name of Object.keys(options.headers)) {
if (name.toLowerCase() === 'proxy-authorization') {
delete options.headers[name];
}
}
}
// Strip any tunneling agent we installed for the previous hop so a redirect
// that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
// stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
// (which won't carry the marker) is left alone.
if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
options.agent = undefined;
}
if (proxy) {
// Read proxy fields without traversing the prototype chain. URL instances expose
// username/password/hostname/host/port/protocol via getters on URL.prototype (so
// direct reads are shielded), but plain object proxies — and the `auth` field
// (which URL does not expose) — must be guarded so a polluted Object.prototype
// (e.g. Object.prototype.auth = { username, password }) cannot inject
// attacker-controlled credentials into the Proxy-Authorization header or
// redirect proxying to an attacker-controlled host.
const isProxyURL = proxy instanceof URL;
const readProxyField = key => isProxyURL || utils$1.hasOwnProp(proxy, key) ? proxy[key] : undefined;
const proxyUsername = readProxyField('username');
const proxyPassword = readProxyField('password');
let proxyAuth = utils$1.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
// Basic proxy authorization
if (proxyUsername) {
proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
}
if (proxyAuth) {
// Support proxy auth object form. Read sub-fields via own-prop checks so a
// plain object inheriting from polluted Object.prototype cannot leak creds.
const authIsObject = typeof proxyAuth === 'object';
const authUsername = authIsObject && utils$1.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
const authPassword = authIsObject && utils$1.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
const validProxyAuth = Boolean(authUsername || authPassword);
if (validProxyAuth) {
proxyAuth = (authUsername || '') + ':' + (authPassword || '');
} else if (authIsObject) {
throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, {
proxy
});
}
}
const targetIsHttps = isHttps.test(options.protocol);
if (targetIsHttps) {
// CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
// the origin so the proxy cannot inspect the URL, headers, or body — the
// behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
// sends Proxy-Authorization on the CONNECT request only, never on the
// wrapped TLS request, which is why we don't stamp it onto
// options.headers here. If the user already supplied an HttpsProxyAgent,
// they own tunneling end-to-end and we leave them alone; otherwise we
// install our own tunneling agent and forward their TLS options (if any)
// so a custom httpsAgent for cert pinning / rejectUnauthorized still
// applies to the origin TLS upgrade.
if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
const proxyHost = readProxyField('hostname') || readProxyField('host');
const proxyPort = readProxyField('port');
const rawProxyProtocol = readProxyField('protocol');
const normalizedProtocol = rawProxyProtocol ? rawProxyProtocol.includes(':') ? rawProxyProtocol : `${rawProxyProtocol}:` : 'http:';
// Bracket IPv6 literals for URL parsing; URL.hostname strips the
// brackets again on read so the agent receives the raw form.
const proxyHostForURL = proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[') ? `[${proxyHost}]` : proxyHost;
const proxyURL = new URL(`${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`);
const agentOptions = {
protocol: proxyURL.protocol,
hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
port: proxyURL.port,
auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined
};
if (proxyURL.protocol === 'https:') {
agentOptions.ALPNProtocols = ['http/1.1'];
}
const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
// Set both: `options.agent` is consumed by the native https.request path
// (maxRedirects === 0); `options.agents.https` is consumed by
// follow-redirects, which ignores `options.agent` when `options.agents`
// is present.
options.agent = tunnelingAgent;
if (options.agents) {
options.agents.https = tunnelingAgent;
}
}
} else {
// Forward-proxy mode for plaintext HTTP targets. The request line carries
// the absolute URL and the proxy sees everything — acceptable for plain
// HTTP since the wire was already plaintext.
if (proxyAuth) {
const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
}
// Preserve a user-supplied Host header (case-insensitive) so callers can override
// the value forwarded to the proxy; otherwise default to the request URL's host.
let hasUserHostHeader = false;
for (const name of Object.keys(options.headers)) {
if (name.toLowerCase() === 'host') {
hasUserHostHeader = true;
break;
}
}
if (!hasUserHostHeader) {
options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
}
const proxyHost = readProxyField('hostname') || readProxyField('host');
options.hostname = proxyHost;
// Replace 'host' since options is not a URL object
options.host = proxyHost;
options.port = readProxyField('port');
options.path = location;
const proxyProtocol = readProxyField('protocol');
if (proxyProtocol) {
options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
}
}
}
options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
// Configure proxy for redirected request, passing the original config proxy to apply
// the exact same logic as if the redirected request was performed by axios directly.
setProxy(redirectOptions, configProxy, redirectOptions.href, true, configHttpsAgent, configHttpAgent);
};
}
const isHttpAdapterSupported = typeof process !== 'undefined' && utils$1.kindOf(process) === 'process';
// temporary hotfix
const wrapAsync = asyncExecutor => {
return new Promise((resolve, reject) => {
let onDone;
let isDone;
const done = (value, isRejected) => {
if (isDone) return;
isDone = true;
onDone && onDone(value, isRejected);
};
const _resolve = value => {
done(value);
resolve(value);
};
const _reject = reason => {
done(reason, true);
reject(reason);
};
asyncExecutor(_resolve, _reject, onDoneHandler => onDone = onDoneHandler).catch(_reject);
});
};
const resolveFamily = ({
address,
family
}) => {
if (!utils$1.isString(address)) {
throw TypeError('address must be a string');
}
return {
address,
family: family || (address.indexOf('.') < 0 ? 6 : 4)
};
};
const buildAddressEntry = (address, family) => resolveFamily(utils$1.isObject(address) ? address : {
address,
family
});
const http2Transport = {
request(options, cb) {
const authority = options.protocol + '//' + options.hostname + ':' + (options.port || (options.protocol === 'https:' ? 443 : 80));
const {
http2Options,
headers
} = options;
const session = http2Sessions.getSession(authority, http2Options);
const {
HTTP2_HEADER_SCHEME,
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_STATUS
} = http2.constants;
const http2Headers = {
[HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
[HTTP2_HEADER_METHOD]: options.method,
[HTTP2_HEADER_PATH]: options.path
};
utils$1.forEach(headers, (header, name) => {
name.charAt(0) !== ':' && (http2Headers[name] = header);
});
const req = session.request(http2Headers);
req.once('response', responseHeaders => {
const response = req; //duplex
responseHeaders = Object.assign({}, responseHeaders);
const status = responseHeaders[HTTP2_HEADER_STATUS];
delete responseHeaders[HTTP2_HEADER_STATUS];
response.headers = responseHeaders;
response.statusCode = +status;
cb(response);
});
return req;
}
};
/*eslint consistent-return:0*/
var httpAdapter = isHttpAdapterSupported && function httpAdapter(config) {
return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
// Read config pollution-safely: own properties and members inherited from
// a non-Object.prototype source (e.g. an Object.create(defaults) template)
// are honored, but values injected onto a polluted Object.prototype are
// ignored. All behavior-affecting reads in this adapter go through own()
// so the protection boundary stays consistent.
const own = key => utils$1.getSafeProp(config, key);
const transitional = own('transitional') || transitionalDefaults;
let data = own('data');
let lookup = own('lookup');
let family = own('family');
let httpVersion = own('httpVersion');
if (httpVersion === undefined) httpVersion = 1;
let http2Options = own('http2Options');
const httpAgent = own('httpAgent');
const httpsAgent = own('httpsAgent');
const configProxy = own('proxy');
const responseType = own('responseType');
const responseEncoding = own('responseEncoding');
const socketPath = own('socketPath');
const method = own('method').toUpperCase();
const maxRedirects = own('maxRedirects');
const maxBodyLength = own('maxBodyLength');
const maxContentLength = own('maxContentLength');
const decompress = own('decompress');
let isDone;
let rejected = false;
let req;
let connectPhaseTimer;
httpVersion = +httpVersion;
if (Number.isNaN(httpVersion)) {
throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
}
if (httpVersion !== 1 && httpVersion !== 2) {
throw TypeError(`Unsupported protocol version '${httpVersion}'`);
}
const isHttp2 = httpVersion === 2;
if (lookup) {
const _lookup = callbackify(lookup, value => utils$1.isArray(value) ? value : [value]);
// hotfix to support opt.all option which is required for node 20.x
lookup = (hostname, opt, cb) => {
_lookup(hostname, opt, (err, arg0, arg1) => {
if (err) {
return cb(err);
}
const addresses = utils$1.isArray(arg0) ? arg0.map(addr => buildAddressEntry(addr)) : [buildAddressEntry(arg0, arg1)];
opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
});
};
}
const abortEmitter = new events.EventEmitter();
function abort(reason) {
try {
abortEmitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
} catch (err) {
// ignore emit errors
}
}
function clearConnectPhaseTimer() {
if (connectPhaseTimer) {
clearTimeout(connectPhaseTimer);
connectPhaseTimer = null;
}
}
function createTimeoutError() {
const configTimeout = own('timeout');
let timeoutErrorMessage = configTimeout ? 'timeout of ' + configTimeout + 'ms exceeded' : 'timeout exceeded';
const configTimeoutErrorMessage = own('timeoutErrorMessage');
if (configTimeoutErrorMessage) {
timeoutErrorMessage = configTimeoutErrorMessage;
}
return new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, req);
}
abortEmitter.once('abort', reject);
const onFinished = () => {
clearConnectPhaseTimer();
if (config.cancelToken) {
config.cancelToken.unsubscribe(abort);
}
if (config.signal) {
config.signal.removeEventListener('abort', abort);
}
abortEmitter.removeAllListeners();
};
if (config.cancelToken || config.signal) {
config.cancelToken && config.cancelToken.subscribe(abort);
if (config.signal) {
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
}
}
onDone((response, isRejected) => {
isDone = true;
clearConnectPhaseTimer();
if (isRejected) {
rejected = true;
onFinished();
return;
}
const {
data
} = response;
if (data instanceof stream.Readable || data instanceof stream.Duplex) {
const offListeners = stream.finished(data, () => {
offListeners();
onFinished();
});
} else {
onFinished();
}
});
// Parse url
const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config);
// Unix-socket requests (own socketPath) commonly pass a path-only url
// like '/foo'; supply a synthetic base so new URL() can still parse it.
// Use the own-property value (not config.socketPath) so a polluted
// prototype cannot influence URL base selection.
const urlBase = socketPath ? 'http://localhost' : platform.hasBrowserEnv ? platform.origin : undefined;
const parsed = new URL(fullPath, urlBase);
const protocol = parsed.protocol || supportedProtocols[0];
if (protocol === 'data:') {
// Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
if (maxContentLength > -1) {
// Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed.
const dataUrl = String(own('url') || fullPath || '');
const estimated = estimateDataURLDecodedBytes(dataUrl);
if (estimated > maxContentLength) {
return reject(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config));
}
}
let convertedData;
if (method !== 'GET') {
return settle(resolve, reject, {
status: 405,
statusText: 'method not allowed',
headers: {},
config
});
}
try {
convertedData = fromDataURI(own('url'), responseType === 'blob', {
Blob: config.env && config.env.Blob
});
} catch (err) {
throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
}
if (responseType === 'text') {
convertedData = convertedData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
convertedData = utils$1.stripBOM(convertedData);
}
} else if (responseType === 'stream') {
convertedData = stream.Readable.from(convertedData);
}
return settle(resolve, reject, {
data: convertedData,
status: 200,
statusText: 'OK',
headers: new AxiosHeaders(),
config
});
}
if (supportedProtocols.indexOf(protocol) === -1) {
return reject(new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config));
}
const headers = AxiosHeaders.from(config.headers).normalize();
// Set User-Agent (required by some servers)
// See https://github.com/axios/axios/issues/69
// User-Agent is specified; handle case where no UA header is desired
// Only set header if it hasn't been set in config
headers.set('User-Agent', 'axios/' + VERSION, false);
const {
onUploadProgress,
onDownloadProgress
} = config;
const maxRate = config.maxRate;
let maxUploadRate = undefined;
let maxDownloadRate = undefined;
// support for spec compliant FormData objects
if (utils$1.isSpecCompliantForm(data)) {
const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
data = formDataToStream(data, formHeaders => {
headers.set(formHeaders);
}, {
tag: `axios-${VERSION}-boundary`,
boundary: userBoundary && userBoundary[1] || undefined
});
// support for https://www.npmjs.com/package/form-data api
} else if (utils$1.isFormData(data) && utils$1.isFunction(data.getHeaders) && data.getHeaders !== Object.prototype.getHeaders) {
setFormDataHeaders$1(headers, data.getHeaders(), own('formDataHeaderPolicy'));
if (!headers.hasContentLength()) {
try {
const knownLength = await util.promisify(data.getLength).call(data);
Number.isFinite(knownLength) && knownLength >= 0 && headers.setContentLength(knownLength);
/*eslint no-empty:0*/
} catch (e) {}
}
} else if (utils$1.isBlob(data) || utils$1.isFile(data)) {
data.size && headers.setContentType(data.type || 'application/octet-stream');
headers.setContentLength(data.size || 0);
data = stream.Readable.from(readBlob(data));
} else if (data && !utils$1.isStream(data)) {
if (Buffer.isBuffer(data)) ; else if (utils$1.isArrayBuffer(data)) {
data = Buffer.from(new Uint8Array(data));
} else if (utils$1.isString(data)) {
data = Buffer.from(data, 'utf-8');
} else {
return reject(new AxiosError('Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream', AxiosError.ERR_BAD_REQUEST, config));
}
// Add Content-Length header if data exists
headers.setContentLength(data.length, false);
if (maxBodyLength > -1 && data.length > maxBodyLength) {
return reject(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config));
}
}
const contentLength = utils$1.toFiniteNumber(headers.getContentLength());
if (utils$1.isArray(maxRate)) {
maxUploadRate = maxRate[0];
maxDownloadRate = maxRate[1];
} else {
maxUploadRate = maxDownloadRate = maxRate;
}
if (data && (onUploadProgress || maxUploadRate)) {
if (!utils$1.isStream(data)) {
data = stream.Readable.from(data, {
objectMode: false
});
}
data = stream.pipeline([data, new AxiosTransformStream({
maxRate: utils$1.toFiniteNumber(maxUploadRate)
})], utils$1.noop);
onUploadProgress && data.on('progress', flushOnFinish(data, progressEventDecorator(contentLength, progressEventReducer(asyncDecorator(onUploadProgress), false, 3))));
}
// HTTP basic authentication
let auth = undefined;
const configAuth = own('auth');
if (configAuth) {
const username = utils$1.getSafeProp(configAuth, 'username') || '';
const password = utils$1.getSafeProp(configAuth, 'password') || '';
auth = username + ':' + password;
}
if (!auth && (parsed.username || parsed.password)) {
const urlUsername = decodeURIComponentSafe$1(parsed.username);
const urlPassword = decodeURIComponentSafe$1(parsed.password);
auth = urlUsername + ':' + urlPassword;
}
auth && headers.delete('authorization');
let path$1;
try {
path$1 = buildURL(parsed.pathname + parsed.search, own('params'), own('paramsSerializer')).replace(/^\?/, '');
} catch (err) {
return reject(AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config, null, null, {
url: own('url'),
exists: true
}));
}
headers.set('Accept-Encoding', utils$1.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') && transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING, false);
// Null-prototype to block prototype pollution gadgets on properties read
// directly by Node's http.request (e.g. insecureHTTPParser, lookup).
const options = Object.assign(Object.create(null), {
path: path$1,
method: method,
headers: toByteStringHeaderObject(headers),
agents: {
http: httpAgent,
https: httpsAgent
},
auth,
protocol,
family,
beforeRedirect: dispatchBeforeRedirect,
beforeRedirects: Object.create(null),
http2Options
});
// cacheable-lookup integration hotfix
!utils$1.isUndefined(lookup) && (options.lookup = lookup);
if (socketPath) {
if (typeof socketPath !== 'string') {
return reject(new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config));
}
const allowedSocketPaths = own('allowedSocketPaths');
if (allowedSocketPaths != null) {
const allowed = Array.isArray(allowedSocketPaths) ? allowedSocketPaths : [allowedSocketPaths];
const resolvedSocket = path.resolve(socketPath);
const isAllowed = allowed.some(entry => typeof entry === 'string' && path.resolve(entry) === resolvedSocket);
if (!isAllowed) {
return reject(new AxiosError(`socketPath "${socketPath}" is not permitted by allowedSocketPaths`, AxiosError.ERR_BAD_OPTION_VALUE, config));
}
}
options.socketPath = socketPath;
} else {
options.hostname = parsed.hostname.startsWith('[') ? parsed.hostname.slice(1, -1) : parsed.hostname;
options.port = parsed.port;
setProxy(options, configProxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path, false, httpsAgent, httpAgent);
}
let transport;
let isNativeTransport = false;
// True only for the follow-redirects transport, which applies
// options.maxBodyLength itself. Every other transport (http2, native
// http/https, a user-supplied custom transport) needs the explicit
// byte-counting pipeline below to enforce maxBodyLength on streamed uploads.
let transportEnforcesMaxBodyLength = false;
const isHttpsRequest = isHttps.test(options.protocol);
// Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
// HTTPS target.
if (options.agent == null) {
options.agent = isHttpsRequest ? httpsAgent : httpAgent;
}
if (isHttp2) {
transport = http2Transport;
} else {
const configTransport = own('transport');
if (configTransport) {
transport = configTransport;
} else if (maxRedirects === 0) {
transport = isHttpsRequest ? https : http;
isNativeTransport = true;
} else {
transportEnforcesMaxBodyLength = true;
options.sensitiveHeaders = [];
if (maxRedirects) {
options.maxRedirects = maxRedirects;
}
const configBeforeRedirect = own('beforeRedirect');
if (configBeforeRedirect) {
options.beforeRedirects.config = configBeforeRedirect;
}
if (auth) {
// Restore HTTP Basic credentials on same-origin redirects only.
// follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929);
// cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md
// and is preserved by deliberately not restoring on origin change.
const requestOrigin = parsed.origin;
const authToRestore = auth;
options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) {
try {
if (new URL(redirectOptions.href).origin === requestOrigin) {
redirectOptions.auth = authToRestore;
}
} catch (e) {
// ignore malformed URL: leaving auth stripped is fail-safe
}
};
}
const sensitiveHeaders = own('sensitiveHeaders');
if (sensitiveHeaders != null) {
if (!utils$1.isArray(sensitiveHeaders)) {
return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
}
const sensitiveSet = new Set();
for (const header of sensitiveHeaders) {
if (!utils$1.isString(header)) {
return reject(new AxiosError('sensitiveHeaders must be an array of strings', AxiosError.ERR_BAD_OPTION_VALUE, config));
}
sensitiveSet.add(header.toLowerCase());
}
if (sensitiveSet.size) {
options.sensitiveHeaders = Array.from(sensitiveSet);
options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(redirectOptions, requestDetails) {
if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
}
};
}
}
transport = isHttpsRequest ? httpsFollow : httpFollow;
}
}
// Set an explicit maxBodyLength option for transports that inspect it.
// When maxBodyLength is -1 (default/unlimited), use Infinity so
// follow-redirects does not fall back to its own 10MB default.
if (maxBodyLength > -1) {
options.maxBodyLength = maxBodyLength;
} else {
options.maxBodyLength = Infinity;
}
// Always set an explicit own value so a polluted
// Object.prototype.insecureHTTPParser cannot enable the lenient parser
// through Node's internal options copy
options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
// Create the request
req = transport.request(options, function handleResponse(res) {
clearConnectPhaseTimer();
if (req.destroyed) return;
const streams = [res];
const responseLength = utils$1.toFiniteNumber(res.headers['content-length']);
if (onDownloadProgress || maxDownloadRate) {
const transformStream = new AxiosTransformStream({
maxRate: utils$1.toFiniteNumber(maxDownloadRate)
});
onDownloadProgress && transformStream.on('progress', flushOnFinish(transformStream, progressEventDecorator(responseLength, progressEventReducer(asyncDecorator(onDownloadProgress), true, 3))));
streams.push(transformStream);
}
// decompress the response body transparently if required
let responseStream = res;
// return the last request in case of redirects
const lastRequest = res.req || req;
// if decompress disabled we should not decompress
if (decompress !== false && res.headers['content-encoding']) {
// if no content, but headers still say that it is encoded,
// remove the header not confuse downstream operations
if (method === 'HEAD' || res.statusCode === 204) {
delete res.headers['content-encoding'];
}
switch ((res.headers['content-encoding'] || '').toLowerCase()) {
/*eslint default-case:0*/
case 'gzip':
case 'x-gzip':
case 'compress':
case 'x-compress':
// add the unzipper to the body stream processing pipeline
streams.push(zlib.createUnzip(zlibOptions));
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'deflate':
streams.push(new ZlibHeaderTransformStream());
// add the unzipper to the body stream processing pipeline
streams.push(zlib.createUnzip(zlibOptions));
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'br':
if (isBrotliSupported) {
streams.push(zlib.createBrotliDecompress(brotliOptions));
delete res.headers['content-encoding'];
}
break;
case 'zstd':
if (isZstdSupported) {
streams.push(zlib.createZstdDecompress(zstdOptions));
delete res.headers['content-encoding'];
}
break;
}
}
responseStream = streams.length > 1 ? stream.pipeline(streams, utils$1.noop) : streams[0];
const response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: new AxiosHeaders(res.headers),
config,
request: lastRequest
};
if (responseType === 'stream') {
// Enforce maxContentLength on streamed responses; previously this
// was applied only to buffered responses.
if (maxContentLength > -1) {
const limit = maxContentLength;
const source = responseStream;
async function* enforceMaxContentLength() {
let totalResponseBytes = 0;
for await (const chunk of source) {
totalResponseBytes += chunk.length;
if (totalResponseBytes > limit) {
throw new AxiosError('maxContentLength size of ' + limit + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest);
}
yield chunk;
}
}
responseStream = stream.Readable.from(enforceMaxContentLength(), {
objectMode: false
});
}
response.data = responseStream;
settle(resolve, reject, response);
} else {
const responseBuffer = [];
let totalResponseBytes = 0;
responseStream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
totalResponseBytes += chunk.length;
// make sure the content length is not over the maxContentLength if specified
if (maxContentLength > -1 && totalResponseBytes > maxContentLength) {
// stream.destroy() emit aborted event before calling reject() on Node.js v16
rejected = true;
responseStream.destroy();
abort(new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, lastRequest));
}
});
responseStream.on('aborted', function handlerStreamAborted() {
if (rejected) {
return;
}
const err = new AxiosError('stream has been aborted', AxiosError.ERR_BAD_RESPONSE, config, lastRequest, response);
responseStream.destroy(err);
reject(err);
});
responseStream.on('error', function handleStreamError(err) {
if (rejected) return;
reject(AxiosError.from(err, null, config, lastRequest, response));
});
responseStream.on('end', function handleStreamEnd() {
try {
let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
if (responseType !== 'arraybuffer') {
responseData = responseData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
responseData = utils$1.stripBOM(responseData);
}
}
response.data = responseData;
} catch (err) {
return reject(AxiosError.from(err, null, config, response.request, response));
}
settle(resolve, reject, response);
});
}
abortEmitter.once('abort', err => {
if (!responseStream.destroyed) {
responseStream.emit('error', err);
responseStream.destroy();
}
});
});
abortEmitter.once('abort', err => {
if (req.close) {
req.close();
} else {
req.destroy(err);
}
});
// Handle errors
req.on('error', function handleRequestError(err) {
reject(AxiosError.from(err, null, config, req));
});
// set tcp keep alive to prevent drop connection by peer
// Track every socket bound to this outer RedirectableRequest so a single
// 'close' listener can release ownership on all of them. follow-redirects
// re-emits the 'socket' event for each hop's native request onto the same
// outer request, so attaching per-request listeners inside this handler
// would accumulate across hops and trigger MaxListenersExceededWarning at
// >= 11 redirects. Clearing only the last-bound socket would leave stale
// kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
// pool, causing an idle-pool 'error' to be attributed to a closed req.
const boundSockets = new Set();
req.on('socket', function handleRequestSocket(socket) {
// default interval of sending ack packet is 1 minute
// proxy agents (e.g. agent-base) may return a generic Duplex stream
// that doesn't have setKeepAlive, so guard before calling
if (typeof socket.setKeepAlive === 'function') {
socket.setKeepAlive(true, 1000 * 60);
}
// Install a single 'error' listener per socket (not per request) to avoid
// accumulating listeners on pooled keep-alive sockets that get reassigned
// to new requests before the previous request's 'close' fires (issue #10780).
// The listener is bound to the socket's currently-active request via a
// symbol, which is swapped as the socket is reassigned.
if (!socket[kAxiosSocketListener]) {
socket.on('error', function handleSocketError(err) {
const current = socket[kAxiosCurrentReq];
if (current && !current.destroyed) {
current.destroy(err);
}
});
socket[kAxiosSocketListener] = true;
}
socket[kAxiosCurrentReq] = req;
boundSockets.add(socket);
});
req.once('close', function clearCurrentReq() {
clearConnectPhaseTimer();
for (const socket of boundSockets) {
if (socket[kAxiosCurrentReq] === req) {
socket[kAxiosCurrentReq] = null;
}
}
boundSockets.clear();
});
// Handle request timeout
if (own('timeout')) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
const timeout = parseInt(own('timeout'), 10);
if (Number.isNaN(timeout)) {
abort(new AxiosError('error trying to parse `config.timeout` to int', AxiosError.ERR_BAD_OPTION_VALUE, config, req));
return;
}
const handleTimeout = function handleTimeout() {
if (isDone) return;
abort(createTimeoutError());
};
if (isNativeTransport && timeout > 0) {
// Native ClientRequest#setTimeout starts from the socket lifecycle and
// may not fire while TCP connect is still pending. Mirror the
// follow-redirects wall-clock timer for the maxRedirects === 0 path.
connectPhaseTimer = setTimeout(handleTimeout, timeout);
}
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
// And then these socket which be hang up will devouring CPU little by little.
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
req.setTimeout(timeout, handleTimeout);
} else {
// explicitly reset the socket timeout value for a possible `keep-alive` request
req.setTimeout(0);
}
// Send the request
if (utils$1.isStream(data)) {
let ended = false;
let errored = false;
data.on('end', () => {
ended = true;
});
data.once('error', err => {
errored = true;
req.destroy(err);
});
data.on('close', () => {
if (!ended && !errored) {
abort(new CanceledError('Request stream has been aborted', config, req));
}
});
// Enforce maxBodyLength for streamed uploads on every transport that
// does not apply options.maxBodyLength itself (native http/https, http2,
// and user-supplied custom transports). The follow-redirects transport
// enforces it on the redirected HTTP/1 path.
let uploadStream = data;
if (maxBodyLength > -1 && !transportEnforcesMaxBodyLength) {
const limit = maxBodyLength;
let bytesSent = 0;
uploadStream = stream.pipeline([data, new stream.Transform({
transform(chunk, _enc, cb) {
bytesSent += chunk.length;
if (bytesSent > limit) {
return cb(new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, req));
}
cb(null, chunk);
}
})], utils$1.noop);
uploadStream.on('error', err => {
if (!req.destroyed) req.destroy(err);
});
}
uploadStream.pipe(req);
} else {
data && req.write(data);
req.end();
}
});
};
var isURLSameOrigin = platform.hasStandardBrowserEnv ? ((origin, isMSIE) => url => {
url = new URL(url, platform.origin);
return origin.protocol === url.protocol && origin.host === url.host && (isMSIE || origin.port === url.port);
})(new URL(platform.origin), platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)) : () => true;
var cookies = platform.hasStandardBrowserEnv ?
// Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure, sameSite) {
if (typeof document === 'undefined') return;
const cookie = [`${name}=${encodeURIComponent(value)}`];
if (utils$1.isNumber(expires)) {
cookie.push(`expires=${new Date(expires).toUTCString()}`);
}
if (utils$1.isString(path)) {
cookie.push(`path=${path}`);
}
if (utils$1.isString(domain)) {
cookie.push(`domain=${domain}`);
}
if (secure === true) {
cookie.push('secure');
}
if (utils$1.isString(sameSite)) {
cookie.push(`SameSite=${sameSite}`);
}
document.cookie = cookie.join('; ');
},
read(name) {
if (typeof document === 'undefined') return null;
// Match name=value by splitting on the semicolon separator instead of building a
// RegExp from `name` — interpolating an unescaped string into a RegExp would let
// metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
// match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
// "; ", so ignore optional whitespace before each cookie name.
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].replace(/^\s+/, '');
const eq = cookie.indexOf('=');
if (eq !== -1 && cookie.slice(0, eq) === name) {
try {
return decodeURIComponent(cookie.slice(eq + 1));
} catch (e) {
return cookie.slice(eq + 1);
}
}
}
return null;
},
remove(name) {
this.write(name, '', Date.now() - 86400000, '/');
}
} :
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {}
};
const headersToObject = thing => thing instanceof AxiosHeaders ? {
...thing
} : thing;
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config1 = config1 || {};
config2 = config2 || {};
// Use a null-prototype object so that downstream reads such as `config.auth`
// or `config.baseURL` cannot inherit polluted values from Object.prototype.
// `hasOwnProperty` is restored as a non-enumerable own slot to preserve
// ergonomics for user code that relies on it.
const config = Object.create(null);
Object.defineProperty(config, 'hasOwnProperty', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: Object.prototype.hasOwnProperty,
enumerable: false,
writable: true,
configurable: true
});
function getMergedValue(target, source, prop, caseless) {
if (utils$1.isPlainObject(target) && utils$1.isPlainObject(source)) {
return utils$1.merge.call({
caseless
}, target, source);
} else if (utils$1.isPlainObject(source)) {
return utils$1.merge({}, source);
} else if (utils$1.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(a, b, prop, caseless) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(a, b, prop, caseless);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a, prop, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils$1.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils$1.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
function getMergedTransitionalOption(prop) {
const transitional2 = utils$1.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
if (!utils$1.isUndefined(transitional2)) {
if (utils$1.isPlainObject(transitional2)) {
if (utils$1.hasOwnProp(transitional2, prop)) {
return transitional2[prop];
}
} else {
return undefined;
}
}
const transitional1 = utils$1.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
if (utils$1.isPlainObject(transitional1) && utils$1.hasOwnProp(transitional1, prop)) {
return transitional1[prop];
}
return undefined;
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (utils$1.hasOwnProp(config2, prop)) {
return getMergedValue(a, b);
} else if (utils$1.hasOwnProp(config1, prop)) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
allowedSocketPaths: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b, prop) => mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true)
};
utils$1.forEach(Object.keys({
...config1,
...config2
}), function computeConfigValue(prop) {
if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
const merge = utils$1.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
const a = utils$1.hasOwnProp(config1, prop) ? config1[prop] : undefined;
const b = utils$1.hasOwnProp(config2, prop) ? config2[prop] : undefined;
const configValue = merge(a, b, prop);
utils$1.isUndefined(configValue) && merge !== mergeDirectKeys || (config[prop] = configValue);
});
if (utils$1.hasOwnProp(config2, 'validateStatus') && utils$1.isUndefined(config2.validateStatus) && getMergedTransitionalOption('validateStatusUndefinedResolves') === false) {
if (utils$1.hasOwnProp(config1, 'validateStatus')) {
config.validateStatus = getMergedValue(undefined, config1.validateStatus);
} else {
delete config.validateStatus;
}
}
return config;
}
const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
function setFormDataHeaders(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders || {}).forEach(([key, val]) => {
if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8$1 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
function resolveConfig(config) {
const newConfig = mergeConfig({}, config);
// Read only own properties to prevent prototype pollution gadgets
// (e.g. Object.prototype.baseURL = 'https://evil.com').
const own = key => utils$1.hasOwnProp(newConfig, key) ? newConfig[key] : undefined;
const data = own('data');
let withXSRFToken = own('withXSRFToken');
const xsrfHeaderName = own('xsrfHeaderName');
const xsrfCookieName = own('xsrfCookieName');
let headers = own('headers');
const auth = own('auth');
const baseURL = own('baseURL');
const allowAbsoluteUrls = own('allowAbsoluteUrls');
const url = own('url');
newConfig.headers = headers = AxiosHeaders.from(headers);
newConfig.url = buildURL(buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig), own('params'), own('paramsSerializer'));
// HTTP basic authentication
if (auth) {
const username = utils$1.getSafeProp(auth, 'username') || '';
const password = utils$1.getSafeProp(auth, 'password') || '';
try {
headers.set('Authorization', 'Basic ' + btoa(username + ':' + (password ? encodeUTF8$1(password) : '')));
} catch (e) {
throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config);
}
}
if (utils$1.isFormData(data)) {
if (platform.hasStandardBrowserEnv || platform.hasStandardBrowserWebWorkerEnv || utils$1.isReactNative(data)) {
headers.setContentType(undefined); // browser/web worker/RN handles it
} else if (utils$1.isFunction(data.getHeaders)) {
// Node.js FormData (like form-data package)
setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
if (utils$1.isFunction(withXSRFToken)) {
withXSRFToken = withXSRFToken(newConfig);
}
// Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
// and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
// the XSRF token cross-origin.
const shouldSendXSRF = withXSRFToken === true || withXSRFToken == null && isURLSameOrigin(newConfig.url);
if (shouldSendXSRF) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
}
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
var xhrAdapter = isXHRAdapterSupported && function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
let {
responseType,
onUploadProgress,
onDownloadProgress
} = _config;
let onCanceled;
let uploadThrottled, downloadThrottled;
let flushUpload, flushDownload;
function done() {
flushUpload && flushUpload(); // flush events
flushDownload && flushDownload(); // flush events
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener('abort', onCanceled);
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders.from('getAllResponseHeaders' in request && request.getAllResponseHeaders());
const responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request
};
settle(function _resolve(value) {
resolve(value);
done();
}, function _reject(err) {
reject(err);
done();
}, response);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.startsWith('file:'))) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
done();
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError(event) {
// Browsers deliver a ProgressEvent in XHR onerror
// (message may be empty; when present, surface it)
// See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
const msg = event && event.message ? event.message : 'Network Error';
const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
// attach the underlying event for consumers who want details
err.event = event || null;
reject(err);
done();
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout ? 'timeout of ' + _config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(new AxiosError(timeoutErrorMessage, transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request));
done();
// Clean up request
request = null;
};
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils$1.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils$1.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = _config.responseType;
}
// Handle progress if needed
if (onDownloadProgress) {
[downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
request.addEventListener('progress', downloadThrottled);
}
// Not all browsers support upload events
if (onUploadProgress && request.upload) {
[uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
request.upload.addEventListener('progress', uploadThrottled);
request.upload.addEventListener('loadend', flushUpload);
}
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = cancel => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
done();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted ? onCanceled() : _config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(_config.url);
if (protocol && !platform.protocols.includes(protocol)) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
done();
return;
}
// Send the request
request.send(requestData || null);
});
};
const composeSignals = (signals, timeout) => {
signals = signals ? signals.filter(Boolean) : [];
if (!timeout && !signals.length) {
return;
}
const controller = new AbortController();
let aborted = false;
const onabort = function (reason) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = reason instanceof Error ? reason : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
}
};
let timer = timeout && setTimeout(() => {
timer = null;
onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (!signals) {
return;
}
timer && clearTimeout(timer);
timer = null;
signals.forEach(signal => {
signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
});
signals = null;
};
signals.forEach(signal => signal.addEventListener('abort', onabort, {
once: true
}));
const {
signal
} = controller;
signal.unsubscribe = () => utils$1.asap(unsubscribe);
return signal;
};
const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
};
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
yield* stream;
return;
}
const reader = stream.getReader();
try {
for (;;) {
const {
done,
value
} = await reader.read();
if (done) {
break;
}
yield value;
}
} finally {
await reader.cancel();
}
};
const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = e => {
if (!done) {
done = true;
onFinish && onFinish(e);
}
};
return new ReadableStream({
async pull(controller) {
try {
const {
done,
value
} = await iterator.next();
if (done) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = bytes += len;
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
}
}, {
highWaterMark: 2
});
};
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const {
isFunction
} = utils$1;
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8 = str => encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
// Decode before composing the `auth` option so credentials such as
// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
// original value for malformed input so a bad encoding never throws.
const decodeURIComponentSafe = value => {
if (!utils$1.isString(value)) {
return value;
}
try {
return decodeURIComponent(value);
} catch (error) {
return value;
}
};
const test = (fn, ...args) => {
try {
return !!fn(...args);
} catch (e) {
return false;
}
};
const maybeWithAuthCredentials = url => {
const protocolIndex = url.indexOf('://');
let urlToCheck = url;
if (protocolIndex !== -1) {
urlToCheck = urlToCheck.slice(protocolIndex + 3);
}
return urlToCheck.includes('@') || urlToCheck.includes(':');
};
const factory = env => {
const globalObject = utils$1.global !== undefined && utils$1.global !== null ? utils$1.global : globalThis;
const {
ReadableStream,
TextEncoder
} = globalObject;
env = utils$1.merge.call({
skipUndefined: true
}, {
Request: globalObject.Request,
Response: globalObject.Response
}, env);
const {
fetch: envFetch,
Request,
Response
} = env;
const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
const isRequestSupported = isFunction(Request);
const isResponseSupported = isFunction(Response);
if (!isFetchSupported) {
return false;
}
const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
const encodeText = isFetchSupported && (typeof TextEncoder === 'function' ? (encoder => str => encoder.encode(str))(new TextEncoder()) : async str => new Uint8Array(await new Request(str).arrayBuffer()));
const supportsRequestStream = isRequestSupported && isReadableStreamSupported && test(() => {
let duplexAccessed = false;
const request = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
}
});
const hasContentType = request.headers.has('Content-Type');
if (request.body != null) {
request.body.cancel();
}
return duplexAccessed && !hasContentType;
});
const supportsResponseStream = isResponseSupported && isReadableStreamSupported && test(() => utils$1.isReadableStream(new Response('').body));
const resolvers = {
stream: supportsResponseStream && (res => res.body)
};
isFetchSupported && (() => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach(type => {
!resolvers[type] && (resolvers[type] = (res, config) => {
let method = res && res[type];
if (method) {
return method.call(res);
}
throw new AxiosError(`Response type '${type}' is not supported`, AxiosError.ERR_NOT_SUPPORT, config);
});
});
})();
const getBodyLength = async body => {
if (body == null) {
return 0;
}
if (utils$1.isBlob(body)) {
return body.size;
}
if (utils$1.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: 'POST',
body
});
return (await _request.arrayBuffer()).byteLength;
}
if (utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body)) {
return body.byteLength;
}
if (utils$1.isURLSearchParams(body)) {
body = body + '';
}
if (utils$1.isString(body)) {
return (await encodeText(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils$1.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
return async config => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions,
maxContentLength,
maxBodyLength
} = resolveConfig(config);
const hasMaxContentLength = utils$1.isNumber(maxContentLength) && maxContentLength > -1;
const hasMaxBodyLength = utils$1.isNumber(maxBodyLength) && maxBodyLength > -1;
const own = key => utils$1.hasOwnProp(config, key) ? config[key] : undefined;
let _fetch = envFetch || fetch;
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let composedSignal = composeSignals([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
let request = null;
const unsubscribe = composedSignal && composedSignal.unsubscribe && (() => {
composedSignal.unsubscribe();
});
let requestContentLength;
// AxiosError we raise while the request body is being streamed. Captured
// by identity so the catch block can surface it directly, regardless of
// how the runtime wraps the resulting fetch rejection (undici exposes it
// as `err.cause`; some browsers drop the original error entirely).
let pendingBodyError = null;
const maxBodyLengthError = () => new AxiosError('Request body larger than maxBodyLength limit', AxiosError.ERR_BAD_REQUEST, config, request);
try {
// HTTP basic authentication
let auth = undefined;
const configAuth = own('auth');
if (configAuth) {
const username = utils$1.getSafeProp(configAuth, 'username') || '';
const password = utils$1.getSafeProp(configAuth, 'password') || '';
auth = {
username,
password
};
}
if (maybeWithAuthCredentials(url)) {
const parsedURL = new URL(url, platform.origin);
if (!auth && (parsedURL.username || parsedURL.password)) {
const urlUsername = decodeURIComponentSafe(parsedURL.username);
const urlPassword = decodeURIComponentSafe(parsedURL.password);
auth = {
username: urlUsername,
password: urlPassword
};
}
if (parsedURL.username || parsedURL.password) {
parsedURL.username = '';
parsedURL.password = '';
url = parsedURL.href;
}
}
if (auth) {
headers.delete('authorization');
headers.set('Authorization', 'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || ''))));
}
// Enforce maxContentLength for data: URLs up-front so we never materialize
// an oversized payload. The HTTP adapter applies the same check (see http.js
// "if (protocol === 'data:')" branch).
if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
const estimated = estimateDataURLDecodedBytes(url);
if (estimated > maxContentLength) {
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
}
}
// Enforce maxBodyLength against known-size bodies before dispatch using
// the body's *actual* size — never a caller-declared Content-Length,
// which could under-report to slip an oversized body past the check.
// Unknown-size streams return undefined here and are counted per-chunk
// below as fetch consumes them.
if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
const outboundLength = await getBodyLength(data);
if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
requestContentLength = outboundLength;
if (outboundLength > maxBodyLength) {
throw maxBodyLengthError();
}
}
}
// A streamed body under maxBodyLength must be counted as fetch consumes
// it; its size is never trusted from a caller-declared Content-Length.
const mustEnforceStreamBody = hasMaxBodyLength && (utils$1.isReadableStream(data) || utils$1.isStream(data));
const trackRequestStream = (stream, onProgress, flush) => trackStream(stream, DEFAULT_CHUNK_SIZE, loadedBytes => {
if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
throw pendingBodyError = maxBodyLengthError();
}
onProgress && onProgress(loadedBytes);
}, flush);
if (supportsRequestStream && method !== 'get' && method !== 'head' && (onUploadProgress || mustEnforceStreamBody)) {
requestContentLength = requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
// A declared length of 0 is only trusted to skip the wrap when we are
// not enforcing a stream limit (which must not rely on that header).
if (requestContentLength !== 0 || mustEnforceStreamBody) {
let _request = new Request(url, {
method: 'POST',
body: data,
duplex: 'half'
});
let contentTypeHeader;
if (utils$1.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
const [onProgress, flush] = onUploadProgress && progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))) || [];
data = trackRequestStream(_request.body, onProgress, flush);
}
}
} else if (mustEnforceStreamBody && !isRequestSupported && isReadableStreamSupported && method !== 'get' && method !== 'head') {
data = trackRequestStream(data);
} else if (mustEnforceStreamBody && isRequestSupported && !supportsRequestStream && method !== 'get' && method !== 'head') {
throw new AxiosError('Stream request bodies are not supported by the current fetch implementation', AxiosError.ERR_NOT_SUPPORT, config, request);
}
if (!utils$1.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
// If data is FormData and Content-Type is multipart/form-data without boundary,
// delete it so fetch can set it correctly with the boundary
if (utils$1.isFormData(data)) {
const contentType = headers.getContentType();
if (contentType && /^multipart\/form-data/i.test(contentType) && !/boundary=/i.test(contentType)) {
headers.delete('content-type');
}
}
// Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
headers.set('User-Agent', 'axios/' + VERSION, false);
const resolvedOptions = {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: toByteStringHeaderObject(headers.normalize()),
body: data,
duplex: 'half',
credentials: isCredentialsSupported ? withCredentials : undefined
};
request = isRequestSupported && new Request(url, resolvedOptions);
let response = await (isRequestSupported ? _fetch(request, fetchOptions) : _fetch(url, resolvedOptions));
const responseHeaders = AxiosHeaders.from(response.headers);
// Cheap pre-check: if the server honestly declares a content-length that
// already exceeds the cap, reject before we start streaming.
if (hasMaxContentLength) {
const declaredLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
if (declaredLength != null && declaredLength > maxContentLength) {
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
}
}
const isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (supportsResponseStream && response.body && (onDownloadProgress || hasMaxContentLength || isStreamResponse && unsubscribe)) {
const options = {};
['status', 'statusText', 'headers'].forEach(prop => {
options[prop] = response[prop];
});
const responseContentLength = utils$1.toFiniteNumber(responseHeaders.getContentLength());
const [onProgress, flush] = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [];
let bytesRead = 0;
const onChunkProgress = loadedBytes => {
if (hasMaxContentLength) {
bytesRead = loadedBytes;
if (bytesRead > maxContentLength) {
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
}
}
onProgress && onProgress(loadedBytes);
};
response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}), options);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
// Fallback enforcement for environments without ReadableStream support
// (legacy runtimes). Detect materialized size from typed output; skip
// streams/Response passthrough since the user will read those themselves.
if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
let materializedSize;
if (responseData != null) {
if (typeof responseData.byteLength === 'number') {
materializedSize = responseData.byteLength;
} else if (typeof responseData.size === 'number') {
materializedSize = responseData.size;
} else if (typeof responseData === 'string') {
materializedSize = typeof TextEncoder === 'function' ? new TextEncoder().encode(responseData).byteLength : responseData.length;
}
}
if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
throw new AxiosError('maxContentLength size of ' + maxContentLength + ' exceeded', AxiosError.ERR_BAD_RESPONSE, config, request);
}
}
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request
});
});
} catch (err) {
unsubscribe && unsubscribe();
// Safari can surface fetch aborts as a DOMException-like object whose
// branded getters throw. Prefer our composed signal reason before reading
// the caught error, preserving timeout vs cancellation semantics.
if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
const canceledError = composedSignal.reason;
canceledError.config = config;
request && (canceledError.request = request);
if (err !== canceledError) {
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(canceledError, 'cause', {
__proto__: null,
value: err,
writable: true,
enumerable: false,
configurable: true
});
}
throw canceledError;
}
// Surface a maxBodyLength violation we raised while the request body was
// being streamed. Matching by identity (rather than reading
// `err.cause.isAxiosError`) keeps the error deterministic across runtimes
// and avoids both prototype-pollution reads and mis-attributing a foreign
// AxiosError that merely happened to land in `err.cause`.
if (pendingBodyError) {
request && !pendingBodyError.request && (pendingBodyError.request = request);
throw pendingBodyError;
}
// Re-throw AxiosErrors we raised synchronously (data: URL / content-length
// pre-checks, response size enforcement) without re-wrapping them.
if (err instanceof AxiosError) {
request && !err.request && (err.request = request);
throw err;
}
if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
const networkError = new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, err && err.response);
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(networkError, 'cause', {
__proto__: null,
value: err.cause || err,
writable: true,
enumerable: false,
configurable: true
});
throw networkError;
}
throw AxiosError.from(err, err && err.code, config, request, err && err.response);
}
};
};
const seedCache = new Map();
const getFetch = config => {
let env = config && config.env || {};
const {
fetch,
Request,
Response
} = env;
const seeds = [Request, Response, fetch];
let len = seeds.length,
i = len,
seed,
target,
map = seedCache;
while (i--) {
seed = seeds[i];
target = map.get(seed);
target === undefined && map.set(seed, target = i ? new Map() : factory(env));
map = target;
}
return target;
};
getFetch();
/**
* Known adapters mapping.
* Provides environment-specific adapters for Axios:
* - `http` for Node.js
* - `xhr` for browsers
* - `fetch` for fetch API-based requests
*
* @type {Object<string, Function|Object>}
*/
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: {
get: getFetch
}
};
// Assign adapter names for easier debugging and identification
utils$1.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
// Null-proto descriptors so a polluted Object.prototype.get cannot turn
// these data descriptors into accessor descriptors on the way in.
Object.defineProperty(fn, 'name', {
__proto__: null,
value
});
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', {
__proto__: null,
value
});
}
});
/**
* Render a rejection reason string for unknown or unsupported adapters
*
* @param {string} reason
* @returns {string}
*/
const renderReason = reason => `- ${reason}`;
/**
* Check if the adapter is resolved (function, null, or false)
*
* @param {Function|null|false} adapter
* @returns {boolean}
*/
const isResolvedHandle = adapter => utils$1.isFunction(adapter) || adapter === null || adapter === false;
/**
* Get the first suitable adapter from the provided list.
* Tries each adapter in order until a supported one is found.
* Throws an AxiosError if no adapter is suitable.
*
* @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
* @param {Object} config - Axios request configuration
* @throws {AxiosError} If no suitable adapter is available
* @returns {Function} The resolved adapter function
*/
function getAdapter(adapters, config) {
adapters = utils$1.isArray(adapters) ? adapters : [adapters];
const {
length
} = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
}
if (adapter && (utils$1.isFunction(adapter) || (adapter = adapter.get(config)))) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons).map(([id, state]) => `adapter ${id} ` + (state === false ? 'is not supported by the environment' : 'is not available in the build'));
let s = length ? reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0]) : 'as no adapter specified';
throw new AxiosError(`There is no suitable adapter to dispatch the request ` + s, AxiosError.ERR_NOT_SUPPORT);
}
return adapter;
}
/**
* Exports Axios adapters and utility to resolve an adapter
*/
var adapters = {
/**
* Resolve an adapter from a list of adapter names or functions.
* @type {Function}
*/
getAdapter,
/**
* Exposes all known adapters
* @type {Object<string, Function|Object>}
*/
adapters: knownAdapters
};
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders.from(config.headers);
// Transform request data
config.data = transformData.call(config, config.transformRequest);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Expose the current response on config so that transformResponse can
// attach it to any AxiosError it throws (e.g. on JSON parse failure).
// We clean it up afterwards to avoid polluting the config object.
config.response = response;
try {
response.data = transformData.call(config, config.transformResponse, response);
} finally {
delete config.response;
}
response.headers = AxiosHeaders.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
config.response = reason.response;
try {
reason.response.data = transformData.call(config, config.transformResponse, reason.response);
} finally {
delete config.response;
}
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
}
const validators$1 = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators$1[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
const deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators$1.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return '[Axios v' + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? '. ' + message : '');
}
// eslint-disable-next-line func-names
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), AxiosError.ERR_DEPRECATED);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(formatMessage(opt, ' has been deprecated since v' + version + ' and will be removed in the near future'));
}
return validator ? validator(value, opt, opts) : true;
};
};
validators$1.spelling = function spelling(correctSpelling) {
return (value, opt) => {
// eslint-disable-next-line no-console
console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
return true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object' || options === null) {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
// Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
// a non-function validator and cause a TypeError.
const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
if (validator) {
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
var validator = {
assertOptions,
validators: validators$1
};
const validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig || {};
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : dummy = new Error();
// slice off the Error: ... line
const stack = (() => {
if (!dummy.stack) {
return '';
}
const firstNewlineIndex = dummy.stack.indexOf('\n');
return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
})();
try {
if (!err.stack) {
err.stack = stack;
// match without the 2 top stack lines
} else if (stack) {
const firstNewlineIndex = stack.indexOf('\n');
const secondNewlineIndex = firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
const stackWithoutTwoTopLines = secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
err.stack += '\n' + stack;
}
}
} catch (e) {
// ignore the case where "stack" is an un-writable property
}
}
throw err;
}
}
_request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
const {
transitional,
paramsSerializer,
headers
} = config;
if (transitional !== undefined) {
validator.assertOptions(transitional, {
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean),
legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
validateStatusUndefinedResolves: validators.transitional(validators.boolean)
}, false);
}
if (paramsSerializer != null) {
if (utils$1.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer
};
} else {
validator.assertOptions(paramsSerializer, {
encode: validators.function,
serialize: validators.function
}, true);
}
}
// Set config.allowAbsoluteUrls
if (config.allowAbsoluteUrls !== undefined) ; else if (this.defaults.allowAbsoluteUrls !== undefined) {
config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
} else {
config.allowAbsoluteUrls = true;
}
validator.assertOptions(config, {
baseUrl: validators.spelling('baseURL'),
withXsrfToken: validators.spelling('withXSRFToken')
}, true);
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
let contextHeaders = headers && utils$1.merge(headers.common, headers[config.method]);
headers && utils$1.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], method => {
delete headers[method];
});
config.headers = AxiosHeaders.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
const transitional = config.transitional || transitionalDefaults;
const legacyInterceptorReqResOrdering = transitional && transitional.legacyInterceptorReqResOrdering;
if (legacyInterceptorReqResOrdering) {
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
} else {
requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
}
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift(...requestInterceptorChain);
chain.push(...responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}
// Provide aliases for supported request methods
utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function (url, config) {
return this.request(mergeConfig(config || {}, {
method,
url,
data: config && utils$1.hasOwnProp(config, 'data') ? config.data : undefined
}));
};
});
utils$1.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(mergeConfig(config || {}, {
method,
headers: isForm ? {
'Content-Type': 'multipart/form-data'
} : {},
url,
data
}));
};
}
Axios.prototype[method] = generateHTTPMethod();
// QUERY is a safe/idempotent read method; multipart form bodies don't fit
// its semantics, so no queryForm shorthand is generated.
if (method !== 'query') {
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
}
});
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then(cancel => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = onfulfilled => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise(resolve => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
toAbortSignal() {
const controller = new AbortController();
const abort = err => {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel
};
}
}
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* const args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
function isAxiosError(payload) {
return utils$1.isObject(payload) && payload.isAxiosError === true;
}
const HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
WebServerIsDown: 521,
ConnectionTimedOut: 522,
OriginIsUnreachable: 523,
TimeoutOccurred: 524,
SslHandshakeFailed: 525,
InvalidSslCertificate: 526
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios(defaultConfig);
const instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils$1.extend(instance, Axios.prototype, context, {
allOwnKeys: true
});
// Copy context to instance
utils$1.extend(instance, context, null, {
allOwnKeys: true
});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders;
axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode;
axios.default = axios;
module.exports = axios;
//# sourceMappingURL=axios.cjs.map
+738
View File
@@ -0,0 +1,738 @@
type MethodsHeaders = Partial<
{
[Key in axios.Method as Lowercase<Key>]: AxiosHeaders;
} & { common: AxiosHeaders }
>;
type AxiosHeaderMatcher =
| string
| RegExp
| ((this: AxiosHeaders, value: string, name: string) => boolean);
type AxiosHeaderParser = (this: AxiosHeaders, value: axios.AxiosHeaderValue, header: string) => any;
type CommonRequestHeadersList =
| 'Accept'
| 'Content-Length'
| 'User-Agent'
| 'Content-Encoding'
| 'Authorization'
| 'Location';
type ContentType =
| axios.AxiosHeaderValue
| 'text/html'
| 'text/plain'
| 'multipart/form-data'
| 'application/json'
| 'application/x-www-form-urlencoded'
| 'application/octet-stream';
type CommonResponseHeadersList =
| 'Server'
| 'Content-Type'
| 'Content-Length'
| 'Cache-Control'
| 'Content-Encoding';
type CommonResponseHeaderKey = CommonResponseHeadersList | Lowercase<CommonResponseHeadersList>;
type BrowserProgressEvent = any;
declare class AxiosHeaders {
constructor(headers?: axios.RawAxiosHeaders | AxiosHeaders | string);
[key: string]: any;
set(
headerName?: string,
value?: axios.AxiosHeaderValue,
rewrite?: boolean | AxiosHeaderMatcher
): AxiosHeaders;
set(headers?: axios.RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
set(headers?: Iterable<[string, axios.AxiosHeaderValue]>, rewrite?: boolean): AxiosHeaders;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderParser): axios.AxiosHeaderValue;
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
clear(matcher?: AxiosHeaderMatcher): boolean;
normalize(format: boolean): AxiosHeaders;
concat(
...targets: Array<AxiosHeaders | axios.RawAxiosHeaders | string | undefined | null>
): AxiosHeaders;
toJSON(asStrings: true): Record<string, string>;
toJSON(asStrings?: false): Record<string, string | string[]>;
toJSON(asStrings?: boolean): Record<string, string | string[]>;
static from(thing?: AxiosHeaders | axios.RawAxiosHeaders | string): AxiosHeaders;
static accessor(header: string | string[]): AxiosHeaders;
static concat(
...targets: Array<AxiosHeaders | axios.RawAxiosHeaders | string | undefined | null>
): AxiosHeaders;
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentType(parser?: RegExp): RegExpExecArray | null;
getContentType(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
setContentLength(
value: axios.AxiosHeaderValue,
rewrite?: boolean | AxiosHeaderMatcher
): AxiosHeaders;
getContentLength(parser?: RegExp): RegExpExecArray | null;
getContentLength(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
setAccept(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAccept(parser?: RegExp): RegExpExecArray | null;
getAccept(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
setUserAgent(value: axios.AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getUserAgent(parser?: RegExp): RegExpExecArray | null;
getUserAgent(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
setContentEncoding(
value: axios.AxiosHeaderValue,
rewrite?: boolean | AxiosHeaderMatcher
): AxiosHeaders;
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
getContentEncoding(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
setAuthorization(
value: axios.AxiosHeaderValue,
rewrite?: boolean | AxiosHeaderMatcher
): AxiosHeaders;
getAuthorization(parser?: RegExp): RegExpExecArray | null;
getAuthorization(matcher?: AxiosHeaderMatcher): axios.AxiosHeaderValue;
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
getSetCookie(): string[];
toString(): string;
[Symbol.iterator](): IterableIterator<[string, axios.AxiosHeaderValue]>;
}
declare class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: axios.InternalAxiosRequestConfig<D>,
request?: any,
response?: axios.AxiosResponse<T, D>
);
config?: axios.InternalAxiosRequestConfig<D>;
code?: string;
request?: any;
response?: axios.AxiosResponse<T, D>;
isAxiosError: boolean;
status?: number;
toJSON: () => object;
cause?: Error;
event?: BrowserProgressEvent;
static from<T = unknown, D = any>(
error: Error | unknown,
code?: string,
config?: axios.InternalAxiosRequestConfig<D>,
request?: any,
response?: axios.AxiosResponse<T, D>,
customProps?: object
): AxiosError<T, D>;
static readonly ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
static readonly ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
static readonly ERR_BAD_OPTION = 'ERR_BAD_OPTION';
static readonly ERR_NETWORK = 'ERR_NETWORK';
static readonly ERR_DEPRECATED = 'ERR_DEPRECATED';
static readonly ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
static readonly ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
static readonly ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
static readonly ERR_INVALID_URL = 'ERR_INVALID_URL';
static readonly ERR_CANCELED = 'ERR_CANCELED';
static readonly ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
static readonly ECONNABORTED = 'ECONNABORTED';
static readonly ECONNREFUSED = 'ECONNREFUSED';
static readonly ETIMEDOUT = 'ETIMEDOUT';
}
declare class CanceledError<T> extends AxiosError<T> {
constructor(message?: string, config?: axios.InternalAxiosRequestConfig, request?: any);
readonly name: 'CanceledError';
__CANCEL__?: boolean;
}
declare class Axios {
constructor(config?: axios.AxiosRequestConfig);
defaults: axios.AxiosDefaults;
interceptors: {
request: axios.AxiosInterceptorManager<axios.InternalAxiosRequestConfig>;
response: axios.AxiosInterceptorManager<axios.AxiosResponse>;
};
getUri(config?: axios.AxiosRequestConfig): string;
request<T = any, R = axios.AxiosResponse<T>, D = any>(
config: axios.AxiosRequestConfig<D>
): Promise<R>;
get<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
delete<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
head<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
options<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
post<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
put<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
patch<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
postForm<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
putForm<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
patchForm<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
query<T = any, R = axios.AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: axios.AxiosRequestConfig<D>
): Promise<R>;
}
declare enum HttpStatusCode {
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
Ok = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
ImUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
Unused = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
UriTooLong = 414,
UnsupportedMediaType = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
ImATeapot = 418,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
TooEarly = 425,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511,
WebServerIsDown = 521,
ConnectionTimedOut = 522,
OriginIsUnreachable = 523,
TimeoutOccurred = 524,
SslHandshakeFailed = 525,
InvalidSslCertificate = 526,
}
type InternalAxiosError<T = unknown, D = any> = AxiosError<T, D>;
declare namespace axios {
type AxiosError<T = unknown, D = any> = InternalAxiosError<T, D>;
interface RawAxiosHeaders {
[key: string]: AxiosHeaderValue;
}
type RawAxiosRequestHeaders = Partial<
RawAxiosHeaders & {
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
} & {
'Content-Type': ContentType;
}
>;
type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
type RawCommonResponseHeaders = {
[Key in CommonResponseHeaderKey]: AxiosHeaderValue;
} & {
'set-cookie': string[];
};
type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
interface AxiosRequestTransformer {
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
}
interface AxiosResponseTransformer {
(
this: InternalAxiosRequestConfig,
data: any,
headers: AxiosResponseHeaders,
status?: number
): any;
}
interface AxiosAdapter {
(config: InternalAxiosRequestConfig): AxiosPromise;
}
interface AxiosBasicCredentials {
username: string;
password: string;
}
interface AxiosProxyConfig {
host: string;
port: number;
auth?: AxiosBasicCredentials;
protocol?: string;
}
type UppercaseMethod =
| 'GET'
| 'DELETE'
| 'HEAD'
| 'OPTIONS'
| 'POST'
| 'PUT'
| 'PATCH'
| 'PURGE'
| 'LINK'
| 'UNLINK'
| 'QUERY';
type Method = (UppercaseMethod | Lowercase<UppercaseMethod>) & {};
type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' | 'formdata';
type UppercaseResponseEncoding =
| 'ASCII'
| 'ANSI'
| 'BINARY'
| 'BASE64'
| 'BASE64URL'
| 'HEX'
| 'LATIN1'
| 'UCS-2'
| 'UCS2'
| 'UTF-8'
| 'UTF8'
| 'UTF16LE';
type responseEncoding = (UppercaseResponseEncoding | Lowercase<UppercaseResponseEncoding>) & {};
interface TransitionalOptions {
silentJSONParsing?: boolean;
forcedJSONParsing?: boolean;
clarifyTimeoutError?: boolean;
legacyInterceptorReqResOrdering?: boolean;
advertiseZstdAcceptEncoding?: boolean;
validateStatusUndefinedResolves?: boolean;
}
interface GenericAbortSignal {
readonly aborted: boolean;
onabort?: ((...args: any) => any) | null;
addEventListener?: (...args: any) => any;
removeEventListener?: (...args: any) => any;
}
interface FormDataVisitorHelpers {
defaultVisitor: SerializerVisitor;
convertValue: (value: any) => any;
isVisitable: (value: any) => boolean;
}
interface SerializerVisitor {
(
this: GenericFormData,
value: any,
key: string | number,
path: null | Array<string | number>,
helpers: FormDataVisitorHelpers
): boolean;
}
interface SerializerOptions {
visitor?: SerializerVisitor;
dots?: boolean;
metaTokens?: boolean;
indexes?: boolean | null;
maxDepth?: number;
Blob?: { new (...args: any[]): any };
}
// tslint:disable-next-line
interface FormSerializerOptions extends SerializerOptions {}
interface ParamEncoder {
(value: any, defaultEncoder: (value: any) => any): any;
}
interface CustomParamsSerializer {
(params: Record<string, any>, options?: ParamsSerializerOptions): string;
}
interface ParamsSerializerOptions extends SerializerOptions {
encode?: ParamEncoder;
serialize?: CustomParamsSerializer;
}
type MaxUploadRate = number;
type MaxDownloadRate = number;
interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
lengthComputable: boolean;
}
type Milliseconds = number;
type AxiosAdapterName = 'fetch' | 'xhr' | 'http' | (string & {});
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
type AddressFamily = 4 | 6 | undefined;
interface LookupAddressEntry {
address: string;
family?: AddressFamily;
}
type LookupAddress = string | LookupAddressEntry;
interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
allowAbsoluteUrls?: boolean;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
data?: D;
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (
options: Record<string, any>,
responseDetails: { headers: Record<string, string>; statusCode: HttpStatusCode },
requestDetails: { headers: Record<string, string>; url: string; method: string },
) => void;
socketPath?: string | null;
allowedSocketPaths?: string | string[] | null;
transport?: any;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken | undefined;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
fetch?: (input: URL | Request | string, init?: RequestInit) => Promise<Response>;
Request?: new (input: URL | Request | string, init?: RequestInit) => Request;
Response?: new (
body?: ArrayBuffer | ArrayBufferView | Blob | FormData | URLSearchParams | string | null,
init?: ResponseInit
) => Response;
};
formSerializer?: FormSerializerOptions;
family?: AddressFamily;
lookup?:
| ((
hostname: string,
options: object,
cb: (
err: Error | null,
address: LookupAddress | LookupAddress[],
family?: AddressFamily
) => void
) => void)
| ((
hostname: string,
options: object
) => Promise<
| [address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily]
| LookupAddress
>);
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
parseReviver?: (this: any, key: string, value: any, context?: { source?: string }) => any;
fetchOptions?:
| Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'>
| Record<string, any>;
httpVersion?: 1 | 2;
http2Options?: Record<string, any> & {
sessionTimeout?: number;
};
formDataHeaderPolicy?: 'legacy' | 'content-only';
redact?: string[];
sensitiveHeaders?: string[];
}
// Alias
type RawAxiosRequestConfig<D = any> = AxiosRequestConfig<D>;
interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
headers: AxiosRequestHeaders;
}
interface HeadersDefaults {
common: RawAxiosRequestHeaders;
delete: RawAxiosRequestHeaders;
get: RawAxiosRequestHeaders;
head: RawAxiosRequestHeaders;
post: RawAxiosRequestHeaders;
put: RawAxiosRequestHeaders;
patch: RawAxiosRequestHeaders;
options?: RawAxiosRequestHeaders;
purge?: RawAxiosRequestHeaders;
link?: RawAxiosRequestHeaders;
unlink?: RawAxiosRequestHeaders;
query?: RawAxiosRequestHeaders;
}
interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers: HeadersDefaults;
}
interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
}
interface AxiosResponse<T = any, D = any, H = {}> {
data: T;
status: number;
statusText: string;
headers: (H & RawAxiosResponseHeaders) | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
}
type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;
interface CancelStatic {
new (message?: string): Cancel;
}
interface Cancel {
message: string | undefined;
}
interface Canceler {
(message?: string, config?: AxiosRequestConfig, request?: any): void;
}
interface CancelTokenStatic {
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
}
interface CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
subscribe(listener: (cancel: Cancel | any) => void): void;
unsubscribe(listener: (cancel: Cancel | any) => void): void;
toAbortSignal(): AbortSignal;
}
interface CancelTokenSource {
token: CancelToken;
cancel: Canceler;
}
interface AxiosInterceptorOptions {
synchronous?: boolean;
runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null;
}
type AxiosInterceptorFulfilled<T> = (value: T) => T | Promise<T>;
type AxiosInterceptorRejected = (error: any) => any;
type AxiosRequestInterceptorUse<T> = (
onFulfilled?: AxiosInterceptorFulfilled<T> | null,
onRejected?: AxiosInterceptorRejected | null,
options?: AxiosInterceptorOptions
) => number;
type AxiosResponseInterceptorUse<T> = (
onFulfilled?: AxiosInterceptorFulfilled<T> | null,
onRejected?: AxiosInterceptorRejected | null
) => number;
interface AxiosInterceptorHandler<T> {
fulfilled: AxiosInterceptorFulfilled<T>;
rejected?: AxiosInterceptorRejected;
synchronous: boolean;
runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null;
}
interface AxiosInterceptorManager<V> {
use: V extends AxiosResponse ? AxiosResponseInterceptorUse<V> : AxiosRequestInterceptorUse<V>;
eject(id: number): void;
clear(): void;
handlers?: Array<AxiosInterceptorHandler<V>>;
}
interface AxiosInstance extends Axios {
<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
<T = any, R = AxiosResponse<T>, D = any>(
url: string,
config?: AxiosRequestConfig<D>
): Promise<R>;
create(config?: CreateAxiosDefaults): AxiosInstance;
defaults: Omit<AxiosDefaults, 'headers'> & {
headers: HeadersDefaults & {
[key: string]: AxiosHeaderValue;
};
};
}
interface GenericFormData {
append(name: string, value: any, options?: any): any;
}
interface GenericHTMLFormElement {
name: string;
method: string;
submit(): void;
}
interface AxiosStatic extends AxiosInstance {
Cancel: typeof CanceledError;
CancelToken: CancelTokenStatic;
Axios: typeof Axios;
AxiosError: typeof AxiosError;
CanceledError: typeof CanceledError;
HttpStatusCode: typeof HttpStatusCode;
readonly VERSION: string;
isCancel<T = any>(value: any): value is CanceledError<T>;
all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
toFormData(
sourceObj: object,
targetFormData?: GenericFormData,
options?: FormSerializerOptions
): GenericFormData;
formToJSON(form: GenericFormData | GenericHTMLFormElement): object;
getAdapter(adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined): AxiosAdapter;
AxiosHeaders: typeof AxiosHeaders;
mergeConfig<D = any>(
config1: AxiosRequestConfig<D>,
config2: AxiosRequestConfig<D>
): AxiosRequestConfig<D>;
}
}
declare const axios: axios.AxiosStatic;
export = axios;
+755
View File
@@ -0,0 +1,755 @@
// TypeScript Version: 4.7
type StringLiteralsOrString<Literals extends string> = Literals | (string & {});
export type AxiosHeaderValue = AxiosHeaders | string | string[] | number | boolean | null;
export interface RawAxiosHeaders {
[key: string]: AxiosHeaderValue;
}
type MethodsHeaders = Partial<
{
[Key in Method as Lowercase<Key>]: AxiosHeaders;
} & { common: AxiosHeaders }
>;
type AxiosHeaderMatcher =
| string
| RegExp
| ((this: AxiosHeaders, value: string, name: string) => boolean);
type AxiosHeaderParser = (this: AxiosHeaders, value: AxiosHeaderValue, header: string) => any;
export class AxiosHeaders {
constructor(headers?: RawAxiosHeaders | AxiosHeaders | string);
[key: string]: any;
set(
headerName?: string,
value?: AxiosHeaderValue,
rewrite?: boolean | AxiosHeaderMatcher
): AxiosHeaders;
set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;
set(headers?: Iterable<[string, AxiosHeaderValue]>, rewrite?: boolean): AxiosHeaders;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;
has(header: string, matcher?: AxiosHeaderMatcher): boolean;
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
clear(matcher?: AxiosHeaderMatcher): boolean;
normalize(format: boolean): AxiosHeaders;
concat(
...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>
): AxiosHeaders;
toJSON(asStrings: true): Record<string, string>;
toJSON(asStrings?: false): Record<string, string | string[]>;
toJSON(asStrings?: boolean): Record<string, string | string[]>;
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
static accessor(header: string | string[]): AxiosHeaders;
static concat(
...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>
): AxiosHeaders;
setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentType(parser?: RegExp): RegExpExecArray | null;
getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentType(matcher?: AxiosHeaderMatcher): boolean;
setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentLength(parser?: RegExp): RegExpExecArray | null;
getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentLength(matcher?: AxiosHeaderMatcher): boolean;
setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAccept(parser?: RegExp): RegExpExecArray | null;
getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasAccept(matcher?: AxiosHeaderMatcher): boolean;
setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getUserAgent(parser?: RegExp): RegExpExecArray | null;
getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;
setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getContentEncoding(parser?: RegExp): RegExpExecArray | null;
getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;
setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
getAuthorization(parser?: RegExp): RegExpExecArray | null;
getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;
getSetCookie(): string[];
toString(): string;
[Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;
}
type CommonRequestHeadersList =
| 'Accept'
| 'Content-Length'
| 'User-Agent'
| 'Content-Encoding'
| 'Authorization'
| 'Location';
type ContentType =
| AxiosHeaderValue
| 'text/html'
| 'text/plain'
| 'multipart/form-data'
| 'application/json'
| 'application/x-www-form-urlencoded'
| 'application/octet-stream';
export type RawAxiosRequestHeaders = Partial<
RawAxiosHeaders & {
[Key in CommonRequestHeadersList]: AxiosHeaderValue;
} & {
'Content-Type': ContentType;
}
>;
export type AxiosRequestHeaders = RawAxiosRequestHeaders & AxiosHeaders;
type CommonResponseHeadersList =
| 'Server'
| 'Content-Type'
| 'Content-Length'
| 'Cache-Control'
| 'Content-Encoding';
type CommonResponseHeaderKey = CommonResponseHeadersList | Lowercase<CommonResponseHeadersList>;
type RawCommonResponseHeaders = {
[Key in CommonResponseHeaderKey]: AxiosHeaderValue;
} & {
'set-cookie': string[];
};
export type RawAxiosResponseHeaders = Partial<RawAxiosHeaders & RawCommonResponseHeaders>;
export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
export interface AxiosRequestTransformer {
(this: InternalAxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
}
export interface AxiosResponseTransformer {
(
this: InternalAxiosRequestConfig,
data: any,
headers: AxiosResponseHeaders,
status?: number
): any;
}
export interface AxiosAdapter {
(config: InternalAxiosRequestConfig): AxiosPromise;
}
export interface AxiosBasicCredentials {
username: string;
password: string;
}
export interface AxiosProxyConfig {
host: string;
port: number;
auth?: AxiosBasicCredentials;
protocol?: string;
}
export enum HttpStatusCode {
Continue = 100,
SwitchingProtocols = 101,
Processing = 102,
EarlyHints = 103,
Ok = 200,
Created = 201,
Accepted = 202,
NonAuthoritativeInformation = 203,
NoContent = 204,
ResetContent = 205,
PartialContent = 206,
MultiStatus = 207,
AlreadyReported = 208,
ImUsed = 226,
MultipleChoices = 300,
MovedPermanently = 301,
Found = 302,
SeeOther = 303,
NotModified = 304,
UseProxy = 305,
Unused = 306,
TemporaryRedirect = 307,
PermanentRedirect = 308,
BadRequest = 400,
Unauthorized = 401,
PaymentRequired = 402,
Forbidden = 403,
NotFound = 404,
MethodNotAllowed = 405,
NotAcceptable = 406,
ProxyAuthenticationRequired = 407,
RequestTimeout = 408,
Conflict = 409,
Gone = 410,
LengthRequired = 411,
PreconditionFailed = 412,
PayloadTooLarge = 413,
UriTooLong = 414,
UnsupportedMediaType = 415,
RangeNotSatisfiable = 416,
ExpectationFailed = 417,
ImATeapot = 418,
MisdirectedRequest = 421,
UnprocessableEntity = 422,
Locked = 423,
FailedDependency = 424,
TooEarly = 425,
UpgradeRequired = 426,
PreconditionRequired = 428,
TooManyRequests = 429,
RequestHeaderFieldsTooLarge = 431,
UnavailableForLegalReasons = 451,
InternalServerError = 500,
NotImplemented = 501,
BadGateway = 502,
ServiceUnavailable = 503,
GatewayTimeout = 504,
HttpVersionNotSupported = 505,
VariantAlsoNegotiates = 506,
InsufficientStorage = 507,
LoopDetected = 508,
NotExtended = 510,
NetworkAuthenticationRequired = 511,
WebServerIsDown = 521,
ConnectionTimedOut = 522,
OriginIsUnreachable = 523,
TimeoutOccurred = 524,
SslHandshakeFailed = 525,
InvalidSslCertificate = 526,
}
type UppercaseMethod =
| 'GET'
| 'DELETE'
| 'HEAD'
| 'OPTIONS'
| 'POST'
| 'PUT'
| 'PATCH'
| 'PURGE'
| 'LINK'
| 'UNLINK'
| 'QUERY';
export type Method = (UppercaseMethod | Lowercase<UppercaseMethod>) & {};
export type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream'
| 'formdata';
type UppercaseResponseEncoding =
| 'ASCII'
| 'ANSI'
| 'BINARY'
| 'BASE64'
| 'BASE64URL'
| 'HEX'
| 'LATIN1'
| 'UCS-2'
| 'UCS2'
| 'UTF-8'
| 'UTF8'
| 'UTF16LE';
export type responseEncoding = (
| UppercaseResponseEncoding
| Lowercase<UppercaseResponseEncoding>
) & {};
export interface TransitionalOptions {
silentJSONParsing?: boolean;
forcedJSONParsing?: boolean;
clarifyTimeoutError?: boolean;
legacyInterceptorReqResOrdering?: boolean;
advertiseZstdAcceptEncoding?: boolean;
validateStatusUndefinedResolves?: boolean;
}
export interface GenericAbortSignal {
readonly aborted: boolean;
onabort?: ((...args: any) => any) | null;
addEventListener?: (...args: any) => any;
removeEventListener?: (...args: any) => any;
}
export interface FormDataVisitorHelpers {
defaultVisitor: SerializerVisitor;
convertValue: (value: any) => any;
isVisitable: (value: any) => boolean;
}
export interface SerializerVisitor {
(
this: GenericFormData,
value: any,
key: string | number,
path: null | Array<string | number>,
helpers: FormDataVisitorHelpers
): boolean;
}
export interface SerializerOptions {
visitor?: SerializerVisitor;
dots?: boolean;
metaTokens?: boolean;
indexes?: boolean | null;
maxDepth?: number;
Blob?: { new (...args: any[]): any };
}
// tslint:disable-next-line
export interface FormSerializerOptions extends SerializerOptions {}
export interface ParamEncoder {
(value: any, defaultEncoder: (value: any) => any): any;
}
export interface CustomParamsSerializer {
(params: Record<string, any>, options?: ParamsSerializerOptions): string;
}
export interface ParamsSerializerOptions extends SerializerOptions {
encode?: ParamEncoder;
serialize?: CustomParamsSerializer;
}
type MaxUploadRate = number;
type MaxDownloadRate = number;
type BrowserProgressEvent = any;
export interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
event?: BrowserProgressEvent;
lengthComputable: boolean;
}
type Milliseconds = number;
type AxiosAdapterName = StringLiteralsOrString<'xhr' | 'http' | 'fetch'>;
type AxiosAdapterConfig = AxiosAdapter | AxiosAdapterName;
export type AddressFamily = 4 | 6 | undefined;
export interface LookupAddressEntry {
address: string;
family?: AddressFamily;
}
export type LookupAddress = string | LookupAddressEntry;
export interface AxiosRequestConfig<D = any> {
url?: string;
method?: StringLiteralsOrString<Method>;
baseURL?: string;
allowAbsoluteUrls?: boolean;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: (RawAxiosRequestHeaders & MethodsHeaders) | AxiosHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions | CustomParamsSerializer;
data?: D;
timeout?: Milliseconds;
timeoutErrorMessage?: string;
withCredentials?: boolean;
adapter?: AxiosAdapterConfig | AxiosAdapterConfig[];
auth?: AxiosBasicCredentials;
responseType?: ResponseType;
responseEncoding?: StringLiteralsOrString<responseEncoding>;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (
options: Record<string, any>,
responseDetails: {
headers: Record<string, string>;
statusCode: HttpStatusCode;
},
requestDetails: {
headers: Record<string, string>;
url: string;
method: string;
},
) => void;
socketPath?: string | null;
allowedSocketPaths?: string | string[] | null;
transport?: any;
httpAgent?: any;
httpsAgent?: any;
proxy?: AxiosProxyConfig | false;
cancelToken?: CancelToken | undefined;
decompress?: boolean;
transitional?: TransitionalOptions;
signal?: GenericAbortSignal;
insecureHTTPParser?: boolean;
env?: {
FormData?: new (...args: any[]) => object;
fetch?: (input: URL | Request | string, init?: RequestInit) => Promise<Response>;
Request?: new (input: URL | Request | string, init?: RequestInit) => Request;
Response?: new (
body?: ArrayBuffer | ArrayBufferView | Blob | FormData | URLSearchParams | string | null,
init?: ResponseInit
) => Response;
};
formSerializer?: FormSerializerOptions;
family?: AddressFamily;
lookup?:
| ((
hostname: string,
options: object,
cb: (
err: Error | null,
address: LookupAddress | LookupAddress[],
family?: AddressFamily
) => void
) => void)
| ((
hostname: string,
options: object
) => Promise<
[address: LookupAddressEntry | LookupAddressEntry[], family?: AddressFamily] | LookupAddress
>);
withXSRFToken?: boolean | ((config: InternalAxiosRequestConfig) => boolean | undefined);
parseReviver?: (this: any, key: string, value: any, context?: { source?: string }) => any;
fetchOptions?: Omit<RequestInit, 'body' | 'headers' | 'method' | 'signal'> | Record<string, any>;
httpVersion?: 1 | 2;
http2Options?: Record<string, any> & {
sessionTimeout?: number;
};
formDataHeaderPolicy?: 'legacy' | 'content-only';
redact?: string[];
sensitiveHeaders?: string[];
}
// Alias
export type RawAxiosRequestConfig<D = any> = AxiosRequestConfig<D>;
export interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
headers: AxiosRequestHeaders;
}
export interface HeadersDefaults {
common: RawAxiosRequestHeaders;
delete: RawAxiosRequestHeaders;
get: RawAxiosRequestHeaders;
head: RawAxiosRequestHeaders;
post: RawAxiosRequestHeaders;
put: RawAxiosRequestHeaders;
patch: RawAxiosRequestHeaders;
options?: RawAxiosRequestHeaders;
purge?: RawAxiosRequestHeaders;
link?: RawAxiosRequestHeaders;
unlink?: RawAxiosRequestHeaders;
query?: RawAxiosRequestHeaders;
}
export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers: HeadersDefaults;
}
export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: RawAxiosRequestHeaders | AxiosHeaders | Partial<HeadersDefaults>;
}
export interface AxiosResponse<T = any, D = any, H = {}> {
data: T;
status: number;
statusText: string;
headers: (H & RawAxiosResponseHeaders) | AxiosResponseHeaders;
config: InternalAxiosRequestConfig<D>;
request?: any;
}
export class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>
);
config?: InternalAxiosRequestConfig<D>;
code?: string;
request?: any;
response?: AxiosResponse<T, D>;
isAxiosError: boolean;
status?: number;
toJSON: () => object;
cause?: Error;
event?: BrowserProgressEvent;
static from<T = unknown, D = any>(
error: Error | unknown,
code?: string,
config?: InternalAxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>,
customProps?: object
): AxiosError<T, D>;
static readonly ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
static readonly ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
static readonly ERR_BAD_OPTION = 'ERR_BAD_OPTION';
static readonly ERR_NETWORK = 'ERR_NETWORK';
static readonly ERR_DEPRECATED = 'ERR_DEPRECATED';
static readonly ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
static readonly ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
static readonly ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
static readonly ERR_INVALID_URL = 'ERR_INVALID_URL';
static readonly ERR_CANCELED = 'ERR_CANCELED';
static readonly ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
static readonly ECONNABORTED = 'ECONNABORTED';
static readonly ECONNREFUSED = 'ECONNREFUSED';
static readonly ETIMEDOUT = 'ETIMEDOUT';
}
export class CanceledError<T> extends AxiosError<T> {
constructor(message?: string, config?: InternalAxiosRequestConfig, request?: any);
readonly name: 'CanceledError';
__CANCEL__?: boolean;
}
export type AxiosPromise<T = any> = Promise<AxiosResponse<T>>;
export interface CancelStatic {
new (message?: string): Cancel;
}
export interface Cancel {
message: string | undefined;
}
export interface Canceler {
(message?: string, config?: AxiosRequestConfig, request?: any): void;
}
export interface CancelTokenStatic {
new (executor: (cancel: Canceler) => void): CancelToken;
source(): CancelTokenSource;
}
export interface CancelToken {
promise: Promise<Cancel>;
reason?: Cancel;
throwIfRequested(): void;
subscribe(listener: (cancel: Cancel | any) => void): void;
unsubscribe(listener: (cancel: Cancel | any) => void): void;
toAbortSignal(): AbortSignal;
}
export interface CancelTokenSource {
token: CancelToken;
cancel: Canceler;
}
export interface AxiosInterceptorOptions {
synchronous?: boolean;
runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null;
}
type AxiosInterceptorFulfilled<T> = (value: T) => T | Promise<T>;
type AxiosInterceptorRejected = (error: any) => any;
type AxiosRequestInterceptorUse<T> = (
onFulfilled?: AxiosInterceptorFulfilled<T> | null,
onRejected?: AxiosInterceptorRejected | null,
options?: AxiosInterceptorOptions
) => number;
type AxiosResponseInterceptorUse<T> = (
onFulfilled?: AxiosInterceptorFulfilled<T> | null,
onRejected?: AxiosInterceptorRejected | null
) => number;
interface AxiosInterceptorHandler<T> {
fulfilled: AxiosInterceptorFulfilled<T>;
rejected?: AxiosInterceptorRejected;
synchronous: boolean;
runWhen?: ((config: InternalAxiosRequestConfig) => boolean) | null;
}
export interface AxiosInterceptorManager<V> {
use: V extends AxiosResponse ? AxiosResponseInterceptorUse<V> : AxiosRequestInterceptorUse<V>;
eject(id: number): void;
clear(): void;
handlers?: Array<AxiosInterceptorHandler<V>>;
}
export class Axios {
constructor(config?: AxiosRequestConfig);
defaults: AxiosDefaults;
interceptors: {
request: AxiosInterceptorManager<InternalAxiosRequestConfig>;
response: AxiosInterceptorManager<AxiosResponse>;
};
getUri(config?: AxiosRequestConfig): string;
request<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
get<T = any, R = AxiosResponse<T>, D = any>(
url: string,
config?: AxiosRequestConfig<D>
): Promise<R>;
delete<T = any, R = AxiosResponse<T>, D = any>(
url: string,
config?: AxiosRequestConfig<D>
): Promise<R>;
head<T = any, R = AxiosResponse<T>, D = any>(
url: string,
config?: AxiosRequestConfig<D>
): Promise<R>;
options<T = any, R = AxiosResponse<T>, D = any>(
url: string,
config?: AxiosRequestConfig<D>
): Promise<R>;
post<T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
): Promise<R>;
put<T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
): Promise<R>;
patch<T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
): Promise<R>;
postForm<T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
): Promise<R>;
putForm<T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
): Promise<R>;
patchForm<T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
): Promise<R>;
query<T = any, R = AxiosResponse<T>, D = any>(
url: string,
data?: D,
config?: AxiosRequestConfig<D>
): Promise<R>;
}
export interface AxiosInstance extends Axios {
<T = any, R = AxiosResponse<T>, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
<T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
create(config?: CreateAxiosDefaults): AxiosInstance;
defaults: Omit<AxiosDefaults, 'headers'> & {
headers: HeadersDefaults & {
[key: string]: AxiosHeaderValue;
};
};
}
export interface GenericFormData {
append(name: string, value: any, options?: any): any;
}
export interface GenericHTMLFormElement {
name: string;
method: string;
submit(): void;
}
export function getAdapter(
adapters: AxiosAdapterConfig | AxiosAdapterConfig[] | undefined
): AxiosAdapter;
export function toFormData(
sourceObj: object,
targetFormData?: GenericFormData,
options?: FormSerializerOptions
): GenericFormData;
export function formToJSON(form: GenericFormData | GenericHTMLFormElement): object;
export function isAxiosError<T = any, D = any>(payload: any): payload is AxiosError<T, D>;
export function spread<T, R>(callback: (...args: T[]) => R): (array: T[]) => R;
export function isCancel<T = any>(value: any): value is CanceledError<T>;
export function all<T>(values: Array<T | Promise<T>>): Promise<T[]>;
export function mergeConfig<D = any>(
config1: AxiosRequestConfig<D>,
config2: AxiosRequestConfig<D>
): AxiosRequestConfig<D>;
export function create(config?: CreateAxiosDefaults): AxiosInstance;
export interface AxiosStatic extends AxiosInstance {
Cancel: typeof CanceledError;
CancelToken: CancelTokenStatic;
Axios: typeof Axios;
AxiosError: typeof AxiosError;
HttpStatusCode: typeof HttpStatusCode;
readonly VERSION: string;
isCancel: typeof isCancel;
all: typeof all;
spread: typeof spread;
isAxiosError: typeof isAxiosError;
toFormData: typeof toFormData;
formToJSON: typeof formToJSON;
getAdapter: typeof getAdapter;
CanceledError: typeof CanceledError;
AxiosHeaders: typeof AxiosHeaders;
mergeConfig: typeof mergeConfig;
}
declare const axios: AxiosStatic;
export default axios;
+45
View File
@@ -0,0 +1,45 @@
import axios from './lib/axios.js';
// This module is intended to unwrap Axios default export as named.
// Keep top-level export same with static properties
// so that it can keep same with es module or cjs
const {
Axios,
AxiosError,
CanceledError,
isCancel,
CancelToken,
VERSION,
all,
Cancel,
isAxiosError,
spread,
toFormData,
AxiosHeaders,
HttpStatusCode,
formToJSON,
getAdapter,
mergeConfig,
create,
} = axios;
export {
axios as default,
create,
Axios,
AxiosError,
CanceledError,
isCancel,
CancelToken,
VERSION,
all,
Cancel,
isAxiosError,
spread,
toFormData,
AxiosHeaders,
HttpStatusCode,
formToJSON,
getAdapter,
mergeConfig,
};
+36
View File
@@ -0,0 +1,36 @@
# axios // adapters
The modules under `adapters/` are modules that handle dispatching a request and settling a returned `Promise` once a response is received.
## Example
```js
var settle = require('../core/settle');
module.exports = function myAdapter(config) {
// At this point:
// - config has been merged with defaults
// - request transformers have already run
// - request interceptors have already run
// Make the request using config provided
// Upon response settle the Promise
return new Promise(function (resolve, reject) {
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request,
};
settle(resolve, reject, response);
// From here:
// - response transformers will run
// - response interceptors will run
});
};
```
+132
View File
@@ -0,0 +1,132 @@
import utils from '../utils.js';
import httpAdapter from './http.js';
import xhrAdapter from './xhr.js';
import * as fetchAdapter from './fetch.js';
import AxiosError from '../core/AxiosError.js';
/**
* Known adapters mapping.
* Provides environment-specific adapters for Axios:
* - `http` for Node.js
* - `xhr` for browsers
* - `fetch` for fetch API-based requests
*
* @type {Object<string, Function|Object>}
*/
const knownAdapters = {
http: httpAdapter,
xhr: xhrAdapter,
fetch: {
get: fetchAdapter.getFetch,
},
};
// Assign adapter names for easier debugging and identification
utils.forEach(knownAdapters, (fn, value) => {
if (fn) {
try {
// Null-proto descriptors so a polluted Object.prototype.get cannot turn
// these data descriptors into accessor descriptors on the way in.
Object.defineProperty(fn, 'name', { __proto__: null, value });
} catch (e) {
// eslint-disable-next-line no-empty
}
Object.defineProperty(fn, 'adapterName', { __proto__: null, value });
}
});
/**
* Render a rejection reason string for unknown or unsupported adapters
*
* @param {string} reason
* @returns {string}
*/
const renderReason = (reason) => `- ${reason}`;
/**
* Check if the adapter is resolved (function, null, or false)
*
* @param {Function|null|false} adapter
* @returns {boolean}
*/
const isResolvedHandle = (adapter) =>
utils.isFunction(adapter) || adapter === null || adapter === false;
/**
* Get the first suitable adapter from the provided list.
* Tries each adapter in order until a supported one is found.
* Throws an AxiosError if no adapter is suitable.
*
* @param {Array<string|Function>|string|Function} adapters - Adapter(s) by name or function.
* @param {Object} config - Axios request configuration
* @throws {AxiosError} If no suitable adapter is available
* @returns {Function} The resolved adapter function
*/
function getAdapter(adapters, config) {
adapters = utils.isArray(adapters) ? adapters : [adapters];
const { length } = adapters;
let nameOrAdapter;
let adapter;
const rejectedReasons = {};
for (let i = 0; i < length; i++) {
nameOrAdapter = adapters[i];
let id;
adapter = nameOrAdapter;
if (!isResolvedHandle(nameOrAdapter)) {
adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()];
if (adapter === undefined) {
throw new AxiosError(`Unknown adapter '${id}'`);
}
}
if (adapter && (utils.isFunction(adapter) || (adapter = adapter.get(config)))) {
break;
}
rejectedReasons[id || '#' + i] = adapter;
}
if (!adapter) {
const reasons = Object.entries(rejectedReasons).map(
([id, state]) =>
`adapter ${id} ` +
(state === false ? 'is not supported by the environment' : 'is not available in the build')
);
let s = length
? reasons.length > 1
? 'since :\n' + reasons.map(renderReason).join('\n')
: ' ' + renderReason(reasons[0])
: 'as no adapter specified';
throw new AxiosError(
`There is no suitable adapter to dispatch the request ` + s,
AxiosError.ERR_NOT_SUPPORT
);
}
return adapter;
}
/**
* Exports Axios adapters and utility to resolve an adapter
*/
export default {
/**
* Resolve an adapter from a list of adapter names or functions.
* @type {Function}
*/
getAdapter,
/**
* Exposes all known adapters
* @type {Object<string, Function|Object>}
*/
adapters: knownAdapters,
};
+643
View File
@@ -0,0 +1,643 @@
import platform from '../platform/index.js';
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import composeSignals from '../helpers/composeSignals.js';
import { trackStream } from '../helpers/trackStream.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import {
progressEventReducer,
progressEventDecorator,
asyncDecorator,
} from '../helpers/progressEventReducer.js';
import resolveConfig from '../helpers/resolveConfig.js';
import settle from '../core/settle.js';
import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js';
import { VERSION } from '../env/data.js';
import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';
const DEFAULT_CHUNK_SIZE = 64 * 1024;
const { isFunction } = utils;
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8 = (str) =>
encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
// Decode before composing the `auth` option so credentials such as
// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
// original value for malformed input so a bad encoding never throws.
const decodeURIComponentSafe = (value) => {
if (!utils.isString(value)) {
return value;
}
try {
return decodeURIComponent(value);
} catch (error) {
return value;
}
};
const test = (fn, ...args) => {
try {
return !!fn(...args);
} catch (e) {
return false;
}
};
const maybeWithAuthCredentials = (url) => {
const protocolIndex = url.indexOf('://');
let urlToCheck = url;
if (protocolIndex !== -1) {
urlToCheck = urlToCheck.slice(protocolIndex + 3);
}
return urlToCheck.includes('@') || urlToCheck.includes(':');
};
const factory = (env) => {
const globalObject =
utils.global !== undefined && utils.global !== null
? utils.global
: globalThis;
const { ReadableStream, TextEncoder } = globalObject;
env = utils.merge.call(
{
skipUndefined: true,
},
{
Request: globalObject.Request,
Response: globalObject.Response,
},
env
);
const { fetch: envFetch, Request, Response } = env;
const isFetchSupported = envFetch ? isFunction(envFetch) : typeof fetch === 'function';
const isRequestSupported = isFunction(Request);
const isResponseSupported = isFunction(Response);
if (!isFetchSupported) {
return false;
}
const isReadableStreamSupported = isFetchSupported && isFunction(ReadableStream);
const encodeText =
isFetchSupported &&
(typeof TextEncoder === 'function'
? (
(encoder) => (str) =>
encoder.encode(str)
)(new TextEncoder())
: async (str) => new Uint8Array(await new Request(str).arrayBuffer()));
const supportsRequestStream =
isRequestSupported &&
isReadableStreamSupported &&
test(() => {
let duplexAccessed = false;
const request = new Request(platform.origin, {
body: new ReadableStream(),
method: 'POST',
get duplex() {
duplexAccessed = true;
return 'half';
},
});
const hasContentType = request.headers.has('Content-Type');
if (request.body != null) {
request.body.cancel();
}
return duplexAccessed && !hasContentType;
});
const supportsResponseStream =
isResponseSupported &&
isReadableStreamSupported &&
test(() => utils.isReadableStream(new Response('').body));
const resolvers = {
stream: supportsResponseStream && ((res) => res.body),
};
isFetchSupported &&
(() => {
['text', 'arrayBuffer', 'blob', 'formData', 'stream'].forEach((type) => {
!resolvers[type] &&
(resolvers[type] = (res, config) => {
let method = res && res[type];
if (method) {
return method.call(res);
}
throw new AxiosError(
`Response type '${type}' is not supported`,
AxiosError.ERR_NOT_SUPPORT,
config
);
});
});
})();
const getBodyLength = async (body) => {
if (body == null) {
return 0;
}
if (utils.isBlob(body)) {
return body.size;
}
if (utils.isSpecCompliantForm(body)) {
const _request = new Request(platform.origin, {
method: 'POST',
body,
});
return (await _request.arrayBuffer()).byteLength;
}
if (utils.isArrayBufferView(body) || utils.isArrayBuffer(body)) {
return body.byteLength;
}
if (utils.isURLSearchParams(body)) {
body = body + '';
}
if (utils.isString(body)) {
return (await encodeText(body)).byteLength;
}
};
const resolveBodyLength = async (headers, body) => {
const length = utils.toFiniteNumber(headers.getContentLength());
return length == null ? getBodyLength(body) : length;
};
return async (config) => {
let {
url,
method,
data,
signal,
cancelToken,
timeout,
onDownloadProgress,
onUploadProgress,
responseType,
headers,
withCredentials = 'same-origin',
fetchOptions,
maxContentLength,
maxBodyLength,
} = resolveConfig(config);
const hasMaxContentLength = utils.isNumber(maxContentLength) && maxContentLength > -1;
const hasMaxBodyLength = utils.isNumber(maxBodyLength) && maxBodyLength > -1;
const own = (key) => (utils.hasOwnProp(config, key) ? config[key] : undefined);
let _fetch = envFetch || fetch;
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
let composedSignal = composeSignals(
[signal, cancelToken && cancelToken.toAbortSignal()],
timeout
);
let request = null;
const unsubscribe =
composedSignal &&
composedSignal.unsubscribe &&
(() => {
composedSignal.unsubscribe();
});
let requestContentLength;
// AxiosError we raise while the request body is being streamed. Captured
// by identity so the catch block can surface it directly, regardless of
// how the runtime wraps the resulting fetch rejection (undici exposes it
// as `err.cause`; some browsers drop the original error entirely).
let pendingBodyError = null;
const maxBodyLengthError = () =>
new AxiosError(
'Request body larger than maxBodyLength limit',
AxiosError.ERR_BAD_REQUEST,
config,
request
);
try {
// HTTP basic authentication
let auth = undefined;
const configAuth = own('auth');
if (configAuth) {
const username = utils.getSafeProp(configAuth, 'username') || '';
const password = utils.getSafeProp(configAuth, 'password') || '';
auth = {
username,
password
};
}
if (maybeWithAuthCredentials(url)) {
const parsedURL = new URL(url, platform.origin);
if (!auth && (parsedURL.username || parsedURL.password)) {
const urlUsername = decodeURIComponentSafe(parsedURL.username);
const urlPassword = decodeURIComponentSafe(parsedURL.password);
auth = {
username: urlUsername,
password: urlPassword
};
}
if (parsedURL.username || parsedURL.password) {
parsedURL.username = '';
parsedURL.password = '';
url = parsedURL.href;
}
}
if (auth) {
headers.delete('authorization');
headers.set(
'Authorization',
'Basic ' + btoa(encodeUTF8((auth.username || '') + ':' + (auth.password || '')))
);
}
// Enforce maxContentLength for data: URLs up-front so we never materialize
// an oversized payload. The HTTP adapter applies the same check (see http.js
// "if (protocol === 'data:')" branch).
if (hasMaxContentLength && typeof url === 'string' && url.startsWith('data:')) {
const estimated = estimateDataURLDecodedBytes(url);
if (estimated > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
// Enforce maxBodyLength against known-size bodies before dispatch using
// the body's *actual* size — never a caller-declared Content-Length,
// which could under-report to slip an oversized body past the check.
// Unknown-size streams return undefined here and are counted per-chunk
// below as fetch consumes them.
if (hasMaxBodyLength && method !== 'get' && method !== 'head') {
const outboundLength = await getBodyLength(data);
if (typeof outboundLength === 'number' && isFinite(outboundLength)) {
requestContentLength = outboundLength;
if (outboundLength > maxBodyLength) {
throw maxBodyLengthError();
}
}
}
// A streamed body under maxBodyLength must be counted as fetch consumes
// it; its size is never trusted from a caller-declared Content-Length.
const mustEnforceStreamBody =
hasMaxBodyLength && (utils.isReadableStream(data) || utils.isStream(data));
const trackRequestStream = (stream, onProgress, flush) =>
trackStream(
stream,
DEFAULT_CHUNK_SIZE,
(loadedBytes) => {
if (hasMaxBodyLength && loadedBytes > maxBodyLength) {
throw (pendingBodyError = maxBodyLengthError());
}
onProgress && onProgress(loadedBytes);
},
flush
);
if (
supportsRequestStream &&
method !== 'get' &&
method !== 'head' &&
(onUploadProgress || mustEnforceStreamBody)
) {
requestContentLength =
requestContentLength == null ? await resolveBodyLength(headers, data) : requestContentLength;
// A declared length of 0 is only trusted to skip the wrap when we are
// not enforcing a stream limit (which must not rely on that header).
if (requestContentLength !== 0 || mustEnforceStreamBody) {
let _request = new Request(url, {
method: 'POST',
body: data,
duplex: 'half',
});
let contentTypeHeader;
if (utils.isFormData(data) && (contentTypeHeader = _request.headers.get('content-type'))) {
headers.setContentType(contentTypeHeader);
}
if (_request.body) {
const [onProgress, flush] =
(onUploadProgress &&
progressEventDecorator(
requestContentLength,
progressEventReducer(asyncDecorator(onUploadProgress))
)) ||
[];
data = trackRequestStream(_request.body, onProgress, flush);
}
}
} else if (
mustEnforceStreamBody &&
!isRequestSupported &&
isReadableStreamSupported &&
method !== 'get' &&
method !== 'head'
) {
data = trackRequestStream(data);
} else if (
mustEnforceStreamBody &&
isRequestSupported &&
!supportsRequestStream &&
method !== 'get' &&
method !== 'head'
) {
throw new AxiosError(
'Stream request bodies are not supported by the current fetch implementation',
AxiosError.ERR_NOT_SUPPORT,
config,
request
);
}
if (!utils.isString(withCredentials)) {
withCredentials = withCredentials ? 'include' : 'omit';
}
// Cloudflare Workers throws when credentials are defined
// see https://github.com/cloudflare/workerd/issues/902
const isCredentialsSupported = isRequestSupported && 'credentials' in Request.prototype;
// If data is FormData and Content-Type is multipart/form-data without boundary,
// delete it so fetch can set it correctly with the boundary
if (utils.isFormData(data)) {
const contentType = headers.getContentType();
if (
contentType &&
/^multipart\/form-data/i.test(contentType) &&
!/boundary=/i.test(contentType)
) {
headers.delete('content-type');
}
}
// Set User-Agent header if not already set (fetch defaults to 'node' in Node.js)
headers.set('User-Agent', 'axios/' + VERSION, false);
const resolvedOptions = {
...fetchOptions,
signal: composedSignal,
method: method.toUpperCase(),
headers: toByteStringHeaderObject(headers.normalize()),
body: data,
duplex: 'half',
credentials: isCredentialsSupported ? withCredentials : undefined,
};
request = isRequestSupported && new Request(url, resolvedOptions);
let response = await (isRequestSupported
? _fetch(request, fetchOptions)
: _fetch(url, resolvedOptions));
const responseHeaders = AxiosHeaders.from(response.headers);
// Cheap pre-check: if the server honestly declares a content-length that
// already exceeds the cap, reject before we start streaming.
if (hasMaxContentLength) {
const declaredLength = utils.toFiniteNumber(responseHeaders.getContentLength());
if (declaredLength != null && declaredLength > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
const isStreamResponse =
supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (
supportsResponseStream &&
response.body &&
(onDownloadProgress || hasMaxContentLength || (isStreamResponse && unsubscribe))
) {
const options = {};
['status', 'statusText', 'headers'].forEach((prop) => {
options[prop] = response[prop];
});
const responseContentLength = utils.toFiniteNumber(responseHeaders.getContentLength());
const [onProgress, flush] =
(onDownloadProgress &&
progressEventDecorator(
responseContentLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true)
)) ||
[];
let bytesRead = 0;
const onChunkProgress = (loadedBytes) => {
if (hasMaxContentLength) {
bytesRead = loadedBytes;
if (bytesRead > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
onProgress && onProgress(loadedBytes);
};
response = new Response(
trackStream(response.body, DEFAULT_CHUNK_SIZE, onChunkProgress, () => {
flush && flush();
unsubscribe && unsubscribe();
}),
options
);
}
responseType = responseType || 'text';
let responseData = await resolvers[utils.findKey(resolvers, responseType) || 'text'](
response,
config
);
// Fallback enforcement for environments without ReadableStream support
// (legacy runtimes). Detect materialized size from typed output; skip
// streams/Response passthrough since the user will read those themselves.
if (hasMaxContentLength && !supportsResponseStream && !isStreamResponse) {
let materializedSize;
if (responseData != null) {
if (typeof responseData.byteLength === 'number') {
materializedSize = responseData.byteLength;
} else if (typeof responseData.size === 'number') {
materializedSize = responseData.size;
} else if (typeof responseData === 'string') {
materializedSize =
typeof TextEncoder === 'function'
? new TextEncoder().encode(responseData).byteLength
: responseData.length;
}
}
if (typeof materializedSize === 'number' && materializedSize > maxContentLength) {
throw new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
request
);
}
}
!isStreamResponse && unsubscribe && unsubscribe();
return await new Promise((resolve, reject) => {
settle(resolve, reject, {
data: responseData,
headers: AxiosHeaders.from(response.headers),
status: response.status,
statusText: response.statusText,
config,
request,
});
});
} catch (err) {
unsubscribe && unsubscribe();
// Safari can surface fetch aborts as a DOMException-like object whose
// branded getters throw. Prefer our composed signal reason before reading
// the caught error, preserving timeout vs cancellation semantics.
if (composedSignal && composedSignal.aborted && composedSignal.reason instanceof AxiosError) {
const canceledError = composedSignal.reason;
canceledError.config = config;
request && (canceledError.request = request);
if (err !== canceledError) {
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(canceledError, 'cause', {
__proto__: null,
value: err,
writable: true,
enumerable: false,
configurable: true,
});
}
throw canceledError;
}
// Surface a maxBodyLength violation we raised while the request body was
// being streamed. Matching by identity (rather than reading
// `err.cause.isAxiosError`) keeps the error deterministic across runtimes
// and avoids both prototype-pollution reads and mis-attributing a foreign
// AxiosError that merely happened to land in `err.cause`.
if (pendingBodyError) {
request && !pendingBodyError.request && (pendingBodyError.request = request);
throw pendingBodyError;
}
// Re-throw AxiosErrors we raised synchronously (data: URL / content-length
// pre-checks, response size enforcement) without re-wrapping them.
if (err instanceof AxiosError) {
request && !err.request && (err.request = request);
throw err;
}
if (err && err.name === 'TypeError' && /Load failed|fetch/i.test(err.message)) {
const networkError = new AxiosError(
'Network Error',
AxiosError.ERR_NETWORK,
config,
request,
err && err.response
);
// Non-enumerable to match native Error `cause` semantics so loggers
// don't recurse into circular fetch internals (see #7205).
Object.defineProperty(networkError, 'cause', {
__proto__: null,
value: err.cause || err,
writable: true,
enumerable: false,
configurable: true,
});
throw networkError;
}
throw AxiosError.from(err, err && err.code, config, request, err && err.response);
}
};
};
const seedCache = new Map();
export const getFetch = (config) => {
let env = (config && config.env) || {};
const { fetch, Request, Response } = env;
const seeds = [Request, Response, fetch];
let len = seeds.length,
i = len,
seed,
target,
map = seedCache;
while (i--) {
seed = seeds[i];
target = map.get(seed);
target === undefined && map.set(seed, (target = i ? new Map() : factory(env)));
map = target;
}
return target;
};
const adapter = getFetch();
export default adapter;
Generated Vendored Executable
+1417
View File
@@ -0,0 +1,1417 @@
import utils from '../utils.js';
import settle from '../core/settle.js';
import buildFullPath from '../core/buildFullPath.js';
import buildURL from '../helpers/buildURL.js';
import { getProxyForUrl } from 'proxy-from-env';
import HttpsProxyAgent from 'https-proxy-agent';
import http from 'http';
import https from 'https';
import http2 from 'http2';
import util from 'util';
import { resolve as resolvePath } from 'path';
import followRedirects from 'follow-redirects';
import zlib from 'zlib';
import { VERSION } from '../env/data.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import platform from '../platform/index.js';
import fromDataURI from '../helpers/fromDataURI.js';
import stream from 'stream';
import AxiosHeaders from '../core/AxiosHeaders.js';
import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
import { EventEmitter } from 'events';
import formDataToStream from '../helpers/formDataToStream.js';
import readBlob from '../helpers/readBlob.js';
import ZlibHeaderTransformStream from '../helpers/ZlibHeaderTransformStream.js';
import Http2Sessions from '../helpers/Http2Sessions.js';
import callbackify from '../helpers/callbackify.js';
import shouldBypassProxy from '../helpers/shouldBypassProxy.js';
import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';
import {
progressEventReducer,
progressEventDecorator,
asyncDecorator,
} from '../helpers/progressEventReducer.js';
import estimateDataURLDecodedBytes from '../helpers/estimateDataURLDecodedBytes.js';
const zlibOptions = {
flush: zlib.constants.Z_SYNC_FLUSH,
finishFlush: zlib.constants.Z_SYNC_FLUSH,
};
const brotliOptions = {
flush: zlib.constants.BROTLI_OPERATION_FLUSH,
finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH,
};
const zstdOptions = {
flush: zlib.constants.ZSTD_e_flush,
finishFlush: zlib.constants.ZSTD_e_flush,
};
const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
const isZstdSupported = utils.isFunction(zlib.createZstdDecompress);
const ACCEPT_ENCODING = 'gzip, compress, deflate' + (isBrotliSupported ? ', br' : '');
const ACCEPT_ENCODING_WITH_ZSTD = ACCEPT_ENCODING + (isZstdSupported ? ', zstd' : '');
const { http: httpFollow, https: httpsFollow } = followRedirects;
const isHttps = /https:?/;
const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
function setFormDataHeaders(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders).forEach(([key, val]) => {
if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
// Symbols used to bind a single 'error' listener to a pooled socket and track
// the request currently owning that socket across keep-alive reuse (issue #10780).
const kAxiosSocketListener = Symbol('axios.http.socketListener');
const kAxiosCurrentReq = Symbol('axios.http.currentReq');
// Tags HttpsProxyAgent instances installed by setProxy() so the redirect path
// can strip them without clobbering a user-supplied agent that happens to be
// an HttpsProxyAgent.
const kAxiosInstalledTunnel = Symbol('axios.http.installedTunnel');
// Cache of CONNECT-tunneling agents keyed by proxy config so repeat requests
// through the same proxy reuse a single agent (and its socket pool). The
// keyspace is bounded by the set of distinct proxy configs the process uses,
// so unbounded growth is not a concern in practice.
const tunnelingAgentCache = new Map();
const tunnelingAgentCacheUser = new WeakMap();
// Minimum minor versions where Node's HTTP Agent supports native proxyEnv
// handling. Checking the selected agent below also covers startup modes such
// as NODE_OPTIONS=--use-env-proxy and --no-use-env-proxy precedence.
const NODE_NATIVE_ENV_PROXY_SUPPORT = {
22: 21,
24: 5,
};
function isNodeNativeEnvProxySupported(nodeVersion = process.versions && process.versions.node) {
if (!nodeVersion) {
return false;
}
const [major, minor] = nodeVersion.split('.').map((part) => Number(part));
if (!Number.isInteger(major) || !Number.isInteger(minor)) {
return false;
}
if (major > 24) {
return true;
}
return (
NODE_NATIVE_ENV_PROXY_SUPPORT[major] != null && minor >= NODE_NATIVE_ENV_PROXY_SUPPORT[major]
);
}
function isNodeEnvProxyEnabled(agent, nodeVersion = process.versions && process.versions.node) {
if (!isNodeNativeEnvProxySupported(nodeVersion)) {
return false;
}
const agentOptions = agent && agent.options;
return Boolean(
agentOptions &&
utils.hasOwnProp(agentOptions, 'proxyEnv') &&
agentOptions.proxyEnv != null
);
}
function getProxyEnvAgent(options, configHttpAgent, configHttpsAgent) {
return isHttps.test(options.protocol)
? (configHttpsAgent || https.globalAgent)
: (configHttpAgent || http.globalAgent);
}
function getTunnelingAgent(agentOptions, userHttpsAgent) {
const key =
agentOptions.protocol +
'//' +
agentOptions.hostname +
':' +
(agentOptions.port || '') +
'#' +
(agentOptions.auth || '');
const cache = userHttpsAgent
? (tunnelingAgentCacheUser.get(userHttpsAgent) ||
tunnelingAgentCacheUser.set(userHttpsAgent, new Map()).get(userHttpsAgent))
: tunnelingAgentCache;
let agent = cache.get(key);
if (agent) return agent;
// Forward the user's TLS options (custom CA, rejectUnauthorized, client cert,
// etc.) into the tunneling agent so they apply to the origin TLS upgrade
// performed after CONNECT. Our proxy fields take precedence on conflict.
const merged = userHttpsAgent && userHttpsAgent.options
? { ...userHttpsAgent.options, ...agentOptions }
: agentOptions;
agent = new HttpsProxyAgent(merged);
if (userHttpsAgent && userHttpsAgent.options) {
const originTLSOptions = { ...userHttpsAgent.options };
const callback = agent.callback;
agent.callback = function axiosTunnelingAgentCallback(req, opts) {
// HttpsProxyAgent v5 reads callback opts for the post-CONNECT origin TLS upgrade.
return callback.call(this, req, { ...originTLSOptions, ...opts });
};
}
agent[kAxiosInstalledTunnel] = true;
cache.set(key, agent);
return agent;
}
const supportedProtocols = platform.protocols.map((protocol) => {
return protocol + ':';
});
// Node's WHATWG URL parser returns `username` and `password` percent-encoded.
// Decode before composing the `auth` option so credentials such as
// `my%40email.com:pass` are sent as `my@email.com:pass`. Falls back to the
// original value for malformed input so a bad encoding never throws.
const decodeURIComponentSafe = (value) => {
if (!utils.isString(value)) {
return value;
}
try {
return decodeURIComponent(value);
} catch (error) {
return value;
}
};
const flushOnFinish = (stream, [throttled, flush]) => {
stream.on('end', flush).on('error', flush);
return throttled;
};
const http2Sessions = new Http2Sessions();
/**
* If the proxy, auth, sensitive header, or config beforeRedirects functions are defined,
* call them with the options object.
*
* @param {Object<string, any>} options - The options object that was passed to the request.
*
* @returns {Object<string, any>}
*/
function dispatchBeforeRedirect(options, responseDetails, requestDetails) {
if (options.beforeRedirects.proxy) {
options.beforeRedirects.proxy(options);
}
if (options.beforeRedirects.auth) {
options.beforeRedirects.auth(options);
}
if (options.beforeRedirects.sensitiveHeaders) {
options.beforeRedirects.sensitiveHeaders(options, requestDetails);
}
if (options.beforeRedirects.config) {
options.beforeRedirects.config(options, responseDetails, requestDetails);
}
}
function stripMatchingHeaders(headers, sensitiveSet) {
if (!headers) {
return;
}
Object.keys(headers).forEach((header) => {
if (sensitiveSet.has(header.toLowerCase())) {
delete headers[header];
}
});
}
function isSameOriginRedirect(redirectOptions, requestDetails) {
if (!requestDetails) {
return false;
}
try {
return new URL(requestDetails.url).origin === new URL(redirectOptions.href).origin;
} catch (e) {
// If origin comparison fails, treat the redirect as unsafe.
return false;
}
}
/**
* If the proxy or config afterRedirects functions are defined, call them with the options
*
* @param {http.ClientRequestArgs} options
* @param {AxiosProxyConfig} configProxy configuration from Axios options object
* @param {string} location
*
* @returns {http.ClientRequestArgs}
*/
function setProxy(options, configProxy, location, isRedirect, configHttpsAgent, configHttpAgent) {
let proxy = configProxy;
const proxyEnvAgent = getProxyEnvAgent(options, configHttpAgent, configHttpsAgent);
if (!proxy && proxy !== false && !isNodeEnvProxyEnabled(proxyEnvAgent)) {
const proxyUrl = getProxyForUrl(location);
if (proxyUrl) {
if (!shouldBypassProxy(location)) {
proxy = new URL(proxyUrl);
}
}
}
// On redirect re-invocation, strip any stale Proxy-Authorization header carried
// over from the prior request (e.g. new target no longer uses a proxy, or uses
// a different proxy). Skip on the initial request so user-supplied headers are
// preserved. Header names are case-insensitive, so remove every case variant.
if (isRedirect && options.headers) {
for (const name of Object.keys(options.headers)) {
if (name.toLowerCase() === 'proxy-authorization') {
delete options.headers[name];
}
}
}
// Strip any tunneling agent we installed for the previous hop so a redirect
// that drops the proxy or crosses an HTTPS↔HTTP boundary doesn't reuse a
// stale one. Match on our Symbol marker so a user-supplied HttpsProxyAgent
// (which won't carry the marker) is left alone.
if (isRedirect && options.agent && options.agent[kAxiosInstalledTunnel]) {
options.agent = undefined;
}
if (proxy) {
// Read proxy fields without traversing the prototype chain. URL instances expose
// username/password/hostname/host/port/protocol via getters on URL.prototype (so
// direct reads are shielded), but plain object proxies — and the `auth` field
// (which URL does not expose) — must be guarded so a polluted Object.prototype
// (e.g. Object.prototype.auth = { username, password }) cannot inject
// attacker-controlled credentials into the Proxy-Authorization header or
// redirect proxying to an attacker-controlled host.
const isProxyURL = proxy instanceof URL;
const readProxyField = (key) =>
isProxyURL || utils.hasOwnProp(proxy, key) ? proxy[key] : undefined;
const proxyUsername = readProxyField('username');
const proxyPassword = readProxyField('password');
let proxyAuth = utils.hasOwnProp(proxy, 'auth') ? proxy.auth : undefined;
// Basic proxy authorization
if (proxyUsername) {
proxyAuth = (proxyUsername || '') + ':' + (proxyPassword || '');
}
if (proxyAuth) {
// Support proxy auth object form. Read sub-fields via own-prop checks so a
// plain object inheriting from polluted Object.prototype cannot leak creds.
const authIsObject = typeof proxyAuth === 'object';
const authUsername =
authIsObject && utils.hasOwnProp(proxyAuth, 'username') ? proxyAuth.username : undefined;
const authPassword =
authIsObject && utils.hasOwnProp(proxyAuth, 'password') ? proxyAuth.password : undefined;
const validProxyAuth = Boolean(authUsername || authPassword);
if (validProxyAuth) {
proxyAuth = (authUsername || '') + ':' + (authPassword || '');
} else if (authIsObject) {
throw new AxiosError('Invalid proxy authorization', AxiosError.ERR_BAD_OPTION, { proxy });
}
}
const targetIsHttps = isHttps.test(options.protocol);
if (targetIsHttps) {
// CONNECT-tunneling path for HTTPS targets. Preserves end-to-end TLS to
// the origin so the proxy cannot inspect the URL, headers, or body — the
// behavior already promised by THREATMODEL.md (T-R9). HttpsProxyAgent
// sends Proxy-Authorization on the CONNECT request only, never on the
// wrapped TLS request, which is why we don't stamp it onto
// options.headers here. If the user already supplied an HttpsProxyAgent,
// they own tunneling end-to-end and we leave them alone; otherwise we
// install our own tunneling agent and forward their TLS options (if any)
// so a custom httpsAgent for cert pinning / rejectUnauthorized still
// applies to the origin TLS upgrade.
if (!(configHttpsAgent instanceof HttpsProxyAgent)) {
const proxyHost = readProxyField('hostname') || readProxyField('host');
const proxyPort = readProxyField('port');
const rawProxyProtocol = readProxyField('protocol');
const normalizedProtocol = rawProxyProtocol
? rawProxyProtocol.includes(':')
? rawProxyProtocol
: `${rawProxyProtocol}:`
: 'http:';
// Bracket IPv6 literals for URL parsing; URL.hostname strips the
// brackets again on read so the agent receives the raw form.
const proxyHostForURL =
proxyHost && proxyHost.includes(':') && !proxyHost.startsWith('[')
? `[${proxyHost}]`
: proxyHost;
const proxyURL = new URL(
`${normalizedProtocol}//${proxyHostForURL}${proxyPort ? ':' + proxyPort : ''}`
);
const agentOptions = {
protocol: proxyURL.protocol,
hostname: proxyURL.hostname.replace(/^\[|\]$/g, ''),
port: proxyURL.port,
auth: proxyAuth && typeof proxyAuth === 'string' ? proxyAuth : undefined,
};
if (proxyURL.protocol === 'https:') {
agentOptions.ALPNProtocols = ['http/1.1'];
}
const tunnelingAgent = getTunnelingAgent(agentOptions, configHttpsAgent);
// Set both: `options.agent` is consumed by the native https.request path
// (maxRedirects === 0); `options.agents.https` is consumed by
// follow-redirects, which ignores `options.agent` when `options.agents`
// is present.
options.agent = tunnelingAgent;
if (options.agents) {
options.agents.https = tunnelingAgent;
}
}
} else {
// Forward-proxy mode for plaintext HTTP targets. The request line carries
// the absolute URL and the proxy sees everything — acceptable for plain
// HTTP since the wire was already plaintext.
if (proxyAuth) {
const base64 = Buffer.from(proxyAuth, 'utf8').toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
}
// Preserve a user-supplied Host header (case-insensitive) so callers can override
// the value forwarded to the proxy; otherwise default to the request URL's host.
let hasUserHostHeader = false;
for (const name of Object.keys(options.headers)) {
if (name.toLowerCase() === 'host') {
hasUserHostHeader = true;
break;
}
}
if (!hasUserHostHeader) {
options.headers.host = options.hostname + (options.port ? ':' + options.port : '');
}
const proxyHost = readProxyField('hostname') || readProxyField('host');
options.hostname = proxyHost;
// Replace 'host' since options is not a URL object
options.host = proxyHost;
options.port = readProxyField('port');
options.path = location;
const proxyProtocol = readProxyField('protocol');
if (proxyProtocol) {
options.protocol = proxyProtocol.includes(':') ? proxyProtocol : `${proxyProtocol}:`;
}
}
}
options.beforeRedirects.proxy = function beforeRedirect(redirectOptions) {
// Configure proxy for redirected request, passing the original config proxy to apply
// the exact same logic as if the redirected request was performed by axios directly.
setProxy(
redirectOptions,
configProxy,
redirectOptions.href,
true,
configHttpsAgent,
configHttpAgent
);
};
}
const isHttpAdapterSupported =
typeof process !== 'undefined' && utils.kindOf(process) === 'process';
// temporary hotfix
const wrapAsync = (asyncExecutor) => {
return new Promise((resolve, reject) => {
let onDone;
let isDone;
const done = (value, isRejected) => {
if (isDone) return;
isDone = true;
onDone && onDone(value, isRejected);
};
const _resolve = (value) => {
done(value);
resolve(value);
};
const _reject = (reason) => {
done(reason, true);
reject(reason);
};
asyncExecutor(_resolve, _reject, (onDoneHandler) => (onDone = onDoneHandler)).catch(_reject);
});
};
const resolveFamily = ({ address, family }) => {
if (!utils.isString(address)) {
throw TypeError('address must be a string');
}
return {
address,
family: family || (address.indexOf('.') < 0 ? 6 : 4),
};
};
const buildAddressEntry = (address, family) =>
resolveFamily(utils.isObject(address) ? address : { address, family });
const http2Transport = {
request(options, cb) {
const authority =
options.protocol +
'//' +
options.hostname +
':' +
(options.port || (options.protocol === 'https:' ? 443 : 80));
const { http2Options, headers } = options;
const session = http2Sessions.getSession(authority, http2Options);
const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } =
http2.constants;
const http2Headers = {
[HTTP2_HEADER_SCHEME]: options.protocol.replace(':', ''),
[HTTP2_HEADER_METHOD]: options.method,
[HTTP2_HEADER_PATH]: options.path,
};
utils.forEach(headers, (header, name) => {
name.charAt(0) !== ':' && (http2Headers[name] = header);
});
const req = session.request(http2Headers);
req.once('response', (responseHeaders) => {
const response = req; //duplex
responseHeaders = Object.assign({}, responseHeaders);
const status = responseHeaders[HTTP2_HEADER_STATUS];
delete responseHeaders[HTTP2_HEADER_STATUS];
response.headers = responseHeaders;
response.statusCode = +status;
cb(response);
});
return req;
},
};
/*eslint consistent-return:0*/
export default isHttpAdapterSupported &&
function httpAdapter(config) {
return wrapAsync(async function dispatchHttpRequest(resolve, reject, onDone) {
// Read config pollution-safely: own properties and members inherited from
// a non-Object.prototype source (e.g. an Object.create(defaults) template)
// are honored, but values injected onto a polluted Object.prototype are
// ignored. All behavior-affecting reads in this adapter go through own()
// so the protection boundary stays consistent.
const own = (key) => utils.getSafeProp(config, key);
const transitional = own('transitional') || transitionalDefaults;
let data = own('data');
let lookup = own('lookup');
let family = own('family');
let httpVersion = own('httpVersion');
if (httpVersion === undefined) httpVersion = 1;
let http2Options = own('http2Options');
const httpAgent = own('httpAgent');
const httpsAgent = own('httpsAgent');
const configProxy = own('proxy');
const responseType = own('responseType');
const responseEncoding = own('responseEncoding');
const socketPath = own('socketPath');
const method = own('method').toUpperCase();
const maxRedirects = own('maxRedirects');
const maxBodyLength = own('maxBodyLength');
const maxContentLength = own('maxContentLength');
const decompress = own('decompress');
let isDone;
let rejected = false;
let req;
let connectPhaseTimer;
httpVersion = +httpVersion;
if (Number.isNaN(httpVersion)) {
throw TypeError(`Invalid protocol version: '${config.httpVersion}' is not a number`);
}
if (httpVersion !== 1 && httpVersion !== 2) {
throw TypeError(`Unsupported protocol version '${httpVersion}'`);
}
const isHttp2 = httpVersion === 2;
if (lookup) {
const _lookup = callbackify(lookup, (value) => (utils.isArray(value) ? value : [value]));
// hotfix to support opt.all option which is required for node 20.x
lookup = (hostname, opt, cb) => {
_lookup(hostname, opt, (err, arg0, arg1) => {
if (err) {
return cb(err);
}
const addresses = utils.isArray(arg0)
? arg0.map((addr) => buildAddressEntry(addr))
: [buildAddressEntry(arg0, arg1)];
opt.all ? cb(err, addresses) : cb(err, addresses[0].address, addresses[0].family);
});
};
}
const abortEmitter = new EventEmitter();
function abort(reason) {
try {
abortEmitter.emit(
'abort',
!reason || reason.type ? new CanceledError(null, config, req) : reason
);
} catch (err) {
// ignore emit errors
}
}
function clearConnectPhaseTimer() {
if (connectPhaseTimer) {
clearTimeout(connectPhaseTimer);
connectPhaseTimer = null;
}
}
function createTimeoutError() {
const configTimeout = own('timeout');
let timeoutErrorMessage = configTimeout
? 'timeout of ' + configTimeout + 'ms exceeded'
: 'timeout exceeded';
const configTimeoutErrorMessage = own('timeoutErrorMessage');
if (configTimeoutErrorMessage) {
timeoutErrorMessage = configTimeoutErrorMessage;
}
return new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
req
);
}
abortEmitter.once('abort', reject);
const onFinished = () => {
clearConnectPhaseTimer();
if (config.cancelToken) {
config.cancelToken.unsubscribe(abort);
}
if (config.signal) {
config.signal.removeEventListener('abort', abort);
}
abortEmitter.removeAllListeners();
};
if (config.cancelToken || config.signal) {
config.cancelToken && config.cancelToken.subscribe(abort);
if (config.signal) {
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
}
}
onDone((response, isRejected) => {
isDone = true;
clearConnectPhaseTimer();
if (isRejected) {
rejected = true;
onFinished();
return;
}
const { data } = response;
if (data instanceof stream.Readable || data instanceof stream.Duplex) {
const offListeners = stream.finished(data, () => {
offListeners();
onFinished();
});
} else {
onFinished();
}
});
// Parse url
const fullPath = buildFullPath(own('baseURL'), own('url'), own('allowAbsoluteUrls'), config);
// Unix-socket requests (own socketPath) commonly pass a path-only url
// like '/foo'; supply a synthetic base so new URL() can still parse it.
// Use the own-property value (not config.socketPath) so a polluted
// prototype cannot influence URL base selection.
const urlBase = socketPath
? 'http://localhost'
: (platform.hasBrowserEnv ? platform.origin : undefined);
const parsed = new URL(fullPath, urlBase);
const protocol = parsed.protocol || supportedProtocols[0];
if (protocol === 'data:') {
// Apply the same semantics as HTTP: only enforce if a finite, non-negative cap is set.
if (maxContentLength > -1) {
// Use the exact string passed to fromDataURI (the configured url); fall back to fullPath if needed.
const dataUrl = String(own('url') || fullPath || '');
const estimated = estimateDataURLDecodedBytes(dataUrl);
if (estimated > maxContentLength) {
return reject(
new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config
)
);
}
}
let convertedData;
if (method !== 'GET') {
return settle(resolve, reject, {
status: 405,
statusText: 'method not allowed',
headers: {},
config,
});
}
try {
convertedData = fromDataURI(own('url'), responseType === 'blob', {
Blob: config.env && config.env.Blob,
});
} catch (err) {
throw AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config);
}
if (responseType === 'text') {
convertedData = convertedData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
convertedData = utils.stripBOM(convertedData);
}
} else if (responseType === 'stream') {
convertedData = stream.Readable.from(convertedData);
}
return settle(resolve, reject, {
data: convertedData,
status: 200,
statusText: 'OK',
headers: new AxiosHeaders(),
config,
});
}
if (supportedProtocols.indexOf(protocol) === -1) {
return reject(
new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_BAD_REQUEST, config)
);
}
const headers = AxiosHeaders.from(config.headers).normalize();
// Set User-Agent (required by some servers)
// See https://github.com/axios/axios/issues/69
// User-Agent is specified; handle case where no UA header is desired
// Only set header if it hasn't been set in config
headers.set('User-Agent', 'axios/' + VERSION, false);
const { onUploadProgress, onDownloadProgress } = config;
const maxRate = config.maxRate;
let maxUploadRate = undefined;
let maxDownloadRate = undefined;
// support for spec compliant FormData objects
if (utils.isSpecCompliantForm(data)) {
const userBoundary = headers.getContentType(/boundary=([-_\w\d]{10,70})/i);
data = formDataToStream(
data,
(formHeaders) => {
headers.set(formHeaders);
},
{
tag: `axios-${VERSION}-boundary`,
boundary: (userBoundary && userBoundary[1]) || undefined,
}
);
// support for https://www.npmjs.com/package/form-data api
} else if (
utils.isFormData(data) &&
utils.isFunction(data.getHeaders) &&
data.getHeaders !== Object.prototype.getHeaders
) {
setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
if (!headers.hasContentLength()) {
try {
const knownLength = await util.promisify(data.getLength).call(data);
Number.isFinite(knownLength) &&
knownLength >= 0 &&
headers.setContentLength(knownLength);
/*eslint no-empty:0*/
} catch (e) {}
}
} else if (utils.isBlob(data) || utils.isFile(data)) {
data.size && headers.setContentType(data.type || 'application/octet-stream');
headers.setContentLength(data.size || 0);
data = stream.Readable.from(readBlob(data));
} else if (data && !utils.isStream(data)) {
if (Buffer.isBuffer(data)) {
// Nothing to do...
} else if (utils.isArrayBuffer(data)) {
data = Buffer.from(new Uint8Array(data));
} else if (utils.isString(data)) {
data = Buffer.from(data, 'utf-8');
} else {
return reject(
new AxiosError(
'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',
AxiosError.ERR_BAD_REQUEST,
config
)
);
}
// Add Content-Length header if data exists
headers.setContentLength(data.length, false);
if (maxBodyLength > -1 && data.length > maxBodyLength) {
return reject(
new AxiosError(
'Request body larger than maxBodyLength limit',
AxiosError.ERR_BAD_REQUEST,
config
)
);
}
}
const contentLength = utils.toFiniteNumber(headers.getContentLength());
if (utils.isArray(maxRate)) {
maxUploadRate = maxRate[0];
maxDownloadRate = maxRate[1];
} else {
maxUploadRate = maxDownloadRate = maxRate;
}
if (data && (onUploadProgress || maxUploadRate)) {
if (!utils.isStream(data)) {
data = stream.Readable.from(data, { objectMode: false });
}
data = stream.pipeline(
[
data,
new AxiosTransformStream({
maxRate: utils.toFiniteNumber(maxUploadRate),
}),
],
utils.noop
);
onUploadProgress &&
data.on(
'progress',
flushOnFinish(
data,
progressEventDecorator(
contentLength,
progressEventReducer(asyncDecorator(onUploadProgress), false, 3)
)
)
);
}
// HTTP basic authentication
let auth = undefined;
const configAuth = own('auth');
if (configAuth) {
const username = utils.getSafeProp(configAuth, 'username') || '';
const password = utils.getSafeProp(configAuth, 'password') || '';
auth = username + ':' + password;
}
if (!auth && (parsed.username || parsed.password)) {
const urlUsername = decodeURIComponentSafe(parsed.username);
const urlPassword = decodeURIComponentSafe(parsed.password);
auth = urlUsername + ':' + urlPassword;
}
auth && headers.delete('authorization');
let path;
try {
path = buildURL(
parsed.pathname + parsed.search,
own('params'),
own('paramsSerializer')
).replace(/^\?/, '');
} catch (err) {
return reject(
AxiosError.from(err, AxiosError.ERR_BAD_REQUEST, config, null, null, {
url: own('url'),
exists: true
})
);
}
headers.set(
'Accept-Encoding',
utils.hasOwnProp(transitional, 'advertiseZstdAcceptEncoding') &&
transitional.advertiseZstdAcceptEncoding === true ? ACCEPT_ENCODING_WITH_ZSTD : ACCEPT_ENCODING,
false
);
// Null-prototype to block prototype pollution gadgets on properties read
// directly by Node's http.request (e.g. insecureHTTPParser, lookup).
const options = Object.assign(Object.create(null), {
path,
method: method,
headers: toByteStringHeaderObject(headers),
agents: { http: httpAgent, https: httpsAgent },
auth,
protocol,
family,
beforeRedirect: dispatchBeforeRedirect,
beforeRedirects: Object.create(null),
http2Options,
});
// cacheable-lookup integration hotfix
!utils.isUndefined(lookup) && (options.lookup = lookup);
if (socketPath) {
if (typeof socketPath !== 'string') {
return reject(
new AxiosError('socketPath must be a string', AxiosError.ERR_BAD_OPTION_VALUE, config)
);
}
const allowedSocketPaths = own('allowedSocketPaths');
if (allowedSocketPaths != null) {
const allowed = Array.isArray(allowedSocketPaths)
? allowedSocketPaths
: [allowedSocketPaths];
const resolvedSocket = resolvePath(socketPath);
const isAllowed = allowed.some(
(entry) => typeof entry === 'string' && resolvePath(entry) === resolvedSocket
);
if (!isAllowed) {
return reject(
new AxiosError(
`socketPath "${socketPath}" is not permitted by allowedSocketPaths`,
AxiosError.ERR_BAD_OPTION_VALUE,
config
)
);
}
}
options.socketPath = socketPath;
} else {
options.hostname = parsed.hostname.startsWith('[')
? parsed.hostname.slice(1, -1)
: parsed.hostname;
options.port = parsed.port;
setProxy(
options,
configProxy,
protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path,
false,
httpsAgent,
httpAgent
);
}
let transport;
let isNativeTransport = false;
// True only for the follow-redirects transport, which applies
// options.maxBodyLength itself. Every other transport (http2, native
// http/https, a user-supplied custom transport) needs the explicit
// byte-counting pipeline below to enforce maxBodyLength on streamed uploads.
let transportEnforcesMaxBodyLength = false;
const isHttpsRequest = isHttps.test(options.protocol);
// Don't clobber a CONNECT-tunneling agent installed by setProxy() for an
// HTTPS target.
if (options.agent == null) {
options.agent = isHttpsRequest ? httpsAgent : httpAgent;
}
if (isHttp2) {
transport = http2Transport;
} else {
const configTransport = own('transport');
if (configTransport) {
transport = configTransport;
} else if (maxRedirects === 0) {
transport = isHttpsRequest ? https : http;
isNativeTransport = true;
} else {
transportEnforcesMaxBodyLength = true;
options.sensitiveHeaders = [];
if (maxRedirects) {
options.maxRedirects = maxRedirects;
}
const configBeforeRedirect = own('beforeRedirect');
if (configBeforeRedirect) {
options.beforeRedirects.config = configBeforeRedirect;
}
if (auth) {
// Restore HTTP Basic credentials on same-origin redirects only.
// follow-redirects >= 1.15.8 strips Authorization on every redirect (see #6929);
// cross-origin stripping is the documented mitigation for T-R2 in THREATMODEL.md
// and is preserved by deliberately not restoring on origin change.
const requestOrigin = parsed.origin;
const authToRestore = auth;
options.beforeRedirects.auth = function beforeRedirectAuth(redirectOptions) {
try {
if (new URL(redirectOptions.href).origin === requestOrigin) {
redirectOptions.auth = authToRestore;
}
} catch (e) {
// ignore malformed URL: leaving auth stripped is fail-safe
}
};
}
const sensitiveHeaders = own('sensitiveHeaders');
if (sensitiveHeaders != null) {
if (!utils.isArray(sensitiveHeaders)) {
return reject(
new AxiosError(
'sensitiveHeaders must be an array of strings',
AxiosError.ERR_BAD_OPTION_VALUE,
config
)
);
}
const sensitiveSet = new Set();
for (const header of sensitiveHeaders) {
if (!utils.isString(header)) {
return reject(
new AxiosError(
'sensitiveHeaders must be an array of strings',
AxiosError.ERR_BAD_OPTION_VALUE,
config
)
);
}
sensitiveSet.add(header.toLowerCase());
}
if (sensitiveSet.size) {
options.sensitiveHeaders = Array.from(sensitiveSet);
options.beforeRedirects.sensitiveHeaders = function beforeRedirectSensitiveHeaders(
redirectOptions,
requestDetails
) {
if (!isSameOriginRedirect(redirectOptions, requestDetails)) {
stripMatchingHeaders(redirectOptions.headers, sensitiveSet);
}
};
}
}
transport = isHttpsRequest ? httpsFollow : httpFollow;
}
}
// Set an explicit maxBodyLength option for transports that inspect it.
// When maxBodyLength is -1 (default/unlimited), use Infinity so
// follow-redirects does not fall back to its own 10MB default.
if (maxBodyLength > -1) {
options.maxBodyLength = maxBodyLength;
} else {
options.maxBodyLength = Infinity;
}
// Always set an explicit own value so a polluted
// Object.prototype.insecureHTTPParser cannot enable the lenient parser
// through Node's internal options copy
options.insecureHTTPParser = Boolean(own('insecureHTTPParser'));
// Create the request
req = transport.request(options, function handleResponse(res) {
clearConnectPhaseTimer();
if (req.destroyed) return;
const streams = [res];
const responseLength = utils.toFiniteNumber(res.headers['content-length']);
if (onDownloadProgress || maxDownloadRate) {
const transformStream = new AxiosTransformStream({
maxRate: utils.toFiniteNumber(maxDownloadRate),
});
onDownloadProgress &&
transformStream.on(
'progress',
flushOnFinish(
transformStream,
progressEventDecorator(
responseLength,
progressEventReducer(asyncDecorator(onDownloadProgress), true, 3)
)
)
);
streams.push(transformStream);
}
// decompress the response body transparently if required
let responseStream = res;
// return the last request in case of redirects
const lastRequest = res.req || req;
// if decompress disabled we should not decompress
if (decompress !== false && res.headers['content-encoding']) {
// if no content, but headers still say that it is encoded,
// remove the header not confuse downstream operations
if (method === 'HEAD' || res.statusCode === 204) {
delete res.headers['content-encoding'];
}
switch ((res.headers['content-encoding'] || '').toLowerCase()) {
/*eslint default-case:0*/
case 'gzip':
case 'x-gzip':
case 'compress':
case 'x-compress':
// add the unzipper to the body stream processing pipeline
streams.push(zlib.createUnzip(zlibOptions));
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'deflate':
streams.push(new ZlibHeaderTransformStream());
// add the unzipper to the body stream processing pipeline
streams.push(zlib.createUnzip(zlibOptions));
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'br':
if (isBrotliSupported) {
streams.push(zlib.createBrotliDecompress(brotliOptions));
delete res.headers['content-encoding'];
}
break;
case 'zstd':
if (isZstdSupported) {
streams.push(zlib.createZstdDecompress(zstdOptions));
delete res.headers['content-encoding'];
}
break;
}
}
responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
const response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: new AxiosHeaders(res.headers),
config,
request: lastRequest,
};
if (responseType === 'stream') {
// Enforce maxContentLength on streamed responses; previously this
// was applied only to buffered responses.
if (maxContentLength > -1) {
const limit = maxContentLength;
const source = responseStream;
async function* enforceMaxContentLength() {
let totalResponseBytes = 0;
for await (const chunk of source) {
totalResponseBytes += chunk.length;
if (totalResponseBytes > limit) {
throw new AxiosError(
'maxContentLength size of ' + limit + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest
);
}
yield chunk;
}
}
responseStream = stream.Readable.from(enforceMaxContentLength(), {
objectMode: false,
});
}
response.data = responseStream;
settle(resolve, reject, response);
} else {
const responseBuffer = [];
let totalResponseBytes = 0;
responseStream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
totalResponseBytes += chunk.length;
// make sure the content length is not over the maxContentLength if specified
if (maxContentLength > -1 && totalResponseBytes > maxContentLength) {
// stream.destroy() emit aborted event before calling reject() on Node.js v16
rejected = true;
responseStream.destroy();
abort(
new AxiosError(
'maxContentLength size of ' + maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest
)
);
}
});
responseStream.on('aborted', function handlerStreamAborted() {
if (rejected) {
return;
}
const err = new AxiosError(
'stream has been aborted',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest,
response
);
responseStream.destroy(err);
reject(err);
});
responseStream.on('error', function handleStreamError(err) {
if (rejected) return;
reject(AxiosError.from(err, null, config, lastRequest, response));
});
responseStream.on('end', function handleStreamEnd() {
try {
let responseData =
responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
if (responseType !== 'arraybuffer') {
responseData = responseData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
responseData = utils.stripBOM(responseData);
}
}
response.data = responseData;
} catch (err) {
return reject(AxiosError.from(err, null, config, response.request, response));
}
settle(resolve, reject, response);
});
}
abortEmitter.once('abort', (err) => {
if (!responseStream.destroyed) {
responseStream.emit('error', err);
responseStream.destroy();
}
});
});
abortEmitter.once('abort', (err) => {
if (req.close) {
req.close();
} else {
req.destroy(err);
}
});
// Handle errors
req.on('error', function handleRequestError(err) {
reject(AxiosError.from(err, null, config, req));
});
// set tcp keep alive to prevent drop connection by peer
// Track every socket bound to this outer RedirectableRequest so a single
// 'close' listener can release ownership on all of them. follow-redirects
// re-emits the 'socket' event for each hop's native request onto the same
// outer request, so attaching per-request listeners inside this handler
// would accumulate across hops and trigger MaxListenersExceededWarning at
// >= 11 redirects. Clearing only the last-bound socket would leave stale
// kAxiosCurrentReq refs on earlier hop sockets returned to the keep-alive
// pool, causing an idle-pool 'error' to be attributed to a closed req.
const boundSockets = new Set();
req.on('socket', function handleRequestSocket(socket) {
// default interval of sending ack packet is 1 minute
// proxy agents (e.g. agent-base) may return a generic Duplex stream
// that doesn't have setKeepAlive, so guard before calling
if (typeof socket.setKeepAlive === 'function') {
socket.setKeepAlive(true, 1000 * 60);
}
// Install a single 'error' listener per socket (not per request) to avoid
// accumulating listeners on pooled keep-alive sockets that get reassigned
// to new requests before the previous request's 'close' fires (issue #10780).
// The listener is bound to the socket's currently-active request via a
// symbol, which is swapped as the socket is reassigned.
if (!socket[kAxiosSocketListener]) {
socket.on('error', function handleSocketError(err) {
const current = socket[kAxiosCurrentReq];
if (current && !current.destroyed) {
current.destroy(err);
}
});
socket[kAxiosSocketListener] = true;
}
socket[kAxiosCurrentReq] = req;
boundSockets.add(socket);
});
req.once('close', function clearCurrentReq() {
clearConnectPhaseTimer();
for (const socket of boundSockets) {
if (socket[kAxiosCurrentReq] === req) {
socket[kAxiosCurrentReq] = null;
}
}
boundSockets.clear();
});
// Handle request timeout
if (own('timeout')) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
const timeout = parseInt(own('timeout'), 10);
if (Number.isNaN(timeout)) {
abort(
new AxiosError(
'error trying to parse `config.timeout` to int',
AxiosError.ERR_BAD_OPTION_VALUE,
config,
req
)
);
return;
}
const handleTimeout = function handleTimeout() {
if (isDone) return;
abort(createTimeoutError());
};
if (isNativeTransport && timeout > 0) {
// Native ClientRequest#setTimeout starts from the socket lifecycle and
// may not fire while TCP connect is still pending. Mirror the
// follow-redirects wall-clock timer for the maxRedirects === 0 path.
connectPhaseTimer = setTimeout(handleTimeout, timeout);
}
// Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.
// And timer callback will be fired, and abort() will be invoked before connection, then get "socket hang up" and code ECONNRESET.
// At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.
// And then these socket which be hang up will devouring CPU little by little.
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
req.setTimeout(timeout, handleTimeout);
} else {
// explicitly reset the socket timeout value for a possible `keep-alive` request
req.setTimeout(0);
}
// Send the request
if (utils.isStream(data)) {
let ended = false;
let errored = false;
data.on('end', () => {
ended = true;
});
data.once('error', (err) => {
errored = true;
req.destroy(err);
});
data.on('close', () => {
if (!ended && !errored) {
abort(new CanceledError('Request stream has been aborted', config, req));
}
});
// Enforce maxBodyLength for streamed uploads on every transport that
// does not apply options.maxBodyLength itself (native http/https, http2,
// and user-supplied custom transports). The follow-redirects transport
// enforces it on the redirected HTTP/1 path.
let uploadStream = data;
if (maxBodyLength > -1 && !transportEnforcesMaxBodyLength) {
const limit = maxBodyLength;
let bytesSent = 0;
uploadStream = stream.pipeline(
[
data,
new stream.Transform({
transform(chunk, _enc, cb) {
bytesSent += chunk.length;
if (bytesSent > limit) {
return cb(
new AxiosError(
'Request body larger than maxBodyLength limit',
AxiosError.ERR_BAD_REQUEST,
config,
req
)
);
}
cb(null, chunk);
},
}),
],
utils.noop
);
uploadStream.on('error', (err) => {
if (!req.destroyed) req.destroy(err);
});
}
uploadStream.pipe(req);
} else {
data && req.write(data);
req.end();
}
});
};
export const __setProxy = setProxy;
export const __isNodeEnvProxyEnabled = isNodeEnvProxyEnabled;
export const __isSameOriginRedirect = isSameOriginRedirect;
+228
View File
@@ -0,0 +1,228 @@
import utils from '../utils.js';
import settle from '../core/settle.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import parseProtocol from '../helpers/parseProtocol.js';
import platform from '../platform/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import { progressEventReducer } from '../helpers/progressEventReducer.js';
import resolveConfig from '../helpers/resolveConfig.js';
import { toByteStringHeaderObject } from '../helpers/sanitizeHeaderValue.js';
const isXHRAdapterSupported = typeof XMLHttpRequest !== 'undefined';
export default isXHRAdapterSupported &&
function (config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
const _config = resolveConfig(config);
let requestData = _config.data;
const requestHeaders = AxiosHeaders.from(_config.headers).normalize();
let { responseType, onUploadProgress, onDownloadProgress } = _config;
let onCanceled;
let uploadThrottled, downloadThrottled;
let flushUpload, flushDownload;
function done() {
flushUpload && flushUpload(); // flush events
flushDownload && flushDownload(); // flush events
_config.cancelToken && _config.cancelToken.unsubscribe(onCanceled);
_config.signal && _config.signal.removeEventListener('abort', onCanceled);
}
let request = new XMLHttpRequest();
request.open(_config.method.toUpperCase(), _config.url, true);
// Set the request timeout in MS
request.timeout = _config.timeout;
function onloadend() {
if (!request) {
return;
}
// Prepare the response
const responseHeaders = AxiosHeaders.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData =
!responseType || responseType === 'text' || responseType === 'json'
? request.responseText
: request.response;
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config,
request,
};
settle(
function _resolve(value) {
resolve(value);
done();
},
function _reject(err) {
reject(err);
done();
},
response
);
// Clean up request
request = null;
}
if ('onloadend' in request) {
// Use onloadend if available
request.onloadend = onloadend;
} else {
// Listen for ready state to emulate onloadend
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (
request.status === 0 &&
!(request.responseURL && request.responseURL.startsWith('file:'))
) {
return;
}
// readystate handler is calling before onerror or ontimeout handlers,
// so we should call onloadend on the next 'tick'
setTimeout(onloadend);
};
}
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));
done();
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError(event) {
// Browsers deliver a ProgressEvent in XHR onerror
// (message may be empty; when present, surface it)
// See https://developer.mozilla.org/docs/Web/API/XMLHttpRequest/error_event
const msg = event && event.message ? event.message : 'Network Error';
const err = new AxiosError(msg, AxiosError.ERR_NETWORK, config, request);
// attach the underlying event for consumers who want details
err.event = event || null;
reject(err);
done();
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
let timeoutErrorMessage = _config.timeout
? 'timeout of ' + _config.timeout + 'ms exceeded'
: 'timeout exceeded';
const transitional = _config.transitional || transitionalDefaults;
if (_config.timeoutErrorMessage) {
timeoutErrorMessage = _config.timeoutErrorMessage;
}
reject(
new AxiosError(
timeoutErrorMessage,
transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,
config,
request
)
);
done();
// Clean up request
request = null;
};
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(toByteStringHeaderObject(requestHeaders), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(_config.withCredentials)) {
request.withCredentials = !!_config.withCredentials;
}
// Add responseType to request if needed
if (responseType && responseType !== 'json') {
request.responseType = _config.responseType;
}
// Handle progress if needed
if (onDownloadProgress) {
[downloadThrottled, flushDownload] = progressEventReducer(onDownloadProgress, true);
request.addEventListener('progress', downloadThrottled);
}
// Not all browsers support upload events
if (onUploadProgress && request.upload) {
[uploadThrottled, flushUpload] = progressEventReducer(onUploadProgress);
request.upload.addEventListener('progress', uploadThrottled);
request.upload.addEventListener('loadend', flushUpload);
}
if (_config.cancelToken || _config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = (cancel) => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
done();
request = null;
};
_config.cancelToken && _config.cancelToken.subscribe(onCanceled);
if (_config.signal) {
_config.signal.aborted
? onCanceled()
: _config.signal.addEventListener('abort', onCanceled);
}
}
const protocol = parseProtocol(_config.url);
if (protocol && !platform.protocols.includes(protocol)) {
reject(
new AxiosError(
'Unsupported protocol ' + protocol + ':',
AxiosError.ERR_BAD_REQUEST,
config
)
);
done();
return;
}
// Send the request
request.send(requestData || null);
});
};
+89
View File
@@ -0,0 +1,89 @@
'use strict';
import utils from './utils.js';
import bind from './helpers/bind.js';
import Axios from './core/Axios.js';
import mergeConfig from './core/mergeConfig.js';
import defaults from './defaults/index.js';
import formDataToJSON from './helpers/formDataToJSON.js';
import CanceledError from './cancel/CanceledError.js';
import CancelToken from './cancel/CancelToken.js';
import isCancel from './cancel/isCancel.js';
import { VERSION } from './env/data.js';
import toFormData from './helpers/toFormData.js';
import AxiosError from './core/AxiosError.js';
import spread from './helpers/spread.js';
import isAxiosError from './helpers/isAxiosError.js';
import AxiosHeaders from './core/AxiosHeaders.js';
import adapters from './adapters/adapters.js';
import HttpStatusCode from './helpers/HttpStatusCode.js';
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
*
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
const context = new Axios(defaultConfig);
const instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context, { allOwnKeys: true });
// Copy context to instance
utils.extend(instance, context, null, { allOwnKeys: true });
// Factory for creating new instances
instance.create = function create(instanceConfig) {
return createInstance(mergeConfig(defaultConfig, instanceConfig));
};
return instance;
}
// Create the default instance to be exported
const axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = isAxiosError;
// Expose mergeConfig
axios.mergeConfig = mergeConfig;
axios.AxiosHeaders = AxiosHeaders;
axios.formToJSON = (thing) => formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
axios.getAdapter = adapters.getAdapter;
axios.HttpStatusCode = HttpStatusCode;
axios.default = axios;
// this module should only have a default export
export default axios;
+135
View File
@@ -0,0 +1,135 @@
'use strict';
import CanceledError from './CanceledError.js';
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @param {Function} executor The executor function.
*
* @returns {CancelToken}
*/
class CancelToken {
constructor(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
let resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
const token = this;
// eslint-disable-next-line func-names
this.promise.then((cancel) => {
if (!token._listeners) return;
let i = token._listeners.length;
while (i-- > 0) {
token._listeners[i](cancel);
}
token._listeners = null;
});
// eslint-disable-next-line func-names
this.promise.then = (onfulfilled) => {
let _resolve;
// eslint-disable-next-line func-names
const promise = new Promise((resolve) => {
token.subscribe(resolve);
_resolve = resolve;
}).then(onfulfilled);
promise.cancel = function reject() {
token.unsubscribe(_resolve);
};
return promise;
};
executor(function cancel(message, config, request) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new CanceledError(message, config, request);
resolvePromise(token.reason);
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason) {
throw this.reason;
}
}
/**
* Subscribe to the cancel signal
*/
subscribe(listener) {
if (this.reason) {
listener(this.reason);
return;
}
if (this._listeners) {
this._listeners.push(listener);
} else {
this._listeners = [listener];
}
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(listener) {
if (!this._listeners) {
return;
}
const index = this._listeners.indexOf(listener);
if (index !== -1) {
this._listeners.splice(index, 1);
}
}
toAbortSignal() {
const controller = new AbortController();
const abort = (err) => {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = () => this.unsubscribe(abort);
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let cancel;
const token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token,
cancel,
};
}
}
export default CancelToken;
+22
View File
@@ -0,0 +1,22 @@
'use strict';
import AxiosError from '../core/AxiosError.js';
class CanceledError extends AxiosError {
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
*
* @param {string=} message The message.
* @param {Object=} config The config.
* @param {Object=} request The request.
*
* @returns {CanceledError} The created error.
*/
constructor(message, config, request) {
super(message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request);
this.name = 'CanceledError';
this.__CANCEL__ = true;
}
}
export default CanceledError;
+5
View File
@@ -0,0 +1,5 @@
'use strict';
export default function isCancel(value) {
return !!(value && value.__CANCEL__);
}
+283
View File
@@ -0,0 +1,283 @@
'use strict';
import utils from '../utils.js';
import buildURL from '../helpers/buildURL.js';
import InterceptorManager from './InterceptorManager.js';
import dispatchRequest from './dispatchRequest.js';
import mergeConfig from './mergeConfig.js';
import buildFullPath from './buildFullPath.js';
import validator from '../helpers/validator.js';
import AxiosHeaders from './AxiosHeaders.js';
import transitionalDefaults from '../defaults/transitional.js';
const validators = validator.validators;
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*
* @return {Axios} A new instance of Axios
*/
class Axios {
constructor(instanceConfig) {
this.defaults = instanceConfig || {};
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager(),
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(configOrUrl, config) {
try {
return await this._request(configOrUrl, config);
} catch (err) {
if (err instanceof Error) {
let dummy = {};
Error.captureStackTrace ? Error.captureStackTrace(dummy) : (dummy = new Error());
// slice off the Error: ... line
const stack = (() => {
if (!dummy.stack) {
return '';
}
const firstNewlineIndex = dummy.stack.indexOf('\n');
return firstNewlineIndex === -1 ? '' : dummy.stack.slice(firstNewlineIndex + 1);
})();
try {
if (!err.stack) {
err.stack = stack;
// match without the 2 top stack lines
} else if (stack) {
const firstNewlineIndex = stack.indexOf('\n');
const secondNewlineIndex =
firstNewlineIndex === -1 ? -1 : stack.indexOf('\n', firstNewlineIndex + 1);
const stackWithoutTwoTopLines =
secondNewlineIndex === -1 ? '' : stack.slice(secondNewlineIndex + 1);
if (!String(err.stack).endsWith(stackWithoutTwoTopLines)) {
err.stack += '\n' + stack;
}
}
} catch (e) {
// ignore the case where "stack" is an un-writable property
}
}
throw err;
}
}
_request(configOrUrl, config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof configOrUrl === 'string') {
config = config || {};
config.url = configOrUrl;
} else {
config = configOrUrl || {};
}
config = mergeConfig(this.defaults, config);
const { transitional, paramsSerializer, headers } = config;
if (transitional !== undefined) {
validator.assertOptions(
transitional,
{
silentJSONParsing: validators.transitional(validators.boolean),
forcedJSONParsing: validators.transitional(validators.boolean),
clarifyTimeoutError: validators.transitional(validators.boolean),
legacyInterceptorReqResOrdering: validators.transitional(validators.boolean),
advertiseZstdAcceptEncoding: validators.transitional(validators.boolean),
validateStatusUndefinedResolves: validators.transitional(validators.boolean),
},
false
);
}
if (paramsSerializer != null) {
if (utils.isFunction(paramsSerializer)) {
config.paramsSerializer = {
serialize: paramsSerializer,
};
} else {
validator.assertOptions(
paramsSerializer,
{
encode: validators.function,
serialize: validators.function,
},
true
);
}
}
// Set config.allowAbsoluteUrls
if (config.allowAbsoluteUrls !== undefined) {
// do nothing
} else if (this.defaults.allowAbsoluteUrls !== undefined) {
config.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls;
} else {
config.allowAbsoluteUrls = true;
}
validator.assertOptions(
config,
{
baseUrl: validators.spelling('baseURL'),
withXsrfToken: validators.spelling('withXSRFToken'),
},
true
);
// Set config.method
config.method = (config.method || this.defaults.method || 'get').toLowerCase();
// Flatten headers
let contextHeaders = headers && utils.merge(headers.common, headers[config.method]);
headers &&
utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query', 'common'], (method) => {
delete headers[method];
});
config.headers = AxiosHeaders.concat(contextHeaders, headers);
// filter out skipped interceptors
const requestInterceptorChain = [];
let synchronousRequestInterceptors = true;
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {
return;
}
synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;
const transitional = config.transitional || transitionalDefaults;
const legacyInterceptorReqResOrdering =
transitional && transitional.legacyInterceptorReqResOrdering;
if (legacyInterceptorReqResOrdering) {
requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);
} else {
requestInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
}
});
const responseInterceptorChain = [];
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);
});
let promise;
let i = 0;
let len;
if (!synchronousRequestInterceptors) {
const chain = [dispatchRequest.bind(this), undefined];
chain.unshift(...requestInterceptorChain);
chain.push(...responseInterceptorChain);
len = chain.length;
promise = Promise.resolve(config);
while (i < len) {
promise = promise.then(chain[i++], chain[i++]);
}
return promise;
}
len = requestInterceptorChain.length;
let newConfig = config;
while (i < len) {
const onFulfilled = requestInterceptorChain[i++];
const onRejected = requestInterceptorChain[i++];
try {
newConfig = onFulfilled(newConfig);
} catch (error) {
onRejected.call(this, error);
break;
}
}
try {
promise = dispatchRequest.call(this, newConfig);
} catch (error) {
return Promise.reject(error);
}
i = 0;
len = responseInterceptorChain.length;
while (i < len) {
promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]);
}
return promise;
}
getUri(config) {
config = mergeConfig(this.defaults, config);
const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls, config);
return buildURL(fullPath, config.params, config.paramsSerializer);
}
}
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function (url, config) {
return this.request(
mergeConfig(config || {}, {
method,
url,
data: config && utils.hasOwnProp(config, 'data') ? config.data : undefined,
})
);
};
});
utils.forEach(['post', 'put', 'patch', 'query'], function forEachMethodWithData(method) {
function generateHTTPMethod(isForm) {
return function httpMethod(url, data, config) {
return this.request(
mergeConfig(config || {}, {
method,
headers: isForm
? {
'Content-Type': 'multipart/form-data',
}
: {},
url,
data,
})
);
};
}
Axios.prototype[method] = generateHTTPMethod();
// QUERY is a safe/idempotent read method; multipart form bodies don't fit
// its semantics, so no queryForm shorthand is generated.
if (method !== 'query') {
Axios.prototype[method + 'Form'] = generateHTTPMethod(true);
}
});
export default Axios;
+188
View File
@@ -0,0 +1,188 @@
'use strict';
import utils from '../utils.js';
import AxiosHeaders from './AxiosHeaders.js';
const REDACTED = '[REDACTED ****]';
function hasOwnOrPrototypeToJSON(source) {
if (utils.hasOwnProp(source, 'toJSON')) {
return true;
}
let prototype = Object.getPrototypeOf(source);
while (prototype && prototype !== Object.prototype) {
if (utils.hasOwnProp(prototype, 'toJSON')) {
return true;
}
prototype = Object.getPrototypeOf(prototype);
}
return false;
}
// Build a plain-object snapshot of `config` and replace the value of any key
// (case-insensitive) listed in `redactKeys` with REDACTED. Walks through arrays
// and AxiosHeaders, and short-circuits on circular references.
function redactConfig(config, redactKeys) {
const lowerKeys = new Set(redactKeys.map((k) => String(k).toLowerCase()));
const seen = [];
const visit = (source) => {
if (source === null || typeof source !== 'object') return source;
if (utils.isBuffer(source)) return source;
if (seen.indexOf(source) !== -1) return undefined;
if (source instanceof AxiosHeaders) {
source = source.toJSON();
}
seen.push(source);
let result;
if (utils.isArray(source)) {
result = [];
source.forEach((v, i) => {
const reducedValue = visit(v);
if (!utils.isUndefined(reducedValue)) {
result[i] = reducedValue;
}
});
} else {
if (!utils.isPlainObject(source) && hasOwnOrPrototypeToJSON(source)) {
seen.pop();
return source;
}
result = Object.create(null);
for (const [key, value] of Object.entries(source)) {
const reducedValue = lowerKeys.has(key.toLowerCase()) ? REDACTED : visit(value);
if (!utils.isUndefined(reducedValue)) {
result[key] = reducedValue;
}
}
}
seen.pop();
return result;
};
return visit(config);
}
class AxiosError extends Error {
static from(error, code, config, request, response, customProps) {
const axiosError = new AxiosError(error.message, code || error.code, config, request, response);
// Match native `Error` `cause` semantics: non-enumerable. The wrapped
// error often carries circular internals (sockets, requests, agents), so
// an enumerable `cause` makes structured loggers (pino/winston) and any
// own-property walk throw "Converting circular structure to JSON".
// Regression from #6982; see #7205. `__proto__: null` mirrors the
// `message` descriptor below (prototype-pollution-safe descriptor).
Object.defineProperty(axiosError, 'cause', {
__proto__: null,
value: error,
writable: true,
enumerable: false,
configurable: true,
});
axiosError.name = error.name;
// Preserve status from the original error if not already set from response
if (error.status != null && axiosError.status == null) {
axiosError.status = error.status;
}
customProps && Object.assign(axiosError, customProps);
return axiosError;
}
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [config] The config.
* @param {Object} [request] The request.
* @param {Object} [response] The response.
*
* @returns {Error} The created error.
*/
constructor(message, code, config, request, response) {
super(message);
// Make message enumerable to maintain backward compatibility
// The native Error constructor sets message as non-enumerable,
// but axios < v1.13.3 had it as enumerable
Object.defineProperty(this, 'message', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: message,
enumerable: true,
writable: true,
configurable: true,
});
this.name = 'AxiosError';
this.isAxiosError = true;
code && (this.code = code);
config && (this.config = config);
request && (this.request = request);
if (response) {
this.response = response;
this.status = response.status;
}
}
toJSON() {
// Opt-in redaction: when the request config carries a `redact` array, the
// value of any matching key (case-insensitive, at any depth) is replaced
// with REDACTED in the serialized snapshot. Undefined or empty leaves the
// existing serialization behavior unchanged.
const config = this.config;
const redactKeys = config && utils.hasOwnProp(config, 'redact') ? config.redact : undefined;
const serializedConfig =
utils.isArray(redactKeys) && redactKeys.length > 0
? redactConfig(config, redactKeys)
: utils.toJSONObject(config);
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: serializedConfig,
code: this.code,
status: this.status,
};
}
}
// This can be changed to static properties as soon as the parser options in .eslint.cjs are updated.
AxiosError.ERR_BAD_OPTION_VALUE = 'ERR_BAD_OPTION_VALUE';
AxiosError.ERR_BAD_OPTION = 'ERR_BAD_OPTION';
AxiosError.ECONNABORTED = 'ECONNABORTED';
AxiosError.ETIMEDOUT = 'ETIMEDOUT';
AxiosError.ECONNREFUSED = 'ECONNREFUSED';
AxiosError.ERR_NETWORK = 'ERR_NETWORK';
AxiosError.ERR_FR_TOO_MANY_REDIRECTS = 'ERR_FR_TOO_MANY_REDIRECTS';
AxiosError.ERR_DEPRECATED = 'ERR_DEPRECATED';
AxiosError.ERR_BAD_RESPONSE = 'ERR_BAD_RESPONSE';
AxiosError.ERR_BAD_REQUEST = 'ERR_BAD_REQUEST';
AxiosError.ERR_CANCELED = 'ERR_CANCELED';
AxiosError.ERR_NOT_SUPPORT = 'ERR_NOT_SUPPORT';
AxiosError.ERR_INVALID_URL = 'ERR_INVALID_URL';
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED = 'ERR_FORM_DATA_DEPTH_EXCEEDED';
export default AxiosError;
+351
View File
@@ -0,0 +1,351 @@
'use strict';
import utils from '../utils.js';
import parseHeaders from '../helpers/parseHeaders.js';
import { sanitizeHeaderValue } from '../helpers/sanitizeHeaderValue.js';
const $internals = Symbol('internals');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return utils.isArray(value) ? value.map(normalizeValue) : sanitizeHeaderValue(String(value));
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
const isValidHeaderName = (str) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str.trim());
function matchHeaderValue(context, value, header, filter, isHeaderNameFilter) {
if (utils.isFunction(filter)) {
return filter.call(this, value, header);
}
if (isHeaderNameFilter) {
value = header;
}
if (!utils.isString(value)) return;
if (utils.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header
.trim()
.toLowerCase()
.replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach((methodName) => {
Object.defineProperty(obj, methodName + accessorName, {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: function (arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true,
});
});
}
class AxiosHeaders {
constructor(headers) {
headers && this.set(headers);
}
set(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
return;
}
const key = utils.findKey(self, lHeader);
if (
!key ||
self[key] === undefined ||
_rewrite === true ||
(_rewrite === undefined && self[key] !== false)
) {
self[key || _header] = normalizeValue(_value);
}
}
const setHeaders = (headers, _rewrite) =>
utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));
if (utils.isPlainObject(header) || header instanceof this.constructor) {
setHeaders(header, valueOrRewrite);
} else if (utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
setHeaders(parseHeaders(header), valueOrRewrite);
} else if (utils.isObject(header) && utils.isSafeIterable(header)) {
let obj = Object.create(null),
dest,
key;
for (const entry of header) {
if (!utils.isArray(entry)) {
throw new TypeError('Object iterator must return a key-value pair');
}
key = entry[0];
if (utils.hasOwnProp(obj, key)) {
dest = obj[key];
obj[key] = utils.isArray(dest) ? [...dest, entry[1]] : [dest, entry[1]];
} else {
obj[key] = entry[1];
}
}
setHeaders(obj, valueOrRewrite);
} else {
header != null && setHeader(valueOrRewrite, header, rewrite);
}
return this;
}
get(header, parser) {
header = normalizeHeader(header);
if (header) {
const key = utils.findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
}
}
has(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = utils.findKey(this, header);
return !!(
key &&
this[key] !== undefined &&
(!matcher || matchHeaderValue(this, this[key], key, matcher))
);
}
return false;
}
delete(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = utils.findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
}
clear(matcher) {
const keys = Object.keys(this);
let i = keys.length;
let deleted = false;
while (i--) {
const key = keys[i];
if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
delete this[key];
deleted = true;
}
}
return deleted;
}
normalize(format) {
const self = this;
const headers = {};
utils.forEach(this, (value, header) => {
const key = utils.findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
}
concat(...targets) {
return this.constructor.concat(this, ...targets);
}
toJSON(asStrings) {
const obj = Object.create(null);
utils.forEach(this, (value, header) => {
value != null &&
value !== false &&
(obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
});
return obj;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON())
.map(([header, value]) => header + ': ' + value)
.join('\n');
}
getSetCookie() {
return this.get('set-cookie') || [];
}
get [Symbol.toStringTag]() {
return 'AxiosHeaders';
}
static from(thing) {
return thing instanceof this ? thing : new this(thing);
}
static concat(first, ...targets) {
const computed = new this(first);
targets.forEach((target) => computed.set(target));
return computed;
}
static accessor(header) {
const internals =
(this[$internals] =
this[$internals] =
{
accessors: {},
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
}
AxiosHeaders.accessor([
'Content-Type',
'Content-Length',
'Accept',
'Accept-Encoding',
'User-Agent',
'Authorization',
]);
// reserved names hotfix
utils.reduceDescriptors(AxiosHeaders.prototype, ({ value }, key) => {
let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set`
return {
get: () => value,
set(headerValue) {
this[mapped] = headerValue;
},
};
});
utils.freezeMethods(AxiosHeaders);
export default AxiosHeaders;
+72
View File
@@ -0,0 +1,72 @@
'use strict';
import utils from '../utils.js';
class InterceptorManager {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
* @param {Object} options The options for the interceptor, synchronous and runWhen
*
* @return {Number} An ID used to remove interceptor later
*/
use(fulfilled, rejected, options) {
this.handlers.push({
fulfilled,
rejected,
synchronous: options ? options.synchronous : false,
runWhen: options ? options.runWhen : null,
});
return this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {void}
*/
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
if (this.handlers) {
this.handlers = [];
}
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
}
}
export default InterceptorManager;
+8
View File
@@ -0,0 +1,8 @@
# axios // core
The modules found in `core/` should be modules that are specific to the domain logic of axios. These modules would most likely not make sense to be consumed outside of the axios module, as their logic is too specific. Some examples of core modules are:
- Dispatching requests
- Requests sent via `adapters/` (see lib/adapters/README.md)
- Managing interceptors
- Handling config
+50
View File
@@ -0,0 +1,50 @@
'use strict';
import AxiosError from './AxiosError.js';
import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
import combineURLs from '../helpers/combineURLs.js';
const malformedHttpProtocol = /^https?:(?!\/\/)/i;
const httpProtocolControlCharacters = /[\t\n\r]/g;
function stripLeadingC0ControlOrSpace(url) {
let i = 0;
while (i < url.length && url.charCodeAt(i) <= 0x20) {
i++;
}
return url.slice(i);
}
function normalizeURLForProtocolCheck(url) {
return stripLeadingC0ControlOrSpace(url).replace(httpProtocolControlCharacters, '');
}
function assertValidHttpProtocolURL(url, config) {
if (typeof url === 'string' && malformedHttpProtocol.test(normalizeURLForProtocolCheck(url))) {
throw new AxiosError(
'Invalid URL: missing "//" after protocol',
AxiosError.ERR_INVALID_URL,
config
);
}
}
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
*
* @returns {string} The combined full path
*/
export default function buildFullPath(baseURL, requestedURL, allowAbsoluteUrls, config) {
assertValidHttpProtocolURL(requestedURL, config);
let isRelativeUrl = !isAbsoluteURL(requestedURL);
if (baseURL && (isRelativeUrl || allowAbsoluteUrls === false)) {
assertValidHttpProtocolURL(baseURL, config);
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
}
+89
View File
@@ -0,0 +1,89 @@
'use strict';
import transformData from './transformData.js';
import isCancel from '../cancel/isCancel.js';
import defaults from '../defaults/index.js';
import CanceledError from '../cancel/CanceledError.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import adapters from '../adapters/adapters.js';
/**
* Throws a `CanceledError` if cancellation has been requested.
*
* @param {Object} config The config that is to be used for the request
*
* @returns {void}
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
if (config.signal && config.signal.aborted) {
throw new CanceledError(null, config);
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
*
* @returns {Promise} The Promise to be fulfilled
*/
export default function dispatchRequest(config) {
throwIfCancellationRequested(config);
config.headers = AxiosHeaders.from(config.headers);
// Transform request data
config.data = transformData.call(config, config.transformRequest);
if (['post', 'put', 'patch'].indexOf(config.method) !== -1) {
config.headers.setContentType('application/x-www-form-urlencoded', false);
}
const adapter = adapters.getAdapter(config.adapter || defaults.adapter, config);
return adapter(config).then(
function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Expose the current response on config so that transformResponse can
// attach it to any AxiosError it throws (e.g. on JSON parse failure).
// We clean it up afterwards to avoid polluting the config object.
config.response = response;
try {
response.data = transformData.call(config, config.transformResponse, response);
} finally {
delete config.response;
}
response.headers = AxiosHeaders.from(response.headers);
return response;
},
function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
config.response = reason.response;
try {
reason.response.data = transformData.call(
config,
config.transformResponse,
reason.response
);
} finally {
delete config.response;
}
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}
return Promise.reject(reason);
}
);
}
+159
View File
@@ -0,0 +1,159 @@
'use strict';
import utils from '../utils.js';
import AxiosHeaders from './AxiosHeaders.js';
const headersToObject = (thing) => (thing instanceof AxiosHeaders ? { ...thing } : thing);
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
*
* @returns {Object} New object resulting from merging config2 to config1
*/
export default function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config1 = config1 || {};
config2 = config2 || {};
// Use a null-prototype object so that downstream reads such as `config.auth`
// or `config.baseURL` cannot inherit polluted values from Object.prototype.
// `hasOwnProperty` is restored as a non-enumerable own slot to preserve
// ergonomics for user code that relies on it.
const config = Object.create(null);
Object.defineProperty(config, 'hasOwnProperty', {
// Null-proto descriptor so a polluted Object.prototype.get cannot turn
// this data descriptor into an accessor descriptor on the way in.
__proto__: null,
value: Object.prototype.hasOwnProperty,
enumerable: false,
writable: true,
configurable: true,
});
function getMergedValue(target, source, prop, caseless) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
return utils.merge.call({ caseless }, target, source);
} else if (utils.isPlainObject(source)) {
return utils.merge({}, source);
} else if (utils.isArray(source)) {
return source.slice();
}
return source;
}
function mergeDeepProperties(a, b, prop, caseless) {
if (!utils.isUndefined(b)) {
return getMergedValue(a, b, prop, caseless);
} else if (!utils.isUndefined(a)) {
return getMergedValue(undefined, a, prop, caseless);
}
}
// eslint-disable-next-line consistent-return
function valueFromConfig2(a, b) {
if (!utils.isUndefined(b)) {
return getMergedValue(undefined, b);
}
}
// eslint-disable-next-line consistent-return
function defaultToConfig2(a, b) {
if (!utils.isUndefined(b)) {
return getMergedValue(undefined, b);
} else if (!utils.isUndefined(a)) {
return getMergedValue(undefined, a);
}
}
function getMergedTransitionalOption(prop) {
const transitional2 = utils.hasOwnProp(config2, 'transitional') ? config2.transitional : undefined;
if (!utils.isUndefined(transitional2)) {
if (utils.isPlainObject(transitional2)) {
if (utils.hasOwnProp(transitional2, prop)) {
return transitional2[prop];
}
} else {
return undefined;
}
}
const transitional1 = utils.hasOwnProp(config1, 'transitional') ? config1.transitional : undefined;
if (utils.isPlainObject(transitional1) && utils.hasOwnProp(transitional1, prop)) {
return transitional1[prop];
}
return undefined;
}
// eslint-disable-next-line consistent-return
function mergeDirectKeys(a, b, prop) {
if (utils.hasOwnProp(config2, prop)) {
return getMergedValue(a, b);
} else if (utils.hasOwnProp(config1, prop)) {
return getMergedValue(undefined, a);
}
}
const mergeMap = {
url: valueFromConfig2,
method: valueFromConfig2,
data: valueFromConfig2,
baseURL: defaultToConfig2,
transformRequest: defaultToConfig2,
transformResponse: defaultToConfig2,
paramsSerializer: defaultToConfig2,
timeout: defaultToConfig2,
timeoutMessage: defaultToConfig2,
withCredentials: defaultToConfig2,
withXSRFToken: defaultToConfig2,
adapter: defaultToConfig2,
responseType: defaultToConfig2,
xsrfCookieName: defaultToConfig2,
xsrfHeaderName: defaultToConfig2,
onUploadProgress: defaultToConfig2,
onDownloadProgress: defaultToConfig2,
decompress: defaultToConfig2,
maxContentLength: defaultToConfig2,
maxBodyLength: defaultToConfig2,
beforeRedirect: defaultToConfig2,
transport: defaultToConfig2,
httpAgent: defaultToConfig2,
httpsAgent: defaultToConfig2,
cancelToken: defaultToConfig2,
socketPath: defaultToConfig2,
allowedSocketPaths: defaultToConfig2,
responseEncoding: defaultToConfig2,
validateStatus: mergeDirectKeys,
headers: (a, b, prop) =>
mergeDeepProperties(headersToObject(a), headersToObject(b), prop, true),
};
utils.forEach(Object.keys({ ...config1, ...config2 }), function computeConfigValue(prop) {
if (prop === '__proto__' || prop === 'constructor' || prop === 'prototype') return;
const merge = utils.hasOwnProp(mergeMap, prop) ? mergeMap[prop] : mergeDeepProperties;
const a = utils.hasOwnProp(config1, prop) ? config1[prop] : undefined;
const b = utils.hasOwnProp(config2, prop) ? config2[prop] : undefined;
const configValue = merge(a, b, prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
if (
utils.hasOwnProp(config2, 'validateStatus') &&
utils.isUndefined(config2.validateStatus) &&
getMergedTransitionalOption('validateStatusUndefinedResolves') === false
) {
if (utils.hasOwnProp(config1, 'validateStatus')) {
config.validateStatus = getMergedValue(undefined, config1.validateStatus);
} else {
delete config.validateStatus;
}
}
return config;
}
+27
View File
@@ -0,0 +1,27 @@
'use strict';
import AxiosError from './AxiosError.js';
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*
* @returns {object} The response.
*/
export default function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(new AxiosError(
'Request failed with status code ' + response.status,
response.status >= 400 && response.status < 500 ? AxiosError.ERR_BAD_REQUEST : AxiosError.ERR_BAD_RESPONSE,
response.config,
response.request,
response
));
}
}
+28
View File
@@ -0,0 +1,28 @@
'use strict';
import utils from '../utils.js';
import defaults from '../defaults/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
/**
* Transform the data for a request or a response
*
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
export default function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders.from(context.headers);
let data = context.data;
utils.forEach(fns, function transform(fn) {
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
}
+177
View File
@@ -0,0 +1,177 @@
'use strict';
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import transitionalDefaults from './transitional.js';
import toFormData from '../helpers/toFormData.js';
import toURLEncodedForm from '../helpers/toURLEncodedForm.js';
import platform from '../platform/index.js';
import formDataToJSON from '../helpers/formDataToJSON.js';
const own = (obj, key) => (obj != null && utils.hasOwnProp(obj, key) ? obj[key] : undefined);
/**
* It takes a string, tries to parse it, and if it fails, it returns the stringified version
* of the input
*
* @param {any} rawValue - The value to be stringified.
* @param {Function} parser - A function that parses a string into a JavaScript object.
* @param {Function} encoder - A function that takes a value and returns a string.
*
* @returns {string} A stringified version of the rawValue.
*/
function stringifySafely(rawValue, parser, encoder) {
if (utils.isString(rawValue)) {
try {
(parser || JSON.parse)(rawValue);
return utils.trim(rawValue);
} catch (e) {
if (e.name !== 'SyntaxError') {
throw e;
}
}
}
return (encoder || JSON.stringify)(rawValue);
}
const defaults = {
transitional: transitionalDefaults,
adapter: ['xhr', 'http', 'fetch'],
transformRequest: [
function transformRequest(data, headers) {
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils.isObject(data);
if (isObjectPayload && utils.isHTMLForm(data)) {
data = new FormData(data);
}
const isFormData = utils.isFormData(data);
if (isFormData) {
return hasJSONContentType ? JSON.stringify(formDataToJSON(data)) : data;
}
if (
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data) ||
utils.isReadableStream(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
let isFileList;
if (isObjectPayload) {
const formSerializer = own(this, 'formSerializer');
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, formSerializer).toString();
}
if (
(isFileList = utils.isFileList(data)) ||
contentType.indexOf('multipart/form-data') > -1
) {
const env = own(this, 'env');
const _FormData = env && env.FormData;
return toFormData(
isFileList ? { 'files[]': data } : data,
_FormData && new _FormData(),
formSerializer
);
}
}
if (isObjectPayload || hasJSONContentType) {
headers.setContentType('application/json', false);
return stringifySafely(data);
}
return data;
},
],
transformResponse: [
function transformResponse(data) {
const transitional = own(this, 'transitional') || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const responseType = own(this, 'responseType');
const JSONRequested = responseType === 'json';
if (utils.isResponse(data) || utils.isReadableStream(data)) {
return data;
}
if (
data &&
utils.isString(data) &&
((forcedJSONParsing && !responseType) || JSONRequested)
) {
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data, own(this, 'parseReviver'));
} catch (e) {
if (strictJSONParsing) {
if (e.name === 'SyntaxError') {
throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, own(this, 'response'));
}
throw e;
}
}
}
return data;
},
],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: platform.classes.FormData,
Blob: platform.classes.Blob,
},
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
},
headers: {
common: {
Accept: 'application/json, text/plain, */*',
'Content-Type': undefined,
},
},
};
utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'query'], (method) => {
defaults.headers[method] = {};
});
export default defaults;
+10
View File
@@ -0,0 +1,10 @@
'use strict';
export default {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false,
legacyInterceptorReqResOrdering: true,
advertiseZstdAcceptEncoding: false,
validateStatusUndefinedResolves: true,
};
+3
View File
@@ -0,0 +1,3 @@
# axios // env
The `data.js` file is updated automatically when the package version is upgrading. Please do not edit it manually.
+2
View File
@@ -0,0 +1,2 @@
import _FormData from 'form-data';
export default typeof FormData !== 'undefined' ? FormData : _FormData;
+1
View File
@@ -0,0 +1 @@
export const VERSION = "1.18.1";
+156
View File
@@ -0,0 +1,156 @@
'use strict';
import stream from 'stream';
import utils from '../utils.js';
const kInternals = Symbol('internals');
class AxiosTransformStream extends stream.Transform {
constructor(options) {
options = utils.toFlatObject(
options,
{
maxRate: 0,
chunkSize: 64 * 1024,
minChunkSize: 100,
timeWindow: 500,
ticksRate: 2,
samplesCount: 15,
},
null,
(prop, source) => {
return !utils.isUndefined(source[prop]);
}
);
super({
readableHighWaterMark: options.chunkSize,
});
const internals = (this[kInternals] = {
timeWindow: options.timeWindow,
chunkSize: options.chunkSize,
maxRate: options.maxRate,
minChunkSize: options.minChunkSize,
bytesSeen: 0,
isCaptured: false,
notifiedBytesLoaded: 0,
ts: Date.now(),
bytes: 0,
onReadCallback: null,
});
this.on('newListener', (event) => {
if (event === 'progress') {
if (!internals.isCaptured) {
internals.isCaptured = true;
}
}
});
}
_read(size) {
const internals = this[kInternals];
if (internals.onReadCallback) {
internals.onReadCallback();
}
return super._read(size);
}
_transform(chunk, encoding, callback) {
const internals = this[kInternals];
const maxRate = internals.maxRate;
const readableHighWaterMark = this.readableHighWaterMark;
const timeWindow = internals.timeWindow;
const divider = 1000 / timeWindow;
const bytesThreshold = maxRate / divider;
const minChunkSize =
internals.minChunkSize !== false
? Math.max(internals.minChunkSize, bytesThreshold * 0.01)
: 0;
const pushChunk = (_chunk, _callback) => {
const bytes = Buffer.byteLength(_chunk);
internals.bytesSeen += bytes;
internals.bytes += bytes;
internals.isCaptured && this.emit('progress', internals.bytesSeen);
if (this.push(_chunk)) {
process.nextTick(_callback);
} else {
internals.onReadCallback = () => {
internals.onReadCallback = null;
process.nextTick(_callback);
};
}
};
const transformChunk = (_chunk, _callback) => {
const chunkSize = Buffer.byteLength(_chunk);
let chunkRemainder = null;
let maxChunkSize = readableHighWaterMark;
let bytesLeft;
let passed = 0;
if (maxRate) {
const now = Date.now();
if (!internals.ts || (passed = now - internals.ts) >= timeWindow) {
internals.ts = now;
bytesLeft = bytesThreshold - internals.bytes;
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
passed = 0;
}
bytesLeft = bytesThreshold - internals.bytes;
}
if (maxRate) {
if (bytesLeft <= 0) {
// next time window
return setTimeout(() => {
_callback(null, _chunk);
}, timeWindow - passed);
}
if (bytesLeft < maxChunkSize) {
maxChunkSize = bytesLeft;
}
}
if (maxChunkSize && chunkSize > maxChunkSize && chunkSize - maxChunkSize > minChunkSize) {
chunkRemainder = _chunk.subarray(maxChunkSize);
_chunk = _chunk.subarray(0, maxChunkSize);
}
pushChunk(
_chunk,
chunkRemainder
? () => {
process.nextTick(_callback, null, chunkRemainder);
}
: _callback
);
};
transformChunk(chunk, function transformNextChunk(err, _chunk) {
if (err) {
return callback(err);
}
if (_chunk) {
transformChunk(_chunk, transformNextChunk);
} else {
callback(null);
}
});
}
}
export default AxiosTransformStream;
+59
View File
@@ -0,0 +1,59 @@
'use strict';
import toFormData from './toFormData.js';
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
* their percent-encoded equivalents
*
* @param {string} str - The string to encode.
*
* @returns {string} The encoded string.
*/
function encode(str) {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
')': '%29',
'~': '%7E',
'%20': '+',
};
return encodeURIComponent(str).replace(/[!'()~]|%20/g, function replacer(match) {
return charMap[match];
});
}
/**
* It takes a params object and converts it to a FormData object
*
* @param {Object<string, any>} params - The parameters to be converted to a FormData object.
* @param {Object<string, any>} options - The options object passed to the Axios constructor.
*
* @returns {void}
*/
function AxiosURLSearchParams(params, options) {
this._pairs = [];
params && toFormData(params, this, options);
}
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
const _encode = encoder
? (value) => encoder.call(this, value, encode)
: encode;
return this._pairs
.map(function each(pair) {
return _encode(pair[0]) + '=' + _encode(pair[1]);
}, '')
.join('&');
};
export default AxiosURLSearchParams;
+119
View File
@@ -0,0 +1,119 @@
'use strict';
// Node-only: relies on the built-in `http2` module. Browser/react-native
// builds replace `lib/adapters/http.js` (the sole importer) with `lib/helpers/null.js`
// via the `browser` package.json field, so this module is never reached in
// those environments. Do not import it from any browser-reachable code path.
import http2 from 'http2';
import util from 'util';
class Http2Sessions {
constructor() {
this.sessions = Object.create(null);
}
getSession(authority, options) {
options = Object.assign(
{
sessionTimeout: 1000,
},
options
);
let authoritySessions = this.sessions[authority];
if (authoritySessions) {
let len = authoritySessions.length;
for (let i = 0; i < len; i++) {
const [sessionHandle, sessionOptions] = authoritySessions[i];
if (
!sessionHandle.destroyed &&
!sessionHandle.closed &&
util.isDeepStrictEqual(sessionOptions, options)
) {
return sessionHandle;
}
}
}
const session = http2.connect(authority, options);
let removed;
let timer;
const removeSession = () => {
if (removed) {
return;
}
removed = true;
if (timer) {
clearTimeout(timer);
timer = null;
}
let entries = authoritySessions,
len = entries.length,
i = len;
while (i--) {
if (entries[i][0] === session) {
if (len === 1) {
delete this.sessions[authority];
} else {
entries.splice(i, 1);
}
if (!session.closed) {
session.close();
}
return;
}
}
};
const originalRequestFn = session.request;
const { sessionTimeout } = options;
if (sessionTimeout != null) {
let streamsCount = 0;
session.request = function () {
const stream = originalRequestFn.apply(this, arguments);
streamsCount++;
if (timer) {
clearTimeout(timer);
timer = null;
}
stream.once('close', () => {
if (!--streamsCount) {
timer = setTimeout(() => {
timer = null;
removeSession();
}, sessionTimeout);
}
});
return stream;
};
}
session.once('close', removeSession);
let entry = [session, options];
authoritySessions
? authoritySessions.push(entry)
: (authoritySessions = this.sessions[authority] = [entry]);
return session;
}
}
export default Http2Sessions;
+77
View File
@@ -0,0 +1,77 @@
const HttpStatusCode = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511,
WebServerIsDown: 521,
ConnectionTimedOut: 522,
OriginIsUnreachable: 523,
TimeoutOccurred: 524,
SslHandshakeFailed: 525,
InvalidSslCertificate: 526,
};
Object.entries(HttpStatusCode).forEach(([key, value]) => {
HttpStatusCode[value] = key;
});
export default HttpStatusCode;
+7
View File
@@ -0,0 +1,7 @@
# axios // helpers
The modules found in `helpers/` should be generic modules that are _not_ specific to the domain logic of axios. These modules could theoretically be published to npm on their own and consumed by other modules or apps. Some examples of generic modules are things like:
- Browser polyfills
- Managing cookies
- Parsing HTTP headers
+29
View File
@@ -0,0 +1,29 @@
'use strict';
import stream from 'stream';
class ZlibHeaderTransformStream extends stream.Transform {
__transform(chunk, encoding, callback) {
this.push(chunk);
callback();
}
_transform(chunk, encoding, callback) {
if (chunk.length !== 0) {
this._transform = this.__transform;
// Add Default Compression headers if no zlib headers are present
if (chunk[0] !== 120) {
// Hex: 78
const header = Buffer.alloc(2);
header[0] = 120; // Hex: 78
header[1] = 156; // Hex: 9C
this.push(header, encoding);
}
}
this.__transform(chunk, encoding, callback);
}
}
export default ZlibHeaderTransformStream;
+14
View File
@@ -0,0 +1,14 @@
'use strict';
/**
* Create a bound version of a function with a specified `this` context
*
* @param {Function} fn - The function to bind
* @param {*} thisArg - The value to be passed as the `this` parameter
* @returns {Function} A new function that will call the original function with the specified `this` context
*/
export default function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
}
+69
View File
@@ -0,0 +1,69 @@
'use strict';
import utils from '../utils.js';
import AxiosURLSearchParams from './AxiosURLSearchParams.js';
/**
* It replaces URL-encoded forms of `:`, `$`, `,`, and spaces with
* their plain counterparts (`:`, `$`, `,`, `+`).
*
* @param {string} val The value to be encoded.
*
* @returns {string} The encoded value.
*/
export function encode(val) {
return encodeURIComponent(val)
.replace(/%3A/gi, ':')
.replace(/%24/g, '$')
.replace(/%2C/gi, ',')
.replace(/%20/g, '+');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @param {?(object|Function)} options
*
* @returns {string} The formatted url
*/
export default function buildURL(url, params, options) {
if (!params) {
return url;
}
url = url || '';
const _options = utils.isFunction(options)
? {
serialize: options,
}
: options;
// Read serializer options pollution-safely: own properties and methods on a
// class/template prototype are honored, but values injected onto a polluted
// Object.prototype are ignored.
const _encode = utils.getSafeProp(_options, 'encode') || encode;
const serializeFn = utils.getSafeProp(_options, 'serialize');
let serializedParams;
if (serializeFn) {
serializedParams = serializeFn(params, _options);
} else {
serializedParams = utils.isURLSearchParams(params)
? params.toString()
: new AxiosURLSearchParams(params, _options).toString(_encode);
}
if (serializedParams) {
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
}
+18
View File
@@ -0,0 +1,18 @@
import utils from '../utils.js';
const callbackify = (fn, reducer) => {
return utils.isAsyncFn(fn)
? function (...args) {
const cb = args.pop();
fn.apply(this, args).then((value) => {
try {
reducer ? cb(null, ...reducer(value)) : cb(null, value);
} catch (err) {
cb(err);
}
}, cb);
}
: fn;
};
export default callbackify;
+15
View File
@@ -0,0 +1,15 @@
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
*
* @returns {string} The combined URL
*/
export default function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/?\/$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
}
+57
View File
@@ -0,0 +1,57 @@
import CanceledError from '../cancel/CanceledError.js';
import AxiosError from '../core/AxiosError.js';
import utils from '../utils.js';
const composeSignals = (signals, timeout) => {
signals = signals ? signals.filter(Boolean) : [];
if (!timeout && !signals.length) {
return;
}
const controller = new AbortController();
let aborted = false;
const onabort = function (reason) {
if (!aborted) {
aborted = true;
unsubscribe();
const err = reason instanceof Error ? reason : this.reason;
controller.abort(
err instanceof AxiosError
? err
: new CanceledError(err instanceof Error ? err.message : err)
);
}
};
let timer =
timeout &&
setTimeout(() => {
timer = null;
onabort(new AxiosError(`timeout of ${timeout}ms exceeded`, AxiosError.ETIMEDOUT));
}, timeout);
const unsubscribe = () => {
if (!signals) { return; }
timer && clearTimeout(timer);
timer = null;
signals.forEach((signal) => {
signal.unsubscribe
? signal.unsubscribe(onabort)
: signal.removeEventListener('abort', onabort);
});
signals = null;
};
signals.forEach((signal) => signal.addEventListener('abort', onabort, { once: true }));
const { signal } = controller;
signal.unsubscribe = () => utils.asap(unsubscribe);
return signal;
};
export default composeSignals;
+64
View File
@@ -0,0 +1,64 @@
import utils from '../utils.js';
import platform from '../platform/index.js';
export default platform.hasStandardBrowserEnv
? // Standard browser envs support document.cookie
{
write(name, value, expires, path, domain, secure, sameSite) {
if (typeof document === 'undefined') return;
const cookie = [`${name}=${encodeURIComponent(value)}`];
if (utils.isNumber(expires)) {
cookie.push(`expires=${new Date(expires).toUTCString()}`);
}
if (utils.isString(path)) {
cookie.push(`path=${path}`);
}
if (utils.isString(domain)) {
cookie.push(`domain=${domain}`);
}
if (secure === true) {
cookie.push('secure');
}
if (utils.isString(sameSite)) {
cookie.push(`SameSite=${sameSite}`);
}
document.cookie = cookie.join('; ');
},
read(name) {
if (typeof document === 'undefined') return null;
// Match name=value by splitting on the semicolon separator instead of building a
// RegExp from `name` — interpolating an unescaped string into a RegExp would let
// metacharacters (e.g. `.+?` in an attacker-influenced cookie name) cause ReDoS or
// match the wrong cookie. Browsers may serialize cookie pairs as either ";" or
// "; ", so ignore optional whitespace before each cookie name.
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].replace(/^\s+/, '');
const eq = cookie.indexOf('=');
if (eq !== -1 && cookie.slice(0, eq) === name) {
try {
return decodeURIComponent(cookie.slice(eq + 1));
} catch (e) {
return cookie.slice(eq + 1);
}
}
}
return null;
},
remove(name) {
this.write(name, '', Date.now() - 86400000, '/');
},
}
: // Non-standard browser env (web workers, react-native) lack needed support.
{
write() {},
read() {
return null;
},
remove() {},
};
+31
View File
@@ -0,0 +1,31 @@
'use strict';
/*eslint no-console:0*/
/**
* Supply a warning to the developer that a method they are using
* has been deprecated.
*
* @param {string} method The name of the deprecated method
* @param {string} [instead] The alternate method to use if applicable
* @param {string} [docs] The documentation URL to get further details
*
* @returns {void}
*/
export default function deprecatedMethod(method, instead, docs) {
try {
console.warn(
'DEPRECATED method `' +
method +
'`.' +
(instead ? ' Use `' + instead + '` instead.' : '') +
' This method will be removed in a future release.'
);
if (docs) {
console.warn('For more information about usage see ' + docs);
}
} catch (e) {
/* Ignore */
}
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Estimate decoded byte length of a data:// URL *without* allocating large buffers.
* - For base64: compute exact decoded size using length and padding;
* handle %XX at the character-count level (no string allocation).
* - For non-base64: compute the exact percent-decoded UTF-8 byte length.
*
* @param {string} url
* @returns {number}
*/
const isHexDigit = (charCode) =>
(charCode >= 48 && charCode <= 57) ||
(charCode >= 65 && charCode <= 70) ||
(charCode >= 97 && charCode <= 102);
const isPercentEncodedByte = (str, i, len) =>
i + 2 < len && isHexDigit(str.charCodeAt(i + 1)) && isHexDigit(str.charCodeAt(i + 2));
export default function estimateDataURLDecodedBytes(url) {
if (!url || typeof url !== 'string') return 0;
if (!url.startsWith('data:')) return 0;
const comma = url.indexOf(',');
if (comma < 0) return 0;
const meta = url.slice(5, comma);
const body = url.slice(comma + 1);
const isBase64 = /;base64/i.test(meta);
if (isBase64) {
let effectiveLen = body.length;
const len = body.length; // cache length
for (let i = 0; i < len; i++) {
if (body.charCodeAt(i) === 37 /* '%' */ && i + 2 < len) {
const a = body.charCodeAt(i + 1);
const b = body.charCodeAt(i + 2);
const isHex = isHexDigit(a) && isHexDigit(b);
if (isHex) {
effectiveLen -= 2;
i += 2;
}
}
}
let pad = 0;
let idx = len - 1;
const tailIsPct3D = (j) =>
j >= 2 &&
body.charCodeAt(j - 2) === 37 && // '%'
body.charCodeAt(j - 1) === 51 && // '3'
(body.charCodeAt(j) === 68 || body.charCodeAt(j) === 100); // 'D' or 'd'
if (idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
idx--;
} else if (tailIsPct3D(idx)) {
pad++;
idx -= 3;
}
}
if (pad === 1 && idx >= 0) {
if (body.charCodeAt(idx) === 61 /* '=' */) {
pad++;
} else if (tailIsPct3D(idx)) {
pad++;
}
}
const groups = Math.floor(effectiveLen / 4);
const bytes = groups * 3 - (pad || 0);
return bytes > 0 ? bytes : 0;
}
// Compute UTF-8 byte length directly from UTF-16 code units without allocating
// a byte buffer (TextEncoder.encode would defeat the DoS guard on large bodies).
// Valid %XX triplets count as one decoded byte; this matches the bytes that
// decodeURIComponent(body) would produce before Buffer re-encodes the string.
let bytes = 0;
for (let i = 0, len = body.length; i < len; i++) {
const c = body.charCodeAt(i);
if (c === 37 /* '%' */ && isPercentEncodedByte(body, i, len)) {
bytes += 1;
i += 2;
} else if (c < 0x80) {
bytes += 1;
} else if (c < 0x800) {
bytes += 2;
} else if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
const next = body.charCodeAt(i + 1);
if (next >= 0xdc00 && next <= 0xdfff) {
bytes += 4;
i++;
} else {
bytes += 3;
}
} else {
bytes += 3;
}
}
return bytes;
}
+119
View File
@@ -0,0 +1,119 @@
'use strict';
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import { DEFAULT_FORM_DATA_MAX_DEPTH } from './toFormData.js';
const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
function throwIfDepthExceeded(index) {
if (index > MAX_DEPTH) {
throw new AxiosError(
'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
);
}
}
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
*
* @param {string} name - The name of the property to get.
*
* @returns An array of strings.
*/
function parsePropPath(name) {
// foo[x][y][z]
// foo.x.y.z
// foo-x-y-z
// foo x y z
const path = [];
const pattern = /\w+|\[(\w*)]/g;
let match;
while ((match = pattern.exec(name)) !== null) {
throwIfDepthExceeded(path.length);
path.push(match[0] === '[]' ? '' : match[1] || match[0]);
}
return path;
}
/**
* Convert an array to an object.
*
* @param {Array<any>} arr - The array to convert to an object.
*
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
}
return obj;
}
/**
* It takes a FormData object and returns a JavaScript object
*
* @param {string} formData The FormData object to convert to JSON.
*
* @returns {Object<string, any> | null} The converted object.
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
throwIfDepthExceeded(index);
let name = path[index++];
if (name === '__proto__') return true;
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils.isArray(target) ? target.length : name;
if (isLast) {
if (utils.hasOwnProp(target, name)) {
target[name] = utils.isArray(target[name])
? target[name].concat(value)
: [target[name], value];
} else {
target[name] = value;
}
return !isNumericKey;
}
if (!utils.hasOwnProp(target, name) || !utils.isObject(target[name])) {
target[name] = [];
}
const result = buildPath(path, value, target[name], index);
if (result && utils.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
}
return !isNumericKey;
}
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
const obj = {};
utils.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
return obj;
}
return null;
}
export default formDataToJSON;
+119
View File
@@ -0,0 +1,119 @@
import util from 'util';
import { Readable } from 'stream';
import utils from '../utils.js';
import readBlob from './readBlob.js';
import platform from '../platform/index.js';
const BOUNDARY_ALPHABET = platform.ALPHABET.ALPHA_DIGIT + '-_';
const textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : new util.TextEncoder();
const CRLF = '\r\n';
const CRLF_BYTES = textEncoder.encode(CRLF);
const CRLF_BYTES_COUNT = 2;
class FormDataPart {
constructor(name, value) {
const { escapeName } = this.constructor;
const isStringValue = utils.isString(value);
let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${
!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ''
}${CRLF}`;
if (isStringValue) {
value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF));
} else {
const safeType = String(value.type || 'application/octet-stream').replace(/[\r\n]/g, '');
headers += `Content-Type: ${safeType}${CRLF}`;
}
this.headers = textEncoder.encode(headers + CRLF);
this.contentLength = isStringValue ? value.byteLength : value.size;
this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT;
this.name = name;
this.value = value;
}
async *encode() {
yield this.headers;
const { value } = this;
if (utils.isTypedArray(value)) {
yield value;
} else {
yield* readBlob(value);
}
yield CRLF_BYTES;
}
static escapeName(name) {
return String(name).replace(
/[\r\n"]/g,
(match) =>
({
'\r': '%0D',
'\n': '%0A',
'"': '%22',
})[match]
);
}
}
const formDataToStream = (form, headersHandler, options) => {
const {
tag = 'form-data-boundary',
size = 25,
boundary = tag + '-' + platform.generateString(size, BOUNDARY_ALPHABET),
} = options || {};
if (!utils.isFormData(form)) {
throw new TypeError('FormData instance required');
}
if (boundary.length < 1 || boundary.length > 70) {
throw new Error('boundary must be 1-70 characters long');
}
const boundaryBytes = textEncoder.encode('--' + boundary + CRLF);
const footerBytes = textEncoder.encode('--' + boundary + '--' + CRLF);
let contentLength = footerBytes.byteLength;
const parts = Array.from(form.entries()).map(([name, value]) => {
const part = new FormDataPart(name, value);
contentLength += part.size;
return part;
});
contentLength += boundaryBytes.byteLength * parts.length;
contentLength = utils.toFiniteNumber(contentLength);
const computedHeaders = {
'Content-Type': `multipart/form-data; boundary=${boundary}`,
};
if (Number.isFinite(contentLength)) {
computedHeaders['Content-Length'] = contentLength;
}
headersHandler && headersHandler(computedHeaders);
return Readable.from(
(async function* () {
for (const part of parts) {
yield boundaryBytes;
yield* part.encode();
}
yield footerBytes;
})()
);
};
export default formDataToStream;
+68
View File
@@ -0,0 +1,68 @@
'use strict';
import AxiosError from '../core/AxiosError.js';
import parseProtocol from './parseProtocol.js';
import platform from '../platform/index.js';
// RFC 2397: data:[<mediatype>][;base64],<data>
// mediatype = type/subtype followed by optional ;name=value parameters
const DATA_URL_PATTERN = /^([^,;]+\/[^,;]+)?((?:;[^,;=]+=[^,;]+)*)(;base64)?,([\s\S]*)$/;
/**
* Parse data uri to a Buffer or Blob
*
* @param {String} uri
* @param {?Boolean} asBlob
* @param {?Object} options
* @param {?Function} options.Blob
*
* @returns {Buffer|Blob}
*/
export default function fromDataURI(uri, asBlob, options) {
const _Blob = (options && options.Blob) || platform.classes.Blob;
const protocol = parseProtocol(uri);
if (asBlob === undefined && _Blob) {
asBlob = true;
}
if (protocol === 'data') {
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
const match = DATA_URL_PATTERN.exec(uri);
if (!match) {
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
}
const type = match[1];
const params = match[2];
const encoding = match[3] ? 'base64' : 'utf8';
const body = match[4];
// RFC 2397 section 3: default mediatype is text/plain;charset=US-ASCII
// Bare `data:,` leaves mime undefined; Blob normalises that to "" per spec.
let mime = '';
if (type) {
mime = params ? type + params : type;
} else if (params) {
mime = 'text/plain' + params;
}
const buffer = encoding === 'base64'
? Buffer.from(body, 'base64')
: Buffer.from(decodeURIComponent(body), encoding);
if (asBlob) {
if (!_Blob) {
throw new AxiosError('Blob is not supported', AxiosError.ERR_NOT_SUPPORT);
}
return new _Blob([buffer], { type: mime });
}
return buffer;
}
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
}
+19
View File
@@ -0,0 +1,19 @@
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
export default function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
if (typeof url !== 'string') {
return false;
}
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
}
+14
View File
@@ -0,0 +1,14 @@
'use strict';
import utils from '../utils.js';
/**
* Determines whether the payload is an error thrown by Axios
*
* @param {*} payload The value to test
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
export default function isAxiosError(payload) {
return utils.isObject(payload) && payload.isAxiosError === true;
}
+16
View File
@@ -0,0 +1,16 @@
import platform from '../platform/index.js';
export default platform.hasStandardBrowserEnv
? ((origin, isMSIE) => (url) => {
url = new URL(url, platform.origin);
return (
origin.protocol === url.protocol &&
origin.host === url.host &&
(isMSIE || origin.port === url.port)
);
})(
new URL(platform.origin),
platform.navigator && /(msie|trident)/i.test(platform.navigator.userAgent)
)
: () => true;
+2
View File
@@ -0,0 +1,2 @@
// eslint-disable-next-line strict
export default null;
+69
View File
@@ -0,0 +1,69 @@
'use strict';
import utils from '../utils.js';
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
const ignoreDuplicateOf = utils.toObjectSet([
'age',
'authorization',
'content-length',
'content-type',
'etag',
'expires',
'from',
'host',
'if-modified-since',
'if-unmodified-since',
'last-modified',
'location',
'max-forwards',
'proxy-authorization',
'referer',
'retry-after',
'user-agent',
]);
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
export default (rawHeaders) => {
const parsed = {};
let key;
let val;
let i;
rawHeaders &&
rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});
return parsed;
};
+6
View File
@@ -0,0 +1,6 @@
'use strict';
export default function parseProtocol(url) {
const match = /^([-+\w]{1,25}):(?:\/\/)?/.exec(url);
return (match && match[1]) || '';
}
+54
View File
@@ -0,0 +1,54 @@
import speedometer from './speedometer.js';
import throttle from './throttle.js';
import utils from '../utils.js';
export const progressEventReducer = (listener, isDownloadStream, freq = 3) => {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return throttle((e) => {
if (!e || typeof e.loaded !== 'number') {
return;
}
const rawLoaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const loaded = total != null ? Math.min(rawLoaded, total) : rawLoaded;
const progressBytes = Math.max(0, loaded - bytesNotified);
const rate = _speedometer(progressBytes);
bytesNotified = Math.max(bytesNotified, loaded);
const data = {
loaded,
total,
progress: total ? loaded / total : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total ? (total - loaded) / rate : undefined,
event: e,
lengthComputable: total != null,
[isDownloadStream ? 'download' : 'upload']: true,
};
listener(data);
}, freq);
};
export const progressEventDecorator = (total, throttled) => {
const lengthComputable = total != null;
return [
(loaded) =>
throttled[0]({
lengthComputable,
total,
loaded,
}),
throttled[1],
];
};
export const asyncDecorator =
(fn) =>
(...args) =>
utils.asap(() => fn(...args));
+15
View File
@@ -0,0 +1,15 @@
const { asyncIterator } = Symbol;
const readBlob = async function* (blob) {
if (blob.stream) {
yield* blob.stream();
} else if (blob.arrayBuffer) {
yield await blob.arrayBuffer();
} else if (blob[asyncIterator]) {
yield* blob[asyncIterator]();
} else {
yield blob;
}
};
export default readBlob;
+119
View File
@@ -0,0 +1,119 @@
import platform from '../platform/index.js';
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import isURLSameOrigin from './isURLSameOrigin.js';
import cookies from './cookies.js';
import buildFullPath from '../core/buildFullPath.js';
import mergeConfig from '../core/mergeConfig.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import buildURL from './buildURL.js';
const FORM_DATA_CONTENT_HEADERS = ['content-type', 'content-length'];
function setFormDataHeaders(headers, formHeaders, policy) {
if (policy !== 'content-only') {
headers.set(formHeaders);
return;
}
Object.entries(formHeaders || {}).forEach(([key, val]) => {
if (FORM_DATA_CONTENT_HEADERS.includes(key.toLowerCase())) {
headers.set(key, val);
}
});
}
/**
* Encode a UTF-8 string to a Latin-1 byte string for use with btoa().
* This is a modern replacement for the deprecated unescape(encodeURIComponent(str)) pattern.
*
* @param {string} str The string to encode
*
* @returns {string} UTF-8 bytes as a Latin-1 string
*/
const encodeUTF8 = (str) =>
encodeURIComponent(str).replace(/%([0-9A-F]{2})/gi, (_, hex) =>
String.fromCharCode(parseInt(hex, 16))
);
function resolveConfig(config) {
const newConfig = mergeConfig({}, config);
// Read only own properties to prevent prototype pollution gadgets
// (e.g. Object.prototype.baseURL = 'https://evil.com').
const own = (key) => (utils.hasOwnProp(newConfig, key) ? newConfig[key] : undefined);
const data = own('data');
let withXSRFToken = own('withXSRFToken');
const xsrfHeaderName = own('xsrfHeaderName');
const xsrfCookieName = own('xsrfCookieName');
let headers = own('headers');
const auth = own('auth');
const baseURL = own('baseURL');
const allowAbsoluteUrls = own('allowAbsoluteUrls');
const url = own('url');
newConfig.headers = headers = AxiosHeaders.from(headers);
newConfig.url = buildURL(
buildFullPath(baseURL, url, allowAbsoluteUrls, newConfig),
own('params'),
own('paramsSerializer')
);
// HTTP basic authentication
if (auth) {
const username = utils.getSafeProp(auth, 'username') || '';
const password = utils.getSafeProp(auth, 'password') || '';
try {
headers.set(
'Authorization',
'Basic ' + btoa(username + ':' + (password ? encodeUTF8(password) : ''))
);
} catch (e) {
throw AxiosError.from(e, AxiosError.ERR_BAD_OPTION_VALUE, config);
}
}
if (utils.isFormData(data)) {
if (
platform.hasStandardBrowserEnv ||
platform.hasStandardBrowserWebWorkerEnv ||
utils.isReactNative(data)
) {
headers.setContentType(undefined); // browser/web worker/RN handles it
} else if (utils.isFunction(data.getHeaders)) {
// Node.js FormData (like form-data package)
setFormDataHeaders(headers, data.getHeaders(), own('formDataHeaderPolicy'));
}
}
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (platform.hasStandardBrowserEnv) {
if (utils.isFunction(withXSRFToken)) {
withXSRFToken = withXSRFToken(newConfig);
}
// Strict boolean check — prevents proto-pollution gadgets (e.g. Object.prototype.withXSRFToken = 1)
// and misconfigurations (e.g. "false") from short-circuiting the same-origin check and leaking
// the XSRF token cross-origin.
const shouldSendXSRF =
withXSRFToken === true || (withXSRFToken == null && isURLSameOrigin(newConfig.url));
if (shouldSendXSRF) {
const xsrfValue = xsrfHeaderName && xsrfCookieName && cookies.read(xsrfCookieName);
if (xsrfValue) {
headers.set(xsrfHeaderName, xsrfValue);
}
}
}
return newConfig;
}
export default resolveConfig;
+60
View File
@@ -0,0 +1,60 @@
'use strict';
import utils from '../utils.js';
function trimSPorHTAB(str) {
let start = 0;
let end = str.length;
while (start < end) {
const code = str.charCodeAt(start);
if (code !== 0x09 && code !== 0x20) {
break;
}
start += 1;
}
while (end > start) {
const code = str.charCodeAt(end - 1);
if (code !== 0x09 && code !== 0x20) {
break;
}
end -= 1;
}
return start === 0 && end === str.length ? str : str.slice(start, end);
}
// The control-code ranges are intentional: header sanitization strips C0/DEL bytes.
// eslint-disable-next-line no-control-regex
const INVALID_UNICODE_HEADER_VALUE_CHARS = new RegExp('[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+', 'g');
// eslint-disable-next-line no-control-regex
const INVALID_BYTE_STRING_HEADER_VALUE_CHARS = new RegExp('[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+', 'g');
function sanitizeValue(value, invalidChars) {
if (utils.isArray(value)) {
return value.map((item) => sanitizeValue(item, invalidChars));
}
return trimSPorHTAB(String(value).replace(invalidChars, ''));
}
export const sanitizeHeaderValue = (value) =>
sanitizeValue(value, INVALID_UNICODE_HEADER_VALUE_CHARS);
export const sanitizeByteStringHeaderValue = (value) =>
sanitizeValue(value, INVALID_BYTE_STRING_HEADER_VALUE_CHARS);
export function toByteStringHeaderObject(headers) {
const byteStringHeaders = Object.create(null);
utils.forEach(headers.toJSON(), (value, header) => {
byteStringHeaders[header] = sanitizeByteStringHeaderValue(value);
});
return byteStringHeaders;
}
+210
View File
@@ -0,0 +1,210 @@
const LOOPBACK_HOSTNAMES = new Set(['localhost', '0.0.0.0']);
const isIPv4Loopback = (host) => {
const parts = host.split('.');
if (parts.length !== 4) return false;
if (parts[0] !== '127') return false;
return parts.every((p) => /^\d+$/.test(p) && Number(p) >= 0 && Number(p) <= 255);
};
const isIPv6ZeroGroup = (group) => /^0{1,4}$/.test(group);
// The unspecified address (IPv4 0.0.0.0 / IPv6 ::) resolves to the local host
// for outbound connections, so treat it as loopback-equivalent for NO_PROXY
// matching. 0.0.0.0 is covered by LOOPBACK_HOSTNAMES; this handles compressed
// and full IPv6 all-zero forms so both families bypass symmetrically.
const isIPv6Unspecified = (host) => {
if (host === '::') return true;
const compressionIndex = host.indexOf('::');
if (compressionIndex !== -1) {
if (compressionIndex !== host.lastIndexOf('::')) return false;
const left = host.slice(0, compressionIndex);
const right = host.slice(compressionIndex + 2);
const leftGroups = left ? left.split(':') : [];
const rightGroups = right ? right.split(':') : [];
const explicitGroups = leftGroups.length + rightGroups.length;
return (
explicitGroups < 8 &&
leftGroups.every(isIPv6ZeroGroup) &&
rightGroups.every(isIPv6ZeroGroup)
);
}
const groups = host.split(':');
return groups.length === 8 && groups.every(isIPv6ZeroGroup);
};
const isIPv6Loopback = (host) => {
// Collapse all-zero groups: any form of ::1 / 0:0:...:0:1
// First, strip any leading "::" by normalising with Set lookup of common forms,
// then fall back to structural check.
if (host === '::1') return true;
// Check IPv4-mapped IPv6 loopback: ::ffff:<v4-loopback> or ::ffff:<hex-v4-loopback>
// Node's URL parser normalises ::ffff:127.0.0.1 → ::ffff:7f00:1
const v4MappedDotted = host.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/i);
if (v4MappedDotted) return isIPv4Loopback(v4MappedDotted[1]);
const v4MappedHex = host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);
if (v4MappedHex) {
const high = parseInt(v4MappedHex[1], 16);
// High 16 bits must start with 127 (0x7f) — i.e. 0x7f00..0x7fff
return high >= 0x7f00 && high <= 0x7fff;
}
// Full-form ::1 variants: any number of zero groups followed by trailing 1
// e.g. 0:0:0:0:0:0:0:1, 0000:...:0001
const groups = host.split(':');
if (groups.length === 8) {
for (let i = 0; i < 7; i++) {
if (!/^0+$/.test(groups[i])) return false;
}
return /^0*1$/.test(groups[7]);
}
return false;
};
const isLoopback = (host) => {
if (!host) return false;
if (LOOPBACK_HOSTNAMES.has(host)) return true;
if (isIPv4Loopback(host)) return true;
if (isIPv6Unspecified(host)) return true;
return isIPv6Loopback(host);
};
const DEFAULT_PORTS = {
http: 80,
https: 443,
ws: 80,
wss: 443,
ftp: 21,
};
const parseNoProxyEntry = (entry) => {
let entryHost = entry;
let entryPort = 0;
if (entryHost.charAt(0) === '[') {
const bracketIndex = entryHost.indexOf(']');
if (bracketIndex !== -1) {
const host = entryHost.slice(1, bracketIndex);
const rest = entryHost.slice(bracketIndex + 1);
if (rest.charAt(0) === ':' && /^\d+$/.test(rest.slice(1))) {
entryPort = Number.parseInt(rest.slice(1), 10);
}
return [host, entryPort];
}
}
const firstColon = entryHost.indexOf(':');
const lastColon = entryHost.lastIndexOf(':');
if (
firstColon !== -1 &&
firstColon === lastColon &&
/^\d+$/.test(entryHost.slice(lastColon + 1))
) {
entryPort = Number.parseInt(entryHost.slice(lastColon + 1), 10);
entryHost = entryHost.slice(0, lastColon);
}
return [entryHost, entryPort];
};
// Convert IPv4-mapped IPv6 (::ffff:0:0/96 prefix) to IPv4 dotted form so both
// sides of a NO_PROXY comparison see the same canonical address. Without this,
// `NO_PROXY=192.168.1.5` would not match a request to `http://[::ffff:192.168.1.5]/`
// (Node's URL parser normalises that to `[::ffff:c0a8:105]`), and vice-versa,
// allowing the proxy-bypass policy to be circumvented by using the alternate
// representation. Returns the input unchanged when not IPv4-mapped.
const IPV4_MAPPED_DOTTED_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:(\d+\.\d+\.\d+\.\d+)$/i;
const IPV4_MAPPED_HEX_RE = /^(?:::|(?:0{1,4}:){1,4}:|(?:0{1,4}:){5})ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i;
const unmapIPv4MappedIPv6 = (host) => {
if (typeof host !== 'string' || host.indexOf(':') === -1) return host;
const dotted = host.match(IPV4_MAPPED_DOTTED_RE);
if (dotted) return dotted[1];
const hex = host.match(IPV4_MAPPED_HEX_RE);
if (hex) {
const high = parseInt(hex[1], 16);
const low = parseInt(hex[2], 16);
return `${high >> 8}.${high & 0xff}.${low >> 8}.${low & 0xff}`;
}
return host;
};
const normalizeNoProxyHost = (hostname) => {
if (!hostname) {
return hostname;
}
if (hostname.charAt(0) === '[' && hostname.charAt(hostname.length - 1) === ']') {
hostname = hostname.slice(1, -1);
}
return unmapIPv4MappedIPv6(hostname.replace(/\.+$/, ''));
};
export default function shouldBypassProxy(location) {
let parsed;
try {
parsed = new URL(location);
} catch (_err) {
return false;
}
const noProxy = (process.env.no_proxy || process.env.NO_PROXY || '').toLowerCase();
if (!noProxy) {
return false;
}
if (noProxy === '*') {
return true;
}
const port =
Number.parseInt(parsed.port, 10) || DEFAULT_PORTS[parsed.protocol.split(':', 1)[0]] || 0;
const hostname = normalizeNoProxyHost(parsed.hostname.toLowerCase());
return noProxy.split(/[\s,]+/).some((entry) => {
if (!entry) {
return false;
}
let [entryHost, entryPort] = parseNoProxyEntry(entry);
entryHost = normalizeNoProxyHost(entryHost);
if (!entryHost) {
return false;
}
if (entryPort && entryPort !== port) {
return false;
}
if (entryHost.charAt(0) === '*') {
entryHost = entryHost.slice(1);
}
if (entryHost.charAt(0) === '.') {
return hostname.endsWith(entryHost);
}
return hostname === entryHost || (isLoopback(hostname) && isLoopback(entryHost));
});
}
+55
View File
@@ -0,0 +1,55 @@
'use strict';
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round((bytesCount * 1000) / passed) : undefined;
};
}
export default speedometer;
+28
View File
@@ -0,0 +1,28 @@
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* const args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
*
* @returns {Function}
*/
export default function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
}
+44
View File
@@ -0,0 +1,44 @@
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
let threshold = 1000 / freq;
let lastArgs;
let timer;
const invoke = (args, now = Date.now()) => {
timestamp = now;
lastArgs = null;
if (timer) {
clearTimeout(timer);
timer = null;
}
fn(...args);
};
const throttled = (...args) => {
const now = Date.now();
const passed = now - timestamp;
if (passed >= threshold) {
invoke(args, now);
} else {
lastArgs = args;
if (!timer) {
timer = setTimeout(() => {
timer = null;
invoke(lastArgs);
}, threshold - passed);
}
}
};
const flush = () => lastArgs && invoke(lastArgs);
return [throttled, flush];
}
export default throttle;
+285
View File
@@ -0,0 +1,285 @@
'use strict';
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
// temporary hotfix to avoid circular references until AxiosURLSearchParams is refactored
import PlatformFormData from '../platform/node/classes/FormData.js';
// Default nesting limit shared with the inverse transform (formDataToJSON) so
// the FormData <-> JSON round-trip stays symmetric.
export const DEFAULT_FORM_DATA_MAX_DEPTH = 100;
/**
* Determines if the given thing is a array or js object.
*
* @param {string} thing - The object or array to be visited.
*
* @returns {boolean}
*/
function isVisitable(thing) {
return utils.isPlainObject(thing) || utils.isArray(thing);
}
/**
* It removes the brackets from the end of a string
*
* @param {string} key - The key of the parameter.
*
* @returns {string} the key without the brackets.
*/
function removeBrackets(key) {
return utils.endsWith(key, '[]') ? key.slice(0, -2) : key;
}
/**
* It takes a path, a key, and a boolean, and returns a string
*
* @param {string} path - The path to the current key.
* @param {string} key - The key of the current object being iterated over.
* @param {string} dots - If true, the key will be rendered with dots instead of brackets.
*
* @returns {string} The path to the current key.
*/
function renderKey(path, key, dots) {
if (!path) return key;
return path
.concat(key)
.map(function each(token, i) {
// eslint-disable-next-line no-param-reassign
token = removeBrackets(token);
return !dots && i ? '[' + token + ']' : token;
})
.join(dots ? '.' : '');
}
/**
* If the array is an array and none of its elements are visitable, then it's a flat array.
*
* @param {Array<any>} arr - The array to check
*
* @returns {boolean}
*/
function isFlatArray(arr) {
return utils.isArray(arr) && !arr.some(isVisitable);
}
const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
/**
* Convert a data object to FormData
*
* @param {Object} obj
* @param {?Object} [formData]
* @param {?Object} [options]
* @param {Function} [options.visitor]
* @param {Boolean} [options.metaTokens = true]
* @param {Boolean} [options.dots = false]
* @param {?Boolean} [options.indexes = false]
*
* @returns {Object}
**/
/**
* It converts an object into a FormData object
*
* @param {Object<any, any>} obj - The object to convert to form data.
* @param {string} formData - The FormData object to append to.
* @param {Object<string, any>} options
*
* @returns
*/
function toFormData(obj, formData, options) {
if (!utils.isObject(obj)) {
throw new TypeError('target must be an object');
}
// eslint-disable-next-line no-param-reassign
formData = formData || new (PlatformFormData || FormData)();
// eslint-disable-next-line no-param-reassign
options = utils.toFlatObject(
options,
{
metaTokens: true,
dots: false,
indexes: false,
},
false,
function defined(option, source) {
// eslint-disable-next-line no-eq-null,eqeqeq
return !utils.isUndefined(source[option]);
}
);
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || (typeof Blob !== 'undefined' && Blob);
const maxDepth = options.maxDepth === undefined ? DEFAULT_FORM_DATA_MAX_DEPTH : options.maxDepth;
const useBlob = _Blob && utils.isSpecCompliantForm(formData);
const stack = [];
if (!utils.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
}
function convertValue(value) {
if (value === null) return '';
if (utils.isDate(value)) {
return value.toISOString();
}
if (utils.isBoolean(value)) {
return value.toString();
}
if (!useBlob && utils.isBlob(value)) {
throw new AxiosError('Blob is not supported. Use a Buffer instead.');
}
if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {
if (useBlob && typeof _Blob === 'function') {
return new _Blob([value]);
}
if (typeof Buffer !== 'undefined') {
return Buffer.from(value);
}
throw new AxiosError('Blob is not supported. Use a Buffer instead.', AxiosError.ERR_NOT_SUPPORT);
}
return value;
}
function throwIfMaxDepthExceeded(depth) {
if (depth > maxDepth) {
throw new AxiosError(
'Object is too deeply nested (' + depth + ' levels). Max depth: ' + maxDepth,
AxiosError.ERR_FORM_DATA_DEPTH_EXCEEDED
);
}
}
function stringifyWithDepthLimit(value, depth) {
if (maxDepth === Infinity) {
return JSON.stringify(value);
}
const ancestors = [];
return JSON.stringify(value, function limitDepth(_key, currentValue) {
if (!utils.isObject(currentValue)) {
return currentValue;
}
while (ancestors.length && ancestors[ancestors.length - 1] !== this) {
ancestors.pop();
}
ancestors.push(currentValue);
throwIfMaxDepthExceeded(depth + ancestors.length - 1);
return currentValue;
});
}
/**
* Default visitor.
*
* @param {*} value
* @param {String|Number} key
* @param {Array<String|Number>} path
* @this {FormData}
*
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
let arr = value;
if (utils.isReactNative(formData) && utils.isReactNativeBlob(value)) {
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
if (value && !path && typeof value === 'object') {
if (utils.endsWith(key, '{}')) {
// eslint-disable-next-line no-param-reassign
key = metaTokens ? key : key.slice(0, -2);
// eslint-disable-next-line no-param-reassign
value = stringifyWithDepthLimit(value, 1);
} else if (
(utils.isArray(value) && isFlatArray(value)) ||
((utils.isFileList(value) || utils.endsWith(key, '[]')) && (arr = utils.toArray(value)))
) {
// eslint-disable-next-line no-param-reassign
key = removeBrackets(key);
arr.forEach(function each(el, index) {
!(utils.isUndefined(el) || el === null) &&
formData.append(
// eslint-disable-next-line no-nested-ternary
indexes === true
? renderKey([key], index, dots)
: indexes === null
? key
: key + '[]',
convertValue(el)
);
});
return false;
}
}
if (isVisitable(value)) {
return true;
}
formData.append(renderKey(path, key, dots), convertValue(value));
return false;
}
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable,
});
function build(value, path, depth = 0) {
if (utils.isUndefined(value)) return;
throwIfMaxDepthExceeded(depth);
if (stack.indexOf(value) !== -1) {
throw new Error('Circular reference detected in ' + path.join('.'));
}
stack.push(value);
utils.forEach(value, function each(el, key) {
const result =
!(utils.isUndefined(el) || el === null) &&
visitor.call(formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers);
if (result === true) {
build(el, path ? path.concat(key) : [key], depth + 1);
}
});
stack.pop();
}
if (!utils.isObject(obj)) {
throw new TypeError('data must be an object');
}
build(obj);
return formData;
}
export default toFormData;
+19
View File
@@ -0,0 +1,19 @@
'use strict';
import utils from '../utils.js';
import toFormData from './toFormData.js';
import platform from '../platform/index.js';
export default function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), {
visitor: function (value, key, path, helpers) {
if (platform.isNode && utils.isBuffer(value)) {
this.append(key, value.toString('base64'));
return false;
}
return helpers.defaultVisitor.apply(this, arguments);
},
...options,
});
}
+89
View File
@@ -0,0 +1,89 @@
export const streamChunk = function* (chunk, chunkSize) {
let len = chunk.byteLength;
if (!chunkSize || len < chunkSize) {
yield chunk;
return;
}
let pos = 0;
let end;
while (pos < len) {
end = pos + chunkSize;
yield chunk.slice(pos, end);
pos = end;
}
};
export const readBytes = async function* (iterable, chunkSize) {
for await (const chunk of readStream(iterable)) {
yield* streamChunk(chunk, chunkSize);
}
};
const readStream = async function* (stream) {
if (stream[Symbol.asyncIterator]) {
yield* stream;
return;
}
const reader = stream.getReader();
try {
for (;;) {
const { done, value } = await reader.read();
if (done) {
break;
}
yield value;
}
} finally {
await reader.cancel();
}
};
export const trackStream = (stream, chunkSize, onProgress, onFinish) => {
const iterator = readBytes(stream, chunkSize);
let bytes = 0;
let done;
let _onFinish = (e) => {
if (!done) {
done = true;
onFinish && onFinish(e);
}
};
return new ReadableStream(
{
async pull(controller) {
try {
const { done, value } = await iterator.next();
if (done) {
_onFinish();
controller.close();
return;
}
let len = value.byteLength;
if (onProgress) {
let loadedBytes = (bytes += len);
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
} catch (err) {
_onFinish(err);
throw err;
}
},
cancel(reason) {
_onFinish(reason);
return iterator.return();
},
},
{
highWaterMark: 2,
}
);
};
+112
View File
@@ -0,0 +1,112 @@
'use strict';
import { VERSION } from '../env/data.js';
import AxiosError from '../core/AxiosError.js';
const validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
const deprecatedWarnings = {};
/**
* Transitional option validator
*
* @param {function|boolean?} validator - set to false if the transitional option has been removed
* @param {string?} version - deprecated version / removed since version
* @param {string?} message - some message with additional info
*
* @returns {function}
*/
validators.transitional = function transitional(validator, version, message) {
function formatMessage(opt, desc) {
return (
'[Axios v' +
VERSION +
"] Transitional option '" +
opt +
"'" +
desc +
(message ? '. ' + message : '')
);
}
// eslint-disable-next-line func-names
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
AxiosError.ERR_DEPRECATED
);
}
if (version && !deprecatedWarnings[opt]) {
deprecatedWarnings[opt] = true;
// eslint-disable-next-line no-console
console.warn(
formatMessage(
opt,
' has been deprecated since v' + version + ' and will be removed in the near future'
)
);
}
return validator ? validator(value, opt, opts) : true;
};
};
validators.spelling = function spelling(correctSpelling) {
return (value, opt) => {
// eslint-disable-next-line no-console
console.warn(`${opt} is likely a misspelling of ${correctSpelling}`);
return true;
};
};
/**
* Assert object's properties type
*
* @param {object} options
* @param {object} schema
* @param {boolean?} allowUnknown
*
* @returns {object}
*/
function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object' || options === null) {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
const opt = keys[i];
// Use hasOwnProperty so a polluted Object.prototype.<opt> cannot supply
// a non-function validator and cause a TypeError.
const validator = Object.prototype.hasOwnProperty.call(schema, opt) ? schema[opt] : undefined;
if (validator) {
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError(
'option ' + opt + ' must be ' + result,
AxiosError.ERR_BAD_OPTION_VALUE
);
}
continue;
}
if (allowUnknown !== true) {
throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);
}
}
}
export default {
assertOptions,
validators,
};
+3
View File
@@ -0,0 +1,3 @@
'use strict';
export default typeof Blob !== 'undefined' ? Blob : null;
+3
View File
@@ -0,0 +1,3 @@
'use strict';
export default typeof FormData !== 'undefined' ? FormData : null;
+4
View File
@@ -0,0 +1,4 @@
'use strict';
import AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';
export default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
+13
View File
@@ -0,0 +1,13 @@
import URLSearchParams from './classes/URLSearchParams.js';
import FormData from './classes/FormData.js';
import Blob from './classes/Blob.js';
export default {
isBrowser: true,
classes: {
URLSearchParams,
FormData,
Blob,
},
protocols: ['http', 'https', 'file', 'blob', 'url', 'data'],
};
+52
View File
@@ -0,0 +1,52 @@
const hasBrowserEnv = typeof window !== 'undefined' && typeof document !== 'undefined';
const _navigator = (typeof navigator === 'object' && navigator) || undefined;
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*
* @returns {boolean}
*/
const hasStandardBrowserEnv =
hasBrowserEnv &&
(!_navigator || ['ReactNative', 'NativeScript', 'NS'].indexOf(_navigator.product) < 0);
/**
* Determine if we're running in a standard browser webWorker environment
*
* Although the `isStandardBrowserEnv` method indicates that
* `allows axios to run in a web worker`, the WebWorker will still be
* filtered out due to its judgment standard
* `typeof window !== 'undefined' && typeof document !== 'undefined'`.
* This leads to a problem when axios post `FormData` in webWorker
*/
const hasStandardBrowserWebWorkerEnv = (() => {
return (
typeof WorkerGlobalScope !== 'undefined' &&
// eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope &&
typeof self.importScripts === 'function'
);
})();
const origin = (hasBrowserEnv && window.location.href) || 'http://localhost';
export {
hasBrowserEnv,
hasStandardBrowserWebWorkerEnv,
hasStandardBrowserEnv,
_navigator as navigator,
origin,
};
+7
View File
@@ -0,0 +1,7 @@
import platform from './node/index.js';
import * as utils from './common/utils.js';
export default {
...utils,
...platform,
};
+3
View File
@@ -0,0 +1,3 @@
import FormData from 'form-data';
export default FormData;
+4
View File
@@ -0,0 +1,4 @@
'use strict';
import url from 'url';
export default url.URLSearchParams;
+37
View File
@@ -0,0 +1,37 @@
import crypto from 'crypto';
import URLSearchParams from './classes/URLSearchParams.js';
import FormData from './classes/FormData.js';
const ALPHA = 'abcdefghijklmnopqrstuvwxyz';
const DIGIT = '0123456789';
const ALPHABET = {
DIGIT,
ALPHA,
ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT,
};
const generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => {
let str = '';
const { length } = alphabet;
const randomValues = new Uint32Array(size);
crypto.randomFillSync(randomValues);
for (let i = 0; i < size; i++) {
str += alphabet[randomValues[i] % length];
}
return str;
};
export default {
isNode: true,
classes: {
URLSearchParams,
FormData,
Blob: (typeof Blob !== 'undefined' && Blob) || null,
},
ALPHABET,
generateString,
protocols: ['http', 'https', 'file', 'data'],
};
+1017
View File
@@ -0,0 +1,1017 @@
'use strict';
import bind from './helpers/bind.js';
// utils is a library of generic helper functions non-specific to axios
const { toString } = Object.prototype;
const { getPrototypeOf } = Object;
const { iterator, toStringTag } = Symbol;
/* Creating a function that will check if an object has a property. */
const hasOwnProperty = (
({ hasOwnProperty }) =>
(obj, prop) =>
hasOwnProperty.call(obj, prop)
)(Object.prototype);
/**
* Walk the prototype chain (excluding the shared Object.prototype) looking for
* an own `prop`. This distinguishes genuine own/inherited members — including
* class accessors and template prototypes — from members injected via
* Object.prototype pollution (e.g. `Object.prototype.username = '...'`), which
* live on Object.prototype itself and are therefore never matched.
*
* @param {*} thing The value whose chain to inspect
* @param {string|symbol} prop The property key to look for
*
* @returns {boolean} True when `prop` is owned below Object.prototype
*/
const hasOwnInPrototypeChain = (thing, prop) => {
let obj = thing;
const seen = [];
while (obj != null && obj !== Object.prototype) {
if (seen.indexOf(obj) !== -1) {
return false;
}
seen.push(obj);
if (hasOwnProperty(obj, prop)) {
return true;
}
obj = getPrototypeOf(obj);
}
return false;
};
/**
* Read `obj[prop]` only when it is safe from Object.prototype pollution. Own
* properties and members inherited from a non-Object.prototype source (a class
* instance or template object) are honored; a value reachable only through a
* polluted Object.prototype is ignored and `undefined` is returned.
*
* @param {*} obj The source object
* @param {string|symbol} prop The property key to read
*
* @returns {*} The resolved value, or undefined when unsafe/absent
*/
const getSafeProp = (obj, prop) =>
obj != null && hasOwnInPrototypeChain(obj, prop) ? obj[prop] : undefined;
const kindOf = ((cache) => (thing) => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
})(Object.create(null));
const kindOfTest = (type) => {
type = type.toLowerCase();
return (thing) => kindOf(thing) === type;
};
const typeOfTest = (type) => (thing) => typeof thing === type;
/**
* Determine if a value is a non-null object
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is an Array, otherwise false
*/
const { isArray } = Array;
/**
* Determine if a value is undefined
*
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return (
val !== null &&
!isUndefined(val) &&
val.constructor !== null &&
!isUndefined(val.constructor) &&
isFunction(val.constructor.isBuffer) &&
val.constructor.isBuffer(val)
);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
let result;
if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
result = ArrayBuffer.isView(val);
} else {
result = val && val.buffer && isArrayBuffer(val.buffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
const isObject = (thing) => thing !== null && typeof thing === 'object';
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = (thing) => thing === true || thing === false;
/**
* Determine if a value is a plain Object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
const isPlainObject = (val) => {
if (!isObject(val)) {
return false;
}
const prototype = getPrototypeOf(val);
return (
(prototype === null ||
prototype === Object.prototype ||
getPrototypeOf(prototype) === null) &&
// Treat any genuine (non-Object.prototype-polluted) Symbol.toStringTag or
// Symbol.iterator as evidence the value is a tagged/iterable type rather
// than a plain object, while ignoring keys injected onto Object.prototype.
!hasOwnInPrototypeChain(val, toStringTag) &&
!hasOwnInPrototypeChain(val, iterator)
);
};
/**
* Determine if a value is an empty object (safely handles Buffers)
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is an empty object, otherwise false
*/
const isEmptyObject = (val) => {
// Early return for non-objects or Buffers to prevent RangeError
if (!isObject(val) || isBuffer(val)) {
return false;
}
try {
return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;
} catch (e) {
// Fallback for any other objects that might cause RangeError with Object.keys()
return false;
}
};
/**
* Determine if a value is a Date
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
const isFile = kindOfTest('File');
/**
* Determine if a value is a React Native Blob
* React Native "blob": an object with a `uri` attribute. Optionally, it can
* also have a `name` and `type` attribute to specify filename and content type
*
* @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71
*
* @param {*} value The value to test
*
* @returns {boolean} True if value is a React Native Blob, otherwise false
*/
const isReactNativeBlob = (value) => {
return !!(value && typeof value.uri !== 'undefined');
};
/**
* Determine if environment is React Native
* ReactNative `FormData` has a non-standard `getParts()` method
*
* @param {*} formData The formData to test
*
* @returns {boolean} True if environment is React Native, otherwise false
*/
const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';
/**
* Determine if a value is a Blob
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a FileList, otherwise false
*/
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
const isStream = (val) => isObject(val) && isFunction(val.pipe);
/**
* Determine if a value is a FormData
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
function getGlobal() {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
return {};
}
const G = getGlobal();
const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;
const isFormData = (thing) => {
if (!thing) return false;
if (FormDataCtor && thing instanceof FormDataCtor) return true;
// Reject plain objects inheriting directly from Object.prototype so prototype-pollution gadgets can't spoof FormData.
const proto = getPrototypeOf(thing);
if (!proto || proto === Object.prototype) return false;
if (!isFunction(thing.append)) return false;
const kind = kindOf(thing);
return (
kind === 'formdata' ||
// detect form-data instance
(kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')
);
};
/**
* Determine if a value is a URLSearchParams object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
const isURLSearchParams = kindOfTest('URLSearchParams');
const [isReadableStream, isRequest, isResponse, isHeaders] = [
'ReadableStream',
'Request',
'Response',
'Headers',
].map(kindOfTest);
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
*
* @returns {String} The String freed of excess whitespace
*/
const trim = (str) => {
return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array<unknown>} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys = false]
* @returns {any}
*/
function forEach(obj, fn, { allOwnKeys = false } = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Buffer check
if (isBuffer(obj)) {
return;
}
// Iterate over object keys
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
/**
* Finds a key in an object, case-insensitive, returning the actual key name.
* Returns null if the object is a Buffer or if no match is found.
*
* @param {Object} obj - The object to search.
* @param {string} key - The key to find (case-insensitive).
* @returns {?string} The actual key name if found, otherwise null.
*/
function findKey(obj, key) {
if (isBuffer(obj)) {
return null;
}
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
const _global = (() => {
/*eslint no-undef:0*/
if (typeof globalThis !== 'undefined') return globalThis;
return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
})();
const isContextDefined = (context) => !isUndefined(context) && context !== _global;
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* const result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
*
* @returns {Object} Result of all merge properties
*/
function merge(...objs) {
const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};
const result = {};
const assignValue = (val, key) => {
// Skip dangerous property names to prevent prototype pollution
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
return;
}
// findKey lowercases the key, so caseless lookup only applies to strings —
// symbol keys are identity-matched.
const targetKey = (caseless && typeof key === 'string' && findKey(result, key)) || key;
// Read via own-prop only — a bare `result[targetKey]` walks the prototype
// chain, so a polluted Object.prototype value could surface here and get
// copied into the merged result.
const existing = hasOwnProperty(result, targetKey) ? result[targetKey] : undefined;
if (isPlainObject(existing) && isPlainObject(val)) {
result[targetKey] = merge(existing, val);
} else if (isPlainObject(val)) {
result[targetKey] = merge({}, val);
} else if (isArray(val)) {
result[targetKey] = val.slice();
} else if (!skipUndefined || !isUndefined(val)) {
result[targetKey] = val;
}
};
for (let i = 0, l = objs.length; i < l; i++) {
const source = objs[i];
if (!source || isBuffer(source)) {
continue;
}
forEach(source, assignValue);
if (typeof source !== 'object' || isArray(source)) {
continue;
}
const symbols = Object.getOwnPropertySymbols(source);
for (let j = 0; j < symbols.length; j++) {
const symbol = symbols[j];
if (propertyIsEnumerable.call(source, symbol)) {
assignValue(source[symbol], symbol);
}
}
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Object} [options]
* @param {Boolean} [options.allOwnKeys]
* @returns {Object} The resulting value of object a
*/
const extend = (a, b, thisArg, { allOwnKeys } = {}) => {
forEach(
b,
(val, key) => {
if (thisArg && isFunction(val)) {
Object.defineProperty(a, key, {
// Null-proto descriptor so a polluted Object.prototype.get cannot
// hijack defineProperty's accessor-vs-data resolution.
__proto__: null,
value: bind(val, thisArg),
writable: true,
enumerable: true,
configurable: true,
});
} else {
Object.defineProperty(a, key, {
__proto__: null,
value: val,
writable: true,
enumerable: true,
configurable: true,
});
}
},
{ allOwnKeys }
);
return a;
};
/**
* Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
*
* @param {string} content with BOM
*
* @returns {string} content value without BOM
*/
const stripBOM = (content) => {
if (content.charCodeAt(0) === 0xfeff) {
content = content.slice(1);
}
return content;
};
/**
* Inherit the prototype methods from one constructor into another
* @param {function} constructor
* @param {function} superConstructor
* @param {object} [props]
* @param {object} [descriptors]
*
* @returns {void}
*/
const inherits = (constructor, superConstructor, props, descriptors) => {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
Object.defineProperty(constructor.prototype, 'constructor', {
__proto__: null,
value: constructor,
writable: true,
enumerable: false,
configurable: true,
});
Object.defineProperty(constructor, 'super', {
__proto__: null,
value: superConstructor.prototype,
});
props && Object.assign(constructor.prototype, props);
};
/**
* Resolve object with deep prototype chain to a flat object
* @param {Object} sourceObj source object
* @param {Object} [destObj]
* @param {Function|Boolean} [filter]
* @param {Function} [propFilter]
*
* @returns {Object}
*/
const toFlatObject = (sourceObj, destObj, filter, propFilter) => {
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
if (sourceObj == null) return destObj;
do {
props = Object.getOwnPropertyNames(sourceObj);
i = props.length;
while (i-- > 0) {
prop = props[i];
if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {
destObj[prop] = sourceObj[prop];
merged[prop] = true;
}
}
sourceObj = filter !== false && getPrototypeOf(sourceObj);
} while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);
return destObj;
};
/**
* Determines whether a string ends with the characters of a specified string
*
* @param {String} str
* @param {String} searchString
* @param {Number} [position= 0]
*
* @returns {boolean}
*/
const endsWith = (str, searchString, position) => {
str = String(str);
if (position === undefined || position > str.length) {
position = str.length;
}
position -= searchString.length;
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
/**
* Returns new array from array like object or null if failed
*
* @param {*} [thing]
*
* @returns {?Array}
*/
const toArray = (thing) => {
if (!thing) return null;
if (isArray(thing)) return thing;
let i = thing.length;
if (!isNumber(i)) return null;
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
return arr;
};
/**
* Checking if the Uint8Array exists and if it does, it returns a function that checks if the
* thing passed in is an instance of Uint8Array
*
* @param {TypedArray}
*
* @returns {Array}
*/
// eslint-disable-next-line func-names
const isTypedArray = ((TypedArray) => {
// eslint-disable-next-line func-names
return (thing) => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));
/**
* For each entry in the object, call the function with the key and value.
*
* @param {Object<any, any>} obj - The object to iterate over.
* @param {Function} fn - The function to call for each entry.
*
* @returns {void}
*/
const forEachEntry = (obj, fn) => {
const generator = obj && obj[iterator];
const _iterator = generator.call(obj);
let result;
while ((result = _iterator.next()) && !result.done) {
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
};
/**
* It takes a regular expression and a string, and returns an array of all the matches
*
* @param {string} regExp - The regular expression to match against.
* @param {string} str - The string to search.
*
* @returns {Array<boolean>}
*/
const matchAll = (regExp, str) => {
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
}
return arr;
};
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = (str) => {
return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
});
};
const { propertyIsEnumerable } = Object.prototype;
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
const reduceDescriptors = (obj, reducer) => {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
let ret;
if ((ret = reducer(descriptor, name, obj)) !== false) {
reducedDescriptors[name] = ret || descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
};
/**
* Makes all methods read-only
* @param {Object} obj
*/
const freezeMethods = (obj) => {
reduceDescriptors(obj, (descriptor, name) => {
// skip restricted props in strict mode
if (isFunction(obj) && ['arguments', 'caller', 'callee'].includes(name)) {
return false;
}
const value = obj[name];
if (!isFunction(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error("Can not rewrite read-only method '" + name + "'");
};
}
});
};
/**
* Converts an array or a delimited string into an object set with values as keys and true as values.
* Useful for fast membership checks.
*
* @param {Array|string} arrayOrString - The array or string to convert.
* @param {string} delimiter - The delimiter to use if input is a string.
* @returns {Object} An object with keys from the array or string, values set to true.
*/
const toObjectSet = (arrayOrString, delimiter) => {
const obj = {};
const define = (arr) => {
arr.forEach((value) => {
obj[value] = true;
});
};
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
};
const noop = () => {};
const toFiniteNumber = (value, defaultValue) => {
return value != null && Number.isFinite((value = +value)) ? value : defaultValue;
};
/**
* If the thing is a FormData object, return true, otherwise return false.
*
* @param {unknown} thing - The thing to check.
*
* @returns {boolean}
*/
function isSpecCompliantForm(thing) {
return !!(
thing &&
isFunction(thing.append) &&
thing[toStringTag] === 'FormData' &&
thing[iterator]
);
}
/**
* Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.
*
* @param {Object} obj - The object to convert.
* @returns {Object} The JSON-compatible object.
*/
const toJSONObject = (obj) => {
const visited = new WeakSet();
const visit = (source) => {
if (isObject(source)) {
if (visited.has(source)) {
return;
}
//Buffer check
if (isBuffer(source)) {
return source;
}
if (!('toJSON' in source)) {
// add-on descent / delete-on-ascent: preserves path semantics, so DAG nodes serialise at every occurrence (see #7230).
visited.add(source);
const target = isArray(source) ? [] : {};
forEach(source, (value, key) => {
const reducedValue = visit(value);
!isUndefined(reducedValue) && (target[key] = reducedValue);
});
visited.delete(source);
return target;
}
}
return source;
};
return visit(obj);
};
/**
* Determines if a value is an async function.
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is an async function, otherwise false.
*/
const isAsyncFn = kindOfTest('AsyncFunction');
/**
* Determines if a value is thenable (has then and catch methods).
*
* @param {*} thing - The value to test.
* @returns {boolean} True if value is thenable, otherwise false.
*/
const isThenable = (thing) =>
thing &&
(isObject(thing) || isFunction(thing)) &&
isFunction(thing.then) &&
isFunction(thing.catch);
// original code
// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34
/**
* Provides a cross-platform setImmediate implementation.
* Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.
*
* @param {boolean} setImmediateSupported - Whether setImmediate is supported.
* @param {boolean} postMessageSupported - Whether postMessage is supported.
* @returns {Function} A function to schedule a callback asynchronously.
*/
const _setImmediate = ((setImmediateSupported, postMessageSupported) => {
if (setImmediateSupported) {
return setImmediate;
}
return postMessageSupported
? ((token, callbacks) => {
_global.addEventListener(
'message',
({ source, data }) => {
if (source === _global && data === token) {
callbacks.length && callbacks.shift()();
}
},
false
);
return (cb) => {
callbacks.push(cb);
_global.postMessage(token, '*');
};
})(`axios@${Math.random()}`, [])
: (cb) => setTimeout(cb);
})(typeof setImmediate === 'function', isFunction(_global.postMessage));
/**
* Schedules a microtask or asynchronous callback as soon as possible.
* Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.
*
* @type {Function}
*/
const asap =
typeof queueMicrotask !== 'undefined'
? queueMicrotask.bind(_global)
: (typeof process !== 'undefined' && process.nextTick) || _setImmediate;
// *********************
const isIterable = (thing) => thing != null && isFunction(thing[iterator]);
/**
* Determine if a value is iterable via an iterator that is NOT sourced solely
* from a polluted Object.prototype. Use this instead of `isIterable` whenever
* the iterable comes from untrusted input (e.g. user-supplied header sources),
* so `Object.prototype[Symbol.iterator] = ...` cannot turn an ordinary object
* into an attacker-controlled entries iterator.
*
* @param {*} thing The value to test
*
* @returns {boolean} True if value has a non-polluted iterator
*/
const isSafeIterable = (thing) =>
thing != null && hasOwnInPrototypeChain(thing, iterator) && isIterable(thing);
export default {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isEmptyObject,
isReadableStream,
isRequest,
isResponse,
isHeaders,
isUndefined,
isDate,
isFile,
isReactNativeBlob,
isReactNative,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
hasOwnInPrototypeChain,
getSafeProp,
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber,
findKey,
global: _global,
isContextDefined,
isSpecCompliantForm,
toJSONObject,
isAsyncFn,
isThenable,
setImmediate: _setImmediate,
asap,
isIterable,
isSafeIterable,
};
+145
View File
@@ -0,0 +1,145 @@
agent-base
==========
### Turn a function into an [`http.Agent`][http.Agent] instance
[![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI)
This module provides an `http.Agent` generator. That is, you pass it an async
callback function, and it returns a new `http.Agent` instance that will invoke the
given callback function when sending outbound HTTP requests.
#### Some subclasses:
Here's some more interesting uses of `agent-base`.
Send a pull request to list yours!
* [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints
* [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints
* [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS
* [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS proxy `http.Agent` implementation for HTTP and HTTPS
Installation
------------
Install with `npm`:
``` bash
$ npm install agent-base
```
Example
-------
Here's a minimal example that creates a new `net.Socket` connection to the server
for every HTTP request (i.e. the equivalent of `agent: false` option):
```js
var net = require('net');
var tls = require('tls');
var url = require('url');
var http = require('http');
var agent = require('agent-base');
var endpoint = 'http://nodejs.org/api/';
var parsed = url.parse(endpoint);
// This is the important part!
parsed.agent = agent(function (req, opts) {
var socket;
// `secureEndpoint` is true when using the https module
if (opts.secureEndpoint) {
socket = tls.connect(opts);
} else {
socket = net.connect(opts);
}
return socket;
});
// Everything else works just like normal...
http.get(parsed, function (res) {
console.log('"response" event!', res.headers);
res.pipe(process.stdout);
});
```
Returning a Promise or using an `async` function is also supported:
```js
agent(async function (req, opts) {
await sleep(1000);
// etc…
});
```
Return another `http.Agent` instance to "pass through" the responsibility
for that HTTP request to that agent:
```js
agent(function (req, opts) {
return opts.secureEndpoint ? https.globalAgent : http.globalAgent;
});
```
API
---
## Agent(Function callback[, Object options]) → [http.Agent][]
Creates a base `http.Agent` that will execute the callback function `callback`
for every HTTP request that it is used as the `agent` for. The callback function
is responsible for creating a `stream.Duplex` instance of some kind that will be
used as the underlying socket in the HTTP request.
The `options` object accepts the following properties:
* `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional).
The callback function should have the following signature:
### callback(http.ClientRequest req, Object options, Function cb) → undefined
The ClientRequest `req` can be accessed to read request headers and
and the path, etc. The `options` object contains the options passed
to the `http.request()`/`https.request()` function call, and is formatted
to be directly passed to `net.connect()`/`tls.connect()`, or however
else you want a Socket to be created. Pass the created socket to
the callback function `cb` once created, and the HTTP request will
continue to proceed.
If the `https` module is used to invoke the HTTP request, then the
`secureEndpoint` property on `options` _will be set to `true`_.
License
-------
(The MIT License)
Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent
[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent
[pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent
[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent
[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent
+78
View File
@@ -0,0 +1,78 @@
/// <reference types="node" />
import net from 'net';
import http from 'http';
import https from 'https';
import { Duplex } from 'stream';
import { EventEmitter } from 'events';
declare function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent;
declare function createAgent(callback: createAgent.AgentCallback, opts?: createAgent.AgentOptions): createAgent.Agent;
declare namespace createAgent {
interface ClientRequest extends http.ClientRequest {
_last?: boolean;
_hadError?: boolean;
method: string;
}
interface AgentRequestOptions {
host?: string;
path?: string;
port: number;
}
interface HttpRequestOptions extends AgentRequestOptions, Omit<http.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: false;
}
interface HttpsRequestOptions extends AgentRequestOptions, Omit<https.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: true;
}
type RequestOptions = HttpRequestOptions | HttpsRequestOptions;
type AgentLike = Pick<createAgent.Agent, 'addRequest'> | http.Agent;
type AgentCallbackReturn = Duplex | AgentLike;
type AgentCallbackCallback = (err?: Error | null, socket?: createAgent.AgentCallbackReturn) => void;
type AgentCallbackPromise = (req: createAgent.ClientRequest, opts: createAgent.RequestOptions) => createAgent.AgentCallbackReturn | Promise<createAgent.AgentCallbackReturn>;
type AgentCallback = typeof Agent.prototype.callback;
type AgentOptions = {
timeout?: number;
};
/**
* Base `http.Agent` implementation.
* No pooling/keep-alive is implemented by default.
*
* @param {Function} callback
* @api public
*/
class Agent extends EventEmitter {
timeout: number | null;
maxFreeSockets: number;
maxTotalSockets: number;
maxSockets: number;
sockets: {
[key: string]: net.Socket[];
};
freeSockets: {
[key: string]: net.Socket[];
};
requests: {
[key: string]: http.IncomingMessage[];
};
options: https.AgentOptions;
private promisifiedCallback?;
private explicitDefaultPort?;
private explicitProtocol?;
constructor(callback?: createAgent.AgentCallback | createAgent.AgentOptions, _opts?: createAgent.AgentOptions);
get defaultPort(): number;
set defaultPort(v: number);
get protocol(): string;
set protocol(v: string);
callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions, fn: createAgent.AgentCallbackCallback): void;
callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions): createAgent.AgentCallbackReturn | Promise<createAgent.AgentCallbackReturn>;
/**
* Called by node-core's "_http_client.js" module when creating
* a new HTTP request with this Agent instance.
*
* @api public
*/
addRequest(req: ClientRequest, _opts: RequestOptions): void;
freeSocket(socket: net.Socket, opts: AgentOptions): void;
destroy(): void;
}
}
export = createAgent;
+203
View File
@@ -0,0 +1,203 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const events_1 = require("events");
const debug_1 = __importDefault(require("debug"));
const promisify_1 = __importDefault(require("./promisify"));
const debug = debug_1.default('agent-base');
function isAgent(v) {
return Boolean(v) && typeof v.addRequest === 'function';
}
function isSecureEndpoint() {
const { stack } = new Error();
if (typeof stack !== 'string')
return false;
return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);
}
function createAgent(callback, opts) {
return new createAgent.Agent(callback, opts);
}
(function (createAgent) {
/**
* Base `http.Agent` implementation.
* No pooling/keep-alive is implemented by default.
*
* @param {Function} callback
* @api public
*/
class Agent extends events_1.EventEmitter {
constructor(callback, _opts) {
super();
let opts = _opts;
if (typeof callback === 'function') {
this.callback = callback;
}
else if (callback) {
opts = callback;
}
// Timeout for the socket to be returned from the callback
this.timeout = null;
if (opts && typeof opts.timeout === 'number') {
this.timeout = opts.timeout;
}
// These aren't actually used by `agent-base`, but are required
// for the TypeScript definition files in `@types/node` :/
this.maxFreeSockets = 1;
this.maxSockets = 1;
this.maxTotalSockets = Infinity;
this.sockets = {};
this.freeSockets = {};
this.requests = {};
this.options = {};
}
get defaultPort() {
if (typeof this.explicitDefaultPort === 'number') {
return this.explicitDefaultPort;
}
return isSecureEndpoint() ? 443 : 80;
}
set defaultPort(v) {
this.explicitDefaultPort = v;
}
get protocol() {
if (typeof this.explicitProtocol === 'string') {
return this.explicitProtocol;
}
return isSecureEndpoint() ? 'https:' : 'http:';
}
set protocol(v) {
this.explicitProtocol = v;
}
callback(req, opts, fn) {
throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`');
}
/**
* Called by node-core's "_http_client.js" module when creating
* a new HTTP request with this Agent instance.
*
* @api public
*/
addRequest(req, _opts) {
const opts = Object.assign({}, _opts);
if (typeof opts.secureEndpoint !== 'boolean') {
opts.secureEndpoint = isSecureEndpoint();
}
if (opts.host == null) {
opts.host = 'localhost';
}
if (opts.port == null) {
opts.port = opts.secureEndpoint ? 443 : 80;
}
if (opts.protocol == null) {
opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';
}
if (opts.host && opts.path) {
// If both a `host` and `path` are specified then it's most
// likely the result of a `url.parse()` call... we need to
// remove the `path` portion so that `net.connect()` doesn't
// attempt to open that as a unix socket file.
delete opts.path;
}
delete opts.agent;
delete opts.hostname;
delete opts._defaultAgent;
delete opts.defaultPort;
delete opts.createConnection;
// Hint to use "Connection: close"
// XXX: non-documented `http` module API :(
req._last = true;
req.shouldKeepAlive = false;
let timedOut = false;
let timeoutId = null;
const timeoutMs = opts.timeout || this.timeout;
const onerror = (err) => {
if (req._hadError)
return;
req.emit('error', err);
// For Safety. Some additional errors might fire later on
// and we need to make sure we don't double-fire the error event.
req._hadError = true;
};
const ontimeout = () => {
timeoutId = null;
timedOut = true;
const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`);
err.code = 'ETIMEOUT';
onerror(err);
};
const callbackError = (err) => {
if (timedOut)
return;
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
onerror(err);
};
const onsocket = (socket) => {
if (timedOut)
return;
if (timeoutId != null) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (isAgent(socket)) {
// `socket` is actually an `http.Agent` instance, so
// relinquish responsibility for this `req` to the Agent
// from here on
debug('Callback returned another Agent instance %o', socket.constructor.name);
socket.addRequest(req, opts);
return;
}
if (socket) {
socket.once('free', () => {
this.freeSocket(socket, opts);
});
req.onSocket(socket);
return;
}
const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``);
onerror(err);
};
if (typeof this.callback !== 'function') {
onerror(new Error('`callback` is not defined'));
return;
}
if (!this.promisifiedCallback) {
if (this.callback.length >= 3) {
debug('Converting legacy callback function to promise');
this.promisifiedCallback = promisify_1.default(this.callback);
}
else {
this.promisifiedCallback = this.callback;
}
}
if (typeof timeoutMs === 'number' && timeoutMs > 0) {
timeoutId = setTimeout(ontimeout, timeoutMs);
}
if ('port' in opts && typeof opts.port !== 'number') {
opts.port = Number(opts.port);
}
try {
debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`);
Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError);
}
catch (err) {
Promise.reject(err).catch(callbackError);
}
}
freeSocket(socket, opts) {
debug('Freeing socket %o %o', socket.constructor.name, opts);
socket.destroy();
}
destroy() {
debug('Destroying agent %o', this.constructor.name);
}
}
createAgent.Agent = Agent;
// So that `instanceof` works correctly
createAgent.prototype = createAgent.Agent.prototype;
})(createAgent || (createAgent = {}));
module.exports = createAgent;
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+4
View File
@@ -0,0 +1,4 @@
import { ClientRequest, RequestOptions, AgentCallbackCallback, AgentCallbackPromise } from './index';
declare type LegacyCallback = (req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback) => void;
export default function promisify(fn: LegacyCallback): AgentCallbackPromise;
export {};
+18
View File
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function promisify(fn) {
return function (req, opts) {
return new Promise((resolve, reject) => {
fn.call(this, req, opts, (err, rtn) => {
if (err) {
reject(err);
}
else {
resolve(rtn);
}
});
});
};
}
exports.default = promisify;
//# sourceMappingURL=promisify.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"promisify.js","sourceRoot":"","sources":["../../src/promisify.ts"],"names":[],"mappings":";;AAeA,SAAwB,SAAS,CAAC,EAAkB;IACnD,OAAO,UAAsB,GAAkB,EAAE,IAAoB;QACpE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,EAAE,CAAC,IAAI,CACN,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,CAAC,GAA6B,EAAE,GAAyB,EAAE,EAAE;gBAC5D,IAAI,GAAG,EAAE;oBACR,MAAM,CAAC,GAAG,CAAC,CAAC;iBACZ;qBAAM;oBACN,OAAO,CAAC,GAAG,CAAC,CAAC;iBACb;YACF,CAAC,CACD,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AAjBD,4BAiBC"}
+64
View File
@@ -0,0 +1,64 @@
{
"name": "agent-base",
"version": "6.0.2",
"description": "Turn a function into an `http.Agent` instance",
"main": "dist/src/index",
"typings": "dist/src/index",
"files": [
"dist/src",
"src"
],
"scripts": {
"prebuild": "rimraf dist",
"build": "tsc",
"postbuild": "cpy --parents src test '!**/*.ts' dist",
"test": "mocha --reporter spec dist/test/*.js",
"test-lint": "eslint src --ext .js,.ts",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-agent-base.git"
},
"keywords": [
"http",
"agent",
"base",
"barebones",
"https"
],
"author": "Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/TooTallNate/node-agent-base/issues"
},
"dependencies": {
"debug": "4"
},
"devDependencies": {
"@types/debug": "4",
"@types/mocha": "^5.2.7",
"@types/node": "^14.0.20",
"@types/semver": "^7.1.0",
"@types/ws": "^6.0.3",
"@typescript-eslint/eslint-plugin": "1.6.0",
"@typescript-eslint/parser": "1.1.0",
"async-listen": "^1.2.0",
"cpy-cli": "^2.0.0",
"eslint": "5.16.0",
"eslint-config-airbnb": "17.1.0",
"eslint-config-prettier": "4.1.0",
"eslint-import-resolver-typescript": "1.1.1",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jsx-a11y": "6.2.1",
"eslint-plugin-react": "7.12.4",
"mocha": "^6.2.0",
"rimraf": "^3.0.0",
"semver": "^7.1.2",
"typescript": "^3.5.3",
"ws": "^3.0.0"
},
"engines": {
"node": ">= 6.0.0"
}
}
+345
View File
@@ -0,0 +1,345 @@
import net from 'net';
import http from 'http';
import https from 'https';
import { Duplex } from 'stream';
import { EventEmitter } from 'events';
import createDebug from 'debug';
import promisify from './promisify';
const debug = createDebug('agent-base');
function isAgent(v: any): v is createAgent.AgentLike {
return Boolean(v) && typeof v.addRequest === 'function';
}
function isSecureEndpoint(): boolean {
const { stack } = new Error();
if (typeof stack !== 'string') return false;
return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1);
}
function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent;
function createAgent(
callback: createAgent.AgentCallback,
opts?: createAgent.AgentOptions
): createAgent.Agent;
function createAgent(
callback?: createAgent.AgentCallback | createAgent.AgentOptions,
opts?: createAgent.AgentOptions
) {
return new createAgent.Agent(callback, opts);
}
namespace createAgent {
export interface ClientRequest extends http.ClientRequest {
_last?: boolean;
_hadError?: boolean;
method: string;
}
export interface AgentRequestOptions {
host?: string;
path?: string;
// `port` on `http.RequestOptions` can be a string or undefined,
// but `net.TcpNetConnectOpts` expects only a number
port: number;
}
export interface HttpRequestOptions
extends AgentRequestOptions,
Omit<http.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: false;
}
export interface HttpsRequestOptions
extends AgentRequestOptions,
Omit<https.RequestOptions, keyof AgentRequestOptions> {
secureEndpoint: true;
}
export type RequestOptions = HttpRequestOptions | HttpsRequestOptions;
export type AgentLike = Pick<createAgent.Agent, 'addRequest'> | http.Agent;
export type AgentCallbackReturn = Duplex | AgentLike;
export type AgentCallbackCallback = (
err?: Error | null,
socket?: createAgent.AgentCallbackReturn
) => void;
export type AgentCallbackPromise = (
req: createAgent.ClientRequest,
opts: createAgent.RequestOptions
) =>
| createAgent.AgentCallbackReturn
| Promise<createAgent.AgentCallbackReturn>;
export type AgentCallback = typeof Agent.prototype.callback;
export type AgentOptions = {
timeout?: number;
};
/**
* Base `http.Agent` implementation.
* No pooling/keep-alive is implemented by default.
*
* @param {Function} callback
* @api public
*/
export class Agent extends EventEmitter {
public timeout: number | null;
public maxFreeSockets: number;
public maxTotalSockets: number;
public maxSockets: number;
public sockets: {
[key: string]: net.Socket[];
};
public freeSockets: {
[key: string]: net.Socket[];
};
public requests: {
[key: string]: http.IncomingMessage[];
};
public options: https.AgentOptions;
private promisifiedCallback?: createAgent.AgentCallbackPromise;
private explicitDefaultPort?: number;
private explicitProtocol?: string;
constructor(
callback?: createAgent.AgentCallback | createAgent.AgentOptions,
_opts?: createAgent.AgentOptions
) {
super();
let opts = _opts;
if (typeof callback === 'function') {
this.callback = callback;
} else if (callback) {
opts = callback;
}
// Timeout for the socket to be returned from the callback
this.timeout = null;
if (opts && typeof opts.timeout === 'number') {
this.timeout = opts.timeout;
}
// These aren't actually used by `agent-base`, but are required
// for the TypeScript definition files in `@types/node` :/
this.maxFreeSockets = 1;
this.maxSockets = 1;
this.maxTotalSockets = Infinity;
this.sockets = {};
this.freeSockets = {};
this.requests = {};
this.options = {};
}
get defaultPort(): number {
if (typeof this.explicitDefaultPort === 'number') {
return this.explicitDefaultPort;
}
return isSecureEndpoint() ? 443 : 80;
}
set defaultPort(v: number) {
this.explicitDefaultPort = v;
}
get protocol(): string {
if (typeof this.explicitProtocol === 'string') {
return this.explicitProtocol;
}
return isSecureEndpoint() ? 'https:' : 'http:';
}
set protocol(v: string) {
this.explicitProtocol = v;
}
callback(
req: createAgent.ClientRequest,
opts: createAgent.RequestOptions,
fn: createAgent.AgentCallbackCallback
): void;
callback(
req: createAgent.ClientRequest,
opts: createAgent.RequestOptions
):
| createAgent.AgentCallbackReturn
| Promise<createAgent.AgentCallbackReturn>;
callback(
req: createAgent.ClientRequest,
opts: createAgent.AgentOptions,
fn?: createAgent.AgentCallbackCallback
):
| createAgent.AgentCallbackReturn
| Promise<createAgent.AgentCallbackReturn>
| void {
throw new Error(
'"agent-base" has no default implementation, you must subclass and override `callback()`'
);
}
/**
* Called by node-core's "_http_client.js" module when creating
* a new HTTP request with this Agent instance.
*
* @api public
*/
addRequest(req: ClientRequest, _opts: RequestOptions): void {
const opts: RequestOptions = { ..._opts };
if (typeof opts.secureEndpoint !== 'boolean') {
opts.secureEndpoint = isSecureEndpoint();
}
if (opts.host == null) {
opts.host = 'localhost';
}
if (opts.port == null) {
opts.port = opts.secureEndpoint ? 443 : 80;
}
if (opts.protocol == null) {
opts.protocol = opts.secureEndpoint ? 'https:' : 'http:';
}
if (opts.host && opts.path) {
// If both a `host` and `path` are specified then it's most
// likely the result of a `url.parse()` call... we need to
// remove the `path` portion so that `net.connect()` doesn't
// attempt to open that as a unix socket file.
delete opts.path;
}
delete opts.agent;
delete opts.hostname;
delete opts._defaultAgent;
delete opts.defaultPort;
delete opts.createConnection;
// Hint to use "Connection: close"
// XXX: non-documented `http` module API :(
req._last = true;
req.shouldKeepAlive = false;
let timedOut = false;
let timeoutId: ReturnType<typeof setTimeout> | null = null;
const timeoutMs = opts.timeout || this.timeout;
const onerror = (err: NodeJS.ErrnoException) => {
if (req._hadError) return;
req.emit('error', err);
// For Safety. Some additional errors might fire later on
// and we need to make sure we don't double-fire the error event.
req._hadError = true;
};
const ontimeout = () => {
timeoutId = null;
timedOut = true;
const err: NodeJS.ErrnoException = new Error(
`A "socket" was not created for HTTP request before ${timeoutMs}ms`
);
err.code = 'ETIMEOUT';
onerror(err);
};
const callbackError = (err: NodeJS.ErrnoException) => {
if (timedOut) return;
if (timeoutId !== null) {
clearTimeout(timeoutId);
timeoutId = null;
}
onerror(err);
};
const onsocket = (socket: AgentCallbackReturn) => {
if (timedOut) return;
if (timeoutId != null) {
clearTimeout(timeoutId);
timeoutId = null;
}
if (isAgent(socket)) {
// `socket` is actually an `http.Agent` instance, so
// relinquish responsibility for this `req` to the Agent
// from here on
debug(
'Callback returned another Agent instance %o',
socket.constructor.name
);
(socket as createAgent.Agent).addRequest(req, opts);
return;
}
if (socket) {
socket.once('free', () => {
this.freeSocket(socket as net.Socket, opts);
});
req.onSocket(socket as net.Socket);
return;
}
const err = new Error(
`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``
);
onerror(err);
};
if (typeof this.callback !== 'function') {
onerror(new Error('`callback` is not defined'));
return;
}
if (!this.promisifiedCallback) {
if (this.callback.length >= 3) {
debug('Converting legacy callback function to promise');
this.promisifiedCallback = promisify(this.callback);
} else {
this.promisifiedCallback = this.callback;
}
}
if (typeof timeoutMs === 'number' && timeoutMs > 0) {
timeoutId = setTimeout(ontimeout, timeoutMs);
}
if ('port' in opts && typeof opts.port !== 'number') {
opts.port = Number(opts.port);
}
try {
debug(
'Resolving socket for %o request: %o',
opts.protocol,
`${req.method} ${req.path}`
);
Promise.resolve(this.promisifiedCallback(req, opts)).then(
onsocket,
callbackError
);
} catch (err) {
Promise.reject(err).catch(callbackError);
}
}
freeSocket(socket: net.Socket, opts: AgentOptions) {
debug('Freeing socket %o %o', socket.constructor.name, opts);
socket.destroy();
}
destroy() {
debug('Destroying agent %o', this.constructor.name);
}
}
// So that `instanceof` works correctly
createAgent.prototype = createAgent.Agent.prototype;
}
export = createAgent;
+33
View File
@@ -0,0 +1,33 @@
import {
Agent,
ClientRequest,
RequestOptions,
AgentCallbackCallback,
AgentCallbackPromise,
AgentCallbackReturn
} from './index';
type LegacyCallback = (
req: ClientRequest,
opts: RequestOptions,
fn: AgentCallbackCallback
) => void;
export default function promisify(fn: LegacyCallback): AgentCallbackPromise {
return function(this: Agent, req: ClientRequest, opts: RequestOptions) {
return new Promise((resolve, reject) => {
fn.call(
this,
req,
opts,
(err: Error | null | undefined, rtn?: AgentCallbackReturn) => {
if (err) {
reject(err);
} else {
resolve(rtn);
}
}
);
});
};
}
+137
View File
@@ -0,0 +1,137 @@
https-proxy-agent
================
### An HTTP(s) proxy `http.Agent` implementation for HTTPS
[![Build Status](https://github.com/TooTallNate/node-https-proxy-agent/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-https-proxy-agent/actions?workflow=Node+CI)
This module provides an `http.Agent` implementation that connects to a specified
HTTP or HTTPS proxy server, and can be used with the built-in `https` module.
Specifically, this `Agent` implementation connects to an intermediary "proxy"
server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to
open a direct TCP connection to the destination server.
Since this agent implements the CONNECT HTTP method, it also works with other
protocols that use this method when connecting over proxies (i.e. WebSockets).
See the "Examples" section below for more.
Installation
------------
Install with `npm`:
``` bash
$ npm install https-proxy-agent
```
Examples
--------
#### `https` module example
``` js
var url = require('url');
var https = require('https');
var HttpsProxyAgent = require('https-proxy-agent');
// HTTP/HTTPS proxy to connect to
var proxy = process.env.http_proxy || 'http://168.63.76.32:3128';
console.log('using proxy server %j', proxy);
// HTTPS endpoint for the proxy to connect to
var endpoint = process.argv[2] || 'https://graph.facebook.com/tootallnate';
console.log('attempting to GET %j', endpoint);
var options = url.parse(endpoint);
// create an instance of the `HttpsProxyAgent` class with the proxy server information
var agent = new HttpsProxyAgent(proxy);
options.agent = agent;
https.get(options, function (res) {
console.log('"response" event!', res.headers);
res.pipe(process.stdout);
});
```
#### `ws` WebSocket connection example
``` js
var url = require('url');
var WebSocket = require('ws');
var HttpsProxyAgent = require('https-proxy-agent');
// HTTP/HTTPS proxy to connect to
var proxy = process.env.http_proxy || 'http://168.63.76.32:3128';
console.log('using proxy server %j', proxy);
// WebSocket endpoint for the proxy to connect to
var endpoint = process.argv[2] || 'ws://echo.websocket.org';
var parsed = url.parse(endpoint);
console.log('attempting to connect to WebSocket %j', endpoint);
// create an instance of the `HttpsProxyAgent` class with the proxy server information
var options = url.parse(proxy);
var agent = new HttpsProxyAgent(options);
// finally, initiate the WebSocket connection
var socket = new WebSocket(endpoint, { agent: agent });
socket.on('open', function () {
console.log('"open" event!');
socket.send('hello world');
});
socket.on('message', function (data, flags) {
console.log('"message" event! %j %j', data, flags);
socket.close();
});
```
API
---
### new HttpsProxyAgent(Object options)
The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects
to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket
requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT].
The `options` argument may either be a string URI of the proxy server to use, or an
"options" object with more specific properties:
* `host` - String - Proxy host to connect to (may use `hostname` as well). Required.
* `port` - Number - Proxy port to connect to. Required.
* `protocol` - String - If `https:`, then use TLS to connect to the proxy.
* `headers` - Object - Additional HTTP headers to be sent on the HTTP CONNECT method.
* Any other options given are passed to the `net.connect()`/`tls.connect()` functions.
License
-------
(The MIT License)
Copyright (c) 2013 Nathan Rajlich &lt;nathan@tootallnate.net&gt;
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling
+30
View File
@@ -0,0 +1,30 @@
/// <reference types="node" />
import net from 'net';
import { Agent, ClientRequest, RequestOptions } from 'agent-base';
import { HttpsProxyAgentOptions } from '.';
/**
* The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
* the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
*
* Outgoing HTTP requests are first tunneled through the proxy server using the
* `CONNECT` HTTP request method to establish a connection to the proxy server,
* and then the proxy server connects to the destination target and issues the
* HTTP request from the proxy server.
*
* `https:` requests have their socket connection upgraded to TLS once
* the connection to the proxy server has been established.
*
* @api public
*/
export default class HttpsProxyAgent extends Agent {
private secureProxy;
private proxy;
constructor(_opts: string | HttpsProxyAgentOptions);
/**
* Called when the node-core HTTP client library is creating a
* new HTTP request.
*
* @api protected
*/
callback(req: ClientRequest, opts: RequestOptions): Promise<net.Socket>;
}
+177
View File
@@ -0,0 +1,177 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const net_1 = __importDefault(require("net"));
const tls_1 = __importDefault(require("tls"));
const url_1 = __importDefault(require("url"));
const assert_1 = __importDefault(require("assert"));
const debug_1 = __importDefault(require("debug"));
const agent_base_1 = require("agent-base");
const parse_proxy_response_1 = __importDefault(require("./parse-proxy-response"));
const debug = debug_1.default('https-proxy-agent:agent');
/**
* The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to
* the specified "HTTP(s) proxy server" in order to proxy HTTPS requests.
*
* Outgoing HTTP requests are first tunneled through the proxy server using the
* `CONNECT` HTTP request method to establish a connection to the proxy server,
* and then the proxy server connects to the destination target and issues the
* HTTP request from the proxy server.
*
* `https:` requests have their socket connection upgraded to TLS once
* the connection to the proxy server has been established.
*
* @api public
*/
class HttpsProxyAgent extends agent_base_1.Agent {
constructor(_opts) {
let opts;
if (typeof _opts === 'string') {
opts = url_1.default.parse(_opts);
}
else {
opts = _opts;
}
if (!opts) {
throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
}
debug('creating new HttpsProxyAgent instance: %o', opts);
super(opts);
const proxy = Object.assign({}, opts);
// If `true`, then connect to the proxy server over TLS.
// Defaults to `false`.
this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol);
// Prefer `hostname` over `host`, and set the `port` if needed.
proxy.host = proxy.hostname || proxy.host;
if (typeof proxy.port === 'string') {
proxy.port = parseInt(proxy.port, 10);
}
if (!proxy.port && proxy.host) {
proxy.port = this.secureProxy ? 443 : 80;
}
// ALPN is supported by Node.js >= v5.
// attempt to negotiate http/1.1 for proxy servers that support http/2
if (this.secureProxy && !('ALPNProtocols' in proxy)) {
proxy.ALPNProtocols = ['http 1.1'];
}
if (proxy.host && proxy.path) {
// If both a `host` and `path` are specified then it's most likely
// the result of a `url.parse()` call... we need to remove the
// `path` portion so that `net.connect()` doesn't attempt to open
// that as a Unix socket file.
delete proxy.path;
delete proxy.pathname;
}
this.proxy = proxy;
}
/**
* Called when the node-core HTTP client library is creating a
* new HTTP request.
*
* @api protected
*/
callback(req, opts) {
return __awaiter(this, void 0, void 0, function* () {
const { proxy, secureProxy } = this;
// Create a socket connection to the proxy server.
let socket;
if (secureProxy) {
debug('Creating `tls.Socket`: %o', proxy);
socket = tls_1.default.connect(proxy);
}
else {
debug('Creating `net.Socket`: %o', proxy);
socket = net_1.default.connect(proxy);
}
const headers = Object.assign({}, proxy.headers);
const hostname = `${opts.host}:${opts.port}`;
let payload = `CONNECT ${hostname} HTTP/1.1\r\n`;
// Inject the `Proxy-Authorization` header if necessary.
if (proxy.auth) {
headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`;
}
// The `Host` header should only include the port
// number when it is not the default port.
let { host, port, secureEndpoint } = opts;
if (!isDefaultPort(port, secureEndpoint)) {
host += `:${port}`;
}
headers.Host = host;
headers.Connection = 'close';
for (const name of Object.keys(headers)) {
payload += `${name}: ${headers[name]}\r\n`;
}
const proxyResponsePromise = parse_proxy_response_1.default(socket);
socket.write(`${payload}\r\n`);
const { statusCode, buffered } = yield proxyResponsePromise;
if (statusCode === 200) {
req.once('socket', resume);
if (opts.secureEndpoint) {
// The proxy is connecting to a TLS server, so upgrade
// this socket connection to a TLS connection.
debug('Upgrading socket connection to TLS');
const servername = opts.servername || opts.host;
return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket,
servername }));
}
return socket;
}
// Some other status code that's not 200... need to re-play the HTTP
// header "data" events onto the socket once the HTTP machinery is
// attached so that the node core `http` can parse and handle the
// error status code.
// Close the original socket, and a new "fake" socket is returned
// instead, so that the proxy doesn't get the HTTP request
// written to it (which may contain `Authorization` headers or other
// sensitive data).
//
// See: https://hackerone.com/reports/541502
socket.destroy();
const fakeSocket = new net_1.default.Socket({ writable: false });
fakeSocket.readable = true;
// Need to wait for the "socket" event to re-play the "data" events.
req.once('socket', (s) => {
debug('replaying proxy buffer for failed request');
assert_1.default(s.listenerCount('data') > 0);
// Replay the "buffered" Buffer onto the fake `socket`, since at
// this point the HTTP module machinery has been hooked up for
// the user.
s.push(buffered);
s.push(null);
});
return fakeSocket;
});
}
}
exports.default = HttpsProxyAgent;
function resume(socket) {
socket.resume();
}
function isDefaultPort(port, secure) {
return Boolean((!secure && port === 80) || (secure && port === 443));
}
function isHTTPS(protocol) {
return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false;
}
function omit(obj, ...keys) {
const ret = {};
let key;
for (key in obj) {
if (!keys.includes(key)) {
ret[key] = obj[key];
}
}
return ret;
}
//# sourceMappingURL=agent.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,8CAAsB;AACtB,8CAAsB;AACtB,8CAAsB;AACtB,oDAA4B;AAC5B,kDAAgC;AAEhC,2CAAkE;AAElE,kFAAwD;AAExD,MAAM,KAAK,GAAG,eAAW,CAAC,yBAAyB,CAAC,CAAC;AAErD;;;;;;;;;;;;;GAaG;AACH,MAAqB,eAAgB,SAAQ,kBAAK;IAIjD,YAAY,KAAsC;QACjD,IAAI,IAA4B,CAAC;QACjC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC9B,IAAI,GAAG,aAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;SACxB;aAAM;YACN,IAAI,GAAG,KAAK,CAAC;SACb;QACD,IAAI,CAAC,IAAI,EAAE;YACV,MAAM,IAAI,KAAK,CACd,8DAA8D,CAC9D,CAAC;SACF;QACD,KAAK,CAAC,2CAA2C,EAAE,IAAI,CAAC,CAAC;QACzD,KAAK,CAAC,IAAI,CAAC,CAAC;QAEZ,MAAM,KAAK,qBAAgC,IAAI,CAAE,CAAC;QAElD,wDAAwD;QACxD,uBAAuB;QACvB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,IAAI,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAE/D,+DAA+D;QAC/D,KAAK,CAAC,IAAI,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,IAAI,CAAC;QAC1C,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,EAAE;YACnC,KAAK,CAAC,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;SACtC;QACD,IAAI,CAAC,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,EAAE;YAC9B,KAAK,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;SACzC;QAED,sCAAsC;QACtC,sEAAsE;QACtE,IAAI,IAAI,CAAC,WAAW,IAAI,CAAC,CAAC,eAAe,IAAI,KAAK,CAAC,EAAE;YACpD,KAAK,CAAC,aAAa,GAAG,CAAC,UAAU,CAAC,CAAC;SACnC;QAED,IAAI,KAAK,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,EAAE;YAC7B,kEAAkE;YAClE,8DAA8D;YAC9D,iEAAiE;YACjE,8BAA8B;YAC9B,OAAO,KAAK,CAAC,IAAI,CAAC;YAClB,OAAO,KAAK,CAAC,QAAQ,CAAC;SACtB;QAED,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACpB,CAAC;IAED;;;;;OAKG;IACG,QAAQ,CACb,GAAkB,EAClB,IAAoB;;YAEpB,MAAM,EAAE,KAAK,EAAE,WAAW,EAAE,GAAG,IAAI,CAAC;YAEpC,kDAAkD;YAClD,IAAI,MAAkB,CAAC;YACvB,IAAI,WAAW,EAAE;gBAChB,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;gBAC1C,MAAM,GAAG,aAAG,CAAC,OAAO,CAAC,KAA8B,CAAC,CAAC;aACrD;iBAAM;gBACN,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;gBAC1C,MAAM,GAAG,aAAG,CAAC,OAAO,CAAC,KAA2B,CAAC,CAAC;aAClD;YAED,MAAM,OAAO,qBAA6B,KAAK,CAAC,OAAO,CAAE,CAAC;YAC1D,MAAM,QAAQ,GAAG,GAAG,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC7C,IAAI,OAAO,GAAG,WAAW,QAAQ,eAAe,CAAC;YAEjD,wDAAwD;YACxD,IAAI,KAAK,CAAC,IAAI,EAAE;gBACf,OAAO,CAAC,qBAAqB,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACpD,KAAK,CAAC,IAAI,CACV,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;aACvB;YAED,iDAAiD;YACjD,0CAA0C;YAC1C,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,IAAI,CAAC;YAC1C,IAAI,CAAC,aAAa,CAAC,IAAI,EAAE,cAAc,CAAC,EAAE;gBACzC,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;aACnB;YACD,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;YAEpB,OAAO,CAAC,UAAU,GAAG,OAAO,CAAC;YAC7B,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;gBACxC,OAAO,IAAI,GAAG,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;aAC3C;YAED,MAAM,oBAAoB,GAAG,8BAAkB,CAAC,MAAM,CAAC,CAAC;YAExD,MAAM,CAAC,KAAK,CAAC,GAAG,OAAO,MAAM,CAAC,CAAC;YAE/B,MAAM,EACL,UAAU,EACV,QAAQ,EACR,GAAG,MAAM,oBAAoB,CAAC;YAE/B,IAAI,UAAU,KAAK,GAAG,EAAE;gBACvB,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;gBAE3B,IAAI,IAAI,CAAC,cAAc,EAAE;oBACxB,sDAAsD;oBACtD,8CAA8C;oBAC9C,KAAK,CAAC,oCAAoC,CAAC,CAAC;oBAC5C,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,IAAI,CAAC;oBAChD,OAAO,aAAG,CAAC,OAAO,iCACd,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,KACjD,MAAM;wBACN,UAAU,IACT,CAAC;iBACH;gBAED,OAAO,MAAM,CAAC;aACd;YAED,oEAAoE;YACpE,kEAAkE;YAClE,iEAAiE;YACjE,qBAAqB;YAErB,iEAAiE;YACjE,0DAA0D;YAC1D,oEAAoE;YACpE,mBAAmB;YACnB,EAAE;YACF,4CAA4C;YAC5C,MAAM,CAAC,OAAO,EAAE,CAAC;YAEjB,MAAM,UAAU,GAAG,IAAI,aAAG,CAAC,MAAM,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;YACvD,UAAU,CAAC,QAAQ,GAAG,IAAI,CAAC;YAE3B,oEAAoE;YACpE,GAAG,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,CAAa,EAAE,EAAE;gBACpC,KAAK,CAAC,2CAA2C,CAAC,CAAC;gBACnD,gBAAM,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;gBAEpC,gEAAgE;gBAChE,8DAA8D;gBAC9D,YAAY;gBACZ,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;gBACjB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACd,CAAC,CAAC,CAAC;YAEH,OAAO,UAAU,CAAC;QACnB,CAAC;KAAA;CACD;AA3JD,kCA2JC;AAED,SAAS,MAAM,CAAC,MAAkC;IACjD,MAAM,CAAC,MAAM,EAAE,CAAC;AACjB,CAAC;AAED,SAAS,aAAa,CAAC,IAAY,EAAE,MAAe;IACnD,OAAO,OAAO,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC;AACtE,CAAC;AAED,SAAS,OAAO,CAAC,QAAwB;IACxC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;AAC3E,CAAC;AAED,SAAS,IAAI,CACZ,GAAM,EACN,GAAG,IAAO;IAIV,MAAM,GAAG,GAAG,EAEX,CAAC;IACF,IAAI,GAAqB,CAAC;IAC1B,KAAK,GAAG,IAAI,GAAG,EAAE;QAChB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;YACxB,GAAG,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;SACpB;KACD;IACD,OAAO,GAAG,CAAC;AACZ,CAAC"}
+23
View File
@@ -0,0 +1,23 @@
/// <reference types="node" />
import net from 'net';
import tls from 'tls';
import { Url } from 'url';
import { AgentOptions } from 'agent-base';
import { OutgoingHttpHeaders } from 'http';
import _HttpsProxyAgent from './agent';
declare function createHttpsProxyAgent(opts: string | createHttpsProxyAgent.HttpsProxyAgentOptions): _HttpsProxyAgent;
declare namespace createHttpsProxyAgent {
interface BaseHttpsProxyAgentOptions {
headers?: OutgoingHttpHeaders;
secureProxy?: boolean;
host?: string | null;
path?: string | null;
port?: string | number | null;
}
export interface HttpsProxyAgentOptions extends AgentOptions, BaseHttpsProxyAgentOptions, Partial<Omit<Url & net.NetConnectOpts & tls.ConnectionOptions, keyof BaseHttpsProxyAgentOptions>> {
}
export type HttpsProxyAgent = _HttpsProxyAgent;
export const HttpsProxyAgent: typeof _HttpsProxyAgent;
export {};
}
export = createHttpsProxyAgent;
+14
View File
@@ -0,0 +1,14 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const agent_1 = __importDefault(require("./agent"));
function createHttpsProxyAgent(opts) {
return new agent_1.default(opts);
}
(function (createHttpsProxyAgent) {
createHttpsProxyAgent.HttpsProxyAgent = agent_1.default;
createHttpsProxyAgent.prototype = agent_1.default.prototype;
})(createHttpsProxyAgent || (createHttpsProxyAgent = {}));
module.exports = createHttpsProxyAgent;
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAKA,oDAAuC;AAEvC,SAAS,qBAAqB,CAC7B,IAA2D;IAE3D,OAAO,IAAI,eAAgB,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,WAAU,qBAAqB;IAoBjB,qCAAe,GAAG,eAAgB,CAAC;IAEhD,qBAAqB,CAAC,SAAS,GAAG,eAAgB,CAAC,SAAS,CAAC;AAC9D,CAAC,EAvBS,qBAAqB,KAArB,qBAAqB,QAuB9B;AAED,iBAAS,qBAAqB,CAAC"}
@@ -0,0 +1,7 @@
/// <reference types="node" />
import { Readable } from 'stream';
export interface ProxyResponse {
statusCode: number;
buffered: Buffer;
}
export default function parseProxyResponse(socket: Readable): Promise<ProxyResponse>;
@@ -0,0 +1,66 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const debug_1 = __importDefault(require("debug"));
const debug = debug_1.default('https-proxy-agent:parse-proxy-response');
function parseProxyResponse(socket) {
return new Promise((resolve, reject) => {
// we need to buffer any HTTP traffic that happens with the proxy before we get
// the CONNECT response, so that if the response is anything other than an "200"
// response code, then we can re-play the "data" events on the socket once the
// HTTP parser is hooked up...
let buffersLength = 0;
const buffers = [];
function read() {
const b = socket.read();
if (b)
ondata(b);
else
socket.once('readable', read);
}
function cleanup() {
socket.removeListener('end', onend);
socket.removeListener('error', onerror);
socket.removeListener('close', onclose);
socket.removeListener('readable', read);
}
function onclose(err) {
debug('onclose had error %o', err);
}
function onend() {
debug('onend');
}
function onerror(err) {
cleanup();
debug('onerror %o', err);
reject(err);
}
function ondata(b) {
buffers.push(b);
buffersLength += b.length;
const buffered = Buffer.concat(buffers, buffersLength);
const endOfHeaders = buffered.indexOf('\r\n\r\n');
if (endOfHeaders === -1) {
// keep buffering
debug('have not received end of HTTP headers yet...');
read();
return;
}
const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n'));
const statusCode = +firstLine.split(' ')[1];
debug('got proxy server response: %o', firstLine);
resolve({
statusCode,
buffered
});
}
socket.on('error', onerror);
socket.on('close', onclose);
socket.on('end', onend);
read();
});
}
exports.default = parseProxyResponse;
//# sourceMappingURL=parse-proxy-response.js.map
@@ -0,0 +1 @@
{"version":3,"file":"parse-proxy-response.js","sourceRoot":"","sources":["../src/parse-proxy-response.ts"],"names":[],"mappings":";;;;;AAAA,kDAAgC;AAGhC,MAAM,KAAK,GAAG,eAAW,CAAC,wCAAwC,CAAC,CAAC;AAOpE,SAAwB,kBAAkB,CACzC,MAAgB;IAEhB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,+EAA+E;QAC/E,gFAAgF;QAChF,8EAA8E;QAC9E,8BAA8B;QAC9B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,MAAM,OAAO,GAAa,EAAE,CAAC;QAE7B,SAAS,IAAI;YACZ,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC;gBAAE,MAAM,CAAC,CAAC,CAAC,CAAC;;gBACZ,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACpC,CAAC;QAED,SAAS,OAAO;YACf,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YACpC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACzC,CAAC;QAED,SAAS,OAAO,CAAC,GAAW;YAC3B,KAAK,CAAC,sBAAsB,EAAE,GAAG,CAAC,CAAC;QACpC,CAAC;QAED,SAAS,KAAK;YACb,KAAK,CAAC,OAAO,CAAC,CAAC;QAChB,CAAC;QAED,SAAS,OAAO,CAAC,GAAU;YAC1B,OAAO,EAAE,CAAC;YACV,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,CAAC;QACb,CAAC;QAED,SAAS,MAAM,CAAC,CAAS;YACxB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,aAAa,IAAI,CAAC,CAAC,MAAM,CAAC;YAE1B,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;YACvD,MAAM,YAAY,GAAG,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;YAElD,IAAI,YAAY,KAAK,CAAC,CAAC,EAAE;gBACxB,iBAAiB;gBACjB,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBACtD,IAAI,EAAE,CAAC;gBACP,OAAO;aACP;YAED,MAAM,SAAS,GAAG,QAAQ,CAAC,QAAQ,CAClC,OAAO,EACP,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CACxB,CAAC;YACF,MAAM,UAAU,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5C,KAAK,CAAC,+BAA+B,EAAE,SAAS,CAAC,CAAC;YAClD,OAAO,CAAC;gBACP,UAAU;gBACV,QAAQ;aACR,CAAC,CAAC;QACJ,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAExB,IAAI,EAAE,CAAC;IACR,CAAC,CAAC,CAAC;AACJ,CAAC;AAvED,qCAuEC"}
+56
View File
@@ -0,0 +1,56 @@
{
"name": "https-proxy-agent",
"version": "5.0.1",
"description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS",
"main": "dist/index",
"types": "dist/index",
"files": [
"dist"
],
"scripts": {
"prebuild": "rimraf dist",
"build": "tsc",
"test": "mocha --reporter spec",
"test-lint": "eslint src --ext .js,.ts",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git://github.com/TooTallNate/node-https-proxy-agent.git"
},
"keywords": [
"https",
"proxy",
"endpoint",
"agent"
],
"author": "Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/TooTallNate/node-https-proxy-agent/issues"
},
"dependencies": {
"agent-base": "6",
"debug": "4"
},
"devDependencies": {
"@types/debug": "4",
"@types/node": "^12.12.11",
"@typescript-eslint/eslint-plugin": "1.6.0",
"@typescript-eslint/parser": "1.1.0",
"eslint": "5.16.0",
"eslint-config-airbnb": "17.1.0",
"eslint-config-prettier": "4.1.0",
"eslint-import-resolver-typescript": "1.1.1",
"eslint-plugin-import": "2.16.0",
"eslint-plugin-jsx-a11y": "6.2.1",
"eslint-plugin-react": "7.12.4",
"mocha": "^6.2.2",
"proxy": "1",
"rimraf": "^3.0.0",
"typescript": "^3.5.3"
},
"engines": {
"node": ">= 6"
}
}
+201
View File
@@ -0,0 +1,201 @@
{
"name": "axios",
"version": "1.18.1",
"description": "Promise based HTTP client for the browser and node.js",
"main": "./dist/node/axios.cjs",
"module": "./index.js",
"type": "module",
"types": "index.d.ts",
"jsdelivr": "dist/axios.min.js",
"unpkg": "dist/axios.min.js",
"typings": "./index.d.ts",
"exports": {
".": {
"types": {
"require": "./index.d.cts",
"default": "./index.d.ts"
},
"bun": {
"require": "./dist/node/axios.cjs",
"default": "./index.js"
},
"react-native": {
"require": "./dist/browser/axios.cjs",
"default": "./dist/esm/axios.js"
},
"browser": {
"require": "./dist/browser/axios.cjs",
"default": "./index.js"
},
"default": {
"require": "./dist/node/axios.cjs",
"default": "./index.js"
}
},
"./lib/adapters/http.js": "./lib/adapters/http.js",
"./lib/adapters/xhr.js": "./lib/adapters/xhr.js",
"./unsafe/*": "./lib/*",
"./unsafe/core/settle.js": "./lib/core/settle.js",
"./unsafe/core/buildFullPath.js": "./lib/core/buildFullPath.js",
"./unsafe/helpers/isAbsoluteURL.js": "./lib/helpers/isAbsoluteURL.js",
"./unsafe/helpers/buildURL.js": "./lib/helpers/buildURL.js",
"./unsafe/helpers/combineURLs.js": "./lib/helpers/combineURLs.js",
"./unsafe/adapters/http.js": "./lib/adapters/http.js",
"./unsafe/adapters/xhr.js": "./lib/adapters/xhr.js",
"./unsafe/utils.js": "./lib/utils.js",
"./package.json": "./package.json",
"./dist/browser/axios.cjs": "./dist/browser/axios.cjs",
"./dist/node/axios.cjs": "./dist/node/axios.cjs"
},
"browser": {
"./dist/node/axios.cjs": "./dist/browser/axios.cjs",
"./lib/adapters/http.js": "./lib/helpers/null.js",
"./lib/platform/node/index.js": "./lib/platform/browser/index.js",
"./lib/platform/node/classes/FormData.js": "./lib/helpers/null.js"
},
"react-native": {
"./dist/node/axios.cjs": "./dist/browser/axios.cjs",
"./lib/adapters/http.js": "./lib/helpers/null.js",
"./lib/platform/node/index.js": "./lib/platform/browser/index.js",
"./lib/platform/node/classes/FormData.js": "./lib/helpers/null.js"
},
"repository": {
"type": "git",
"url": "https://github.com/axios/axios.git"
},
"keywords": [
"xhr",
"http",
"ajax",
"promise",
"node",
"browser",
"fetch",
"rest",
"api",
"client"
],
"author": "Matt Zabriskie",
"contributors": [
"Matt Zabriskie (https://github.com/mzabriskie)",
"Jay (https://github.com/jasonsaayman)",
"Dmitriy Mozgovoy (https://github.com/DigitalBrainJS)",
"Nick Uraltsev (https://github.com/nickuraltsev)",
"Emily Morehouse (https://github.com/emilyemorehouse)",
"Rubén Norte (https://github.com/rubennorte)",
"Justin Beckwith (https://github.com/JustinBeckwith)",
"Martti Laine (https://github.com/codeclown)",
"Xianming Zhong (https://github.com/chinesedfan)",
"Shaan Majid (https://github.com/shaanmajid)",
"Remco Haszing (https://github.com/remcohaszing)",
"Willian Agostini (https://github.com/WillianAgostini)",
"Rikki Gibson (https://github.com/RikkiGibson)"
],
"sideEffects": false,
"license": "MIT",
"bugs": {
"url": "https://github.com/axios/axios/issues"
},
"homepage": "https://axios-http.com",
"files": [
"index.js",
"index.d.ts",
"index.d.cts",
"CHANGELOG.md",
"MIGRATION_GUIDE.md",
"lib/",
"dist/axios.js",
"dist/axios.min.js",
"dist/axios.min.js.map",
"dist/esm/axios.js",
"dist/esm/axios.min.js",
"dist/esm/axios.min.js.map",
"dist/browser/axios.cjs",
"dist/node/axios.cjs"
],
"scripts": {
"build": "gulp clear && cross-env NODE_ENV=production rollup -c -m",
"version": "npm run build && git add package.json",
"preversion": "gulp version",
"test": "npm run test:vitest",
"test:vitest": "vitest run",
"test:vitest:unit": "vitest run --project unit",
"test:vitest:browser": "vitest run --project browser",
"test:vitest:browser:headless": "vitest run --project browser-headless",
"test:vitest:watch": "vitest",
"test:smoke:cjs:vitest": "npm --prefix tests/smoke/cjs run test:smoke:cjs:mocha",
"test:smoke:esm:vitest": "npm --prefix tests/smoke/esm run test:smoke:esm:vitest",
"test:smoke:deno": "deno task --cwd tests/smoke/deno test",
"test:smoke:bun": "bun test --cwd tests/smoke/bun",
"test:module:cjs": "npm --prefix tests/module/cjs run test:module:cjs",
"test:module:esm": "npm --prefix tests/module/esm run test:module:esm",
"docs:dev": "cd docs && npm run docs:dev",
"start": "node ./sandbox/server.js",
"examples": "node ./examples/server.js",
"lint": "eslint lib/**/*.js",
"fix": "eslint --fix lib/**/*.js",
"prepare": "husky"
},
"dependencies": {
"follow-redirects": "^1.16.0",
"form-data": "^4.0.5",
"https-proxy-agent": "^5.0.1",
"proxy-from-env": "^2.1.0"
},
"devDependencies": {
"@babel/core": "^7.29.0",
"@babel/preset-env": "^7.29.5",
"@commitlint/cli": "^21.0.1",
"@commitlint/config-conventional": "^21.0.1",
"@eslint/js": "^10.0.1",
"@rollup/plugin-alias": "^6.0.0",
"@rollup/plugin-babel": "^7.0.0",
"@rollup/plugin-commonjs": "^29.0.2",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^16.0.3",
"@rollup/plugin-terser": "^1.0.0",
"@vitest/browser": "^4.1.7",
"@vitest/browser-playwright": "^4.1.7",
"abortcontroller-polyfill": "^1.7.8",
"acorn": "^8.16.0",
"body-parser": "^2.2.2",
"chalk": "^5.6.2",
"cross-env": "^10.1.0",
"dev-null": "^0.1.1",
"eslint": "^10.4.0",
"express": "^5.2.1",
"formdata-node": "^6.0.3",
"formidable": "^3.5.4",
"fs-extra": "^11.3.4",
"get-stream": "^9.0.1",
"globals": "^17.6.0",
"gulp": "^5.0.1",
"husky": "^9.1.7",
"lint-staged": "^17.0.5",
"minimist": "^1.2.8",
"multer": "^2.1.1",
"playwright": "^1.60.0",
"prettier": "^3.8.3",
"rollup": "^4.60.4",
"rollup-plugin-bundle-size": "^1.0.3",
"selfsigned": "^5.5.0",
"stream-throttle": "^0.1.3",
"typescript": "^5.9.3",
"vitest": "^4.1.7"
},
"commitlint": {
"rules": {
"header-max-length": [
2,
"always",
130
]
},
"extends": [
"@commitlint/config-conventional"
]
},
"lint-staged": {
"*.{js,cjs,mjs,ts,json,md,yml,yaml}": "prettier --write"
}
}