UNPKG

@sp-api-sdk/common

Version:

Common library for the Amazon Selling Partner API (SP-API) SDK: Axios factory, regions, rate limiting and errors

184 lines (180 loc) 7.32 kB
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); //#region \0rolldown/runtime.js var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { key = keys[i]; if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: ((k) => from[k]).bind(null, key), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); //#endregion let axios = require("axios"); axios = __toESM(axios, 1); let axios_logger = require("axios-logger"); let axios_retry = require("axios-retry"); axios_retry = __toESM(axios_retry, 1); let _sp_api_sdk_auth = require("@sp-api-sdk/auth"); let node_url = require("node:url"); let read_pkg_up = require("read-pkg-up"); //#region src/regions.ts /** Endpoint mapping for each Selling Partner API region. */ const sellingPartnerRegions = { na: { endpoints: { production: "https://sellingpartnerapi-na.amazon.com", sandbox: "https://sandbox.sellingpartnerapi-na.amazon.com" } }, eu: { endpoints: { production: "https://sellingpartnerapi-eu.amazon.com", sandbox: "https://sandbox.sellingpartnerapi-eu.amazon.com" } }, fe: { endpoints: { production: "https://sellingpartnerapi-fe.amazon.com", sandbox: "https://sandbox.sellingpartnerapi-fe.amazon.com" } } }; //#endregion //#region src/errors.ts /** Error thrown when a Selling Partner API request fails. Wraps the underlying Axios error with a message that includes the API name, version, and HTTP status code (or "No response" for network errors). */ var SellingPartnerApiError = class extends axios.AxiosError { /** The original error message from the failed HTTP request. */ innerMessage; /** The API name extracted from the request URL path (e.g. `"orders"`). */ apiName; /** The API version extracted from the request URL path (e.g. `"v0"`). */ apiVersion; constructor(error) { super("Unknown error", error.code, error.config, error.request, error.response); this.innerMessage = error.message; if (error.config.url) { const [apiName, apiVersion] = new node_url.URL(error.config.url).pathname.split("/").slice(1); const apiPrefix = `${apiName} (${apiVersion})`; this.apiName = apiName; this.apiVersion = apiVersion; this.message = error.response ? `${apiPrefix} error: Response code ${error.response.status}` : `${apiPrefix} error: No response`; } this.name = this.constructor.name; } }; const packageJson = (0, read_pkg_up.sync)()?.packageJson ?? { _id: "", readme: "", name: "@sp-api-sdk/common", version: "unknown" }; //#endregion //#region src/axios.ts /** Creates a pre-configured Axios instance for a Selling Partner API client. The instance handles authentication, rate-limit retries, error wrapping, and optional request/response logging. @param configuration - Client configuration options. @param rateLimits - Per-endpoint rate limits used for retry delay calculation. @returns An object containing the configured Axios instance and the resolved API endpoint. */ function createAxiosInstance({ auth, restrictedDataToken, region, userAgent = `${packageJson.name}/${packageJson.version}`, sandbox = false, rateLimiting, logging }, rateLimits) { if (!Object.hasOwn(sellingPartnerRegions, region)) throw new TypeError(`Unknown or unsupported region: ${region}`); const regionConfiguration = sellingPartnerRegions[region]; const instance = axios.default.create({ headers: { "user-agent": userAgent } }); const endpoint = regionConfiguration.endpoints[sandbox ? "sandbox" : "production"]; if (rateLimiting?.retry) (0, axios_retry.default)(instance, { retryCondition: (error) => error.response?.status === 429, retryDelay(retryCount, error) { const url = new URL(error.config.url); const method = error.config.method?.toLowerCase(); const amznRateLimitHeader = error.response?.headers["x-amzn-ratelimit-limit"]; const amznRateLimit = amznRateLimitHeader ? Number(amznRateLimitHeader) : NaN; const rateLimit = Number.isNaN(amznRateLimit) ? rateLimits.find((rateLimit) => rateLimit.method.toLowerCase() === method && rateLimit.urlRegex.test(url.pathname))?.rate : amznRateLimit; const requestInterval = rateLimit !== void 0 && rateLimit > 0 ? 1e3 / rateLimit : void 0; const delay = requestInterval === void 0 ? 6e4 : requestInterval + 1500; if (rateLimiting.onRetry) rateLimiting.onRetry({ delay, rateLimit, retryCount, error }); return delay; } }); instance.interceptors.request.use(async (config) => { config.headers["x-amz-access-token"] = restrictedDataToken ?? await auth.getAccessToken(); return config; }); instance.interceptors.response.use(async (response) => response, async (error) => { if ((0, axios.isAxiosError)(error) && !(error instanceof _sp_api_sdk_auth.SellingPartnerApiAuthError)) throw new SellingPartnerApiError(error); throw error; }); if (logging?.request !== void 0) { const requestLoggerOptions = logging.request === true ? void 0 : logging.request; if (requestLoggerOptions?.headers) console.warn("WARNING: You have enabled logging of request headers, this can leak authentication information, you should disable in production."); instance.interceptors.request.use((config) => { return { ...(0, axios_logger.requestLogger)(config, { prefixText: `sp-api-sdk/${region}`, dateFormat: "isoDateTime", method: true, url: true, params: false, data: true, headers: false, logger: console.info, ...requestLoggerOptions }), headers: config.headers }; }); } if (logging?.response !== void 0) { const responseLoggerOptions = logging.response === true ? void 0 : logging.response; instance.interceptors.response.use((response) => (0, axios_logger.responseLogger)(response, { prefixText: `sp-api-sdk/${region}`, dateFormat: "isoDateTime", status: true, statusText: false, params: false, data: false, headers: true, logger: console.info, ...responseLoggerOptions })); } if (logging?.error !== void 0) { const errorLoggerOptions = logging.error === true ? void 0 : logging.error; instance.interceptors.response.use((response) => response, async (error) => (0, axios_logger.errorLogger)(error, { prefixText: `sp-api-sdk/${region}`, dateFormat: "isoDateTime", status: true, statusText: false, params: false, data: false, headers: true, logger: console.error, ...errorLoggerOptions })); } return { axios: instance, endpoint }; } //#endregion exports.SellingPartnerApiError = SellingPartnerApiError; exports.createAxiosInstance = createAxiosInstance; exports.sellingPartnerRegions = sellingPartnerRegions; //# sourceMappingURL=index.cjs.map