@sp-api-sdk/common
Advanced tools
+223
| "use strict"; | ||
| 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 __export = (target, all) => { | ||
| for (var name in all) | ||
| __defProp(target, name, { get: all[name], enumerable: true }); | ||
| }; | ||
| var __copyProps = (to, from, except, desc) => { | ||
| if (from && typeof from === "object" || typeof from === "function") { | ||
| for (let key of __getOwnPropNames(from)) | ||
| if (!__hasOwnProp.call(to, key) && key !== except) | ||
| __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
| } | ||
| return to; | ||
| }; | ||
| var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( | ||
| // If the importer is in node compatibility mode or this is not an ESM | ||
| // file that has been converted to a CommonJS file using a Babel- | ||
| // compatible transform (i.e. "__esModule" has not been set), then set | ||
| // "default" to the CommonJS "module.exports" for node compatibility. | ||
| isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, | ||
| mod | ||
| )); | ||
| var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
| // src/index.ts | ||
| var index_exports = {}; | ||
| __export(index_exports, { | ||
| SellingPartnerApiError: () => SellingPartnerApiError, | ||
| createAxiosInstance: () => createAxiosInstance, | ||
| sellingPartnerRegions: () => sellingPartnerRegions | ||
| }); | ||
| module.exports = __toCommonJS(index_exports); | ||
| // src/regions.ts | ||
| var sellingPartnerRegions = { | ||
| na: { | ||
| awsRegion: "us-east-1", | ||
| endpoints: { | ||
| production: "https://sellingpartnerapi-na.amazon.com", | ||
| sandbox: "https://sandbox.sellingpartnerapi-na.amazon.com" | ||
| } | ||
| }, | ||
| eu: { | ||
| awsRegion: "eu-west-1", | ||
| endpoints: { | ||
| production: "https://sellingpartnerapi-eu.amazon.com", | ||
| sandbox: "https://sandbox.sellingpartnerapi-eu.amazon.com" | ||
| } | ||
| }, | ||
| fe: { | ||
| awsRegion: "us-west-2", | ||
| endpoints: { | ||
| production: "https://sellingpartnerapi-fe.amazon.com", | ||
| sandbox: "https://sandbox.sellingpartnerapi-fe.amazon.com" | ||
| } | ||
| } | ||
| }; | ||
| // src/axios.ts | ||
| var import_axios2 = __toESM(require("axios"), 1); | ||
| var import_axios_logger = require("axios-logger"); | ||
| var import_axios_retry = __toESM(require("axios-retry"), 1); | ||
| var import_auth = require("@sp-api-sdk/auth"); | ||
| // src/errors.ts | ||
| var import_node_url = require("url"); | ||
| var import_axios = require("axios"); | ||
| var SellingPartnerApiError = class extends import_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 import_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; | ||
| } | ||
| }; | ||
| // src/utils/package.ts | ||
| var import_read_pkg_up = require("read-pkg-up"); | ||
| var result = (0, import_read_pkg_up.sync)(); | ||
| var packageJson = result?.packageJson ?? { | ||
| _id: "", | ||
| readme: "", | ||
| name: "@sp-api-sdk/common", | ||
| version: "unknown" | ||
| }; | ||
| // src/axios.ts | ||
| function createAxiosInstance({ | ||
| auth, | ||
| restrictedDataToken, | ||
| region, | ||
| userAgent = `${packageJson.name}/${packageJson.version}`, | ||
| sandbox = false, | ||
| rateLimiting, | ||
| logging | ||
| }, rateLimits) { | ||
| const regionConfiguration = sellingPartnerRegions[region]; | ||
| if (!regionConfiguration) { | ||
| throw new TypeError(`Unknown or unsupported region: ${region}`); | ||
| } | ||
| const instance = import_axios2.default.create({ | ||
| headers: { | ||
| "user-agent": userAgent | ||
| } | ||
| }); | ||
| const endpoint = regionConfiguration.endpoints[sandbox ? "sandbox" : "production"]; | ||
| if (rateLimiting?.retry) { | ||
| (0, import_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 amznRateLimit = Number.parseFloat( | ||
| error.response?.headers["x-amzn-ratelimit-limit"] ?? "" | ||
| ); | ||
| const rateLimit = Number.isNaN(amznRateLimit) ? rateLimits.find( | ||
| (rateLimit2) => rateLimit2.method.toLowerCase() === method && rateLimit2.urlRegex.exec(url.pathname) | ||
| )?.rate : amznRateLimit; | ||
| const delay = rateLimit ? 1 / rateLimit * 1e3 + 1500 : 60 * 1e3; | ||
| 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, import_axios2.isAxiosError)(error) && !(error instanceof import_auth.SellingPartnerApiAuthError)) { | ||
| throw new SellingPartnerApiError(error); | ||
| } | ||
| throw error; | ||
| } | ||
| ); | ||
| if (logging?.request) { | ||
| 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) => { | ||
| const logger = (0, import_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 | ||
| }); | ||
| return { | ||
| ...logger, | ||
| headers: config.headers | ||
| }; | ||
| }); | ||
| } | ||
| if (logging?.response) { | ||
| const responseLoggerOptions = logging.response === true ? void 0 : logging.response; | ||
| instance.interceptors.response.use( | ||
| (response) => (0, import_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) { | ||
| const errorLoggerOptions = logging.error === true ? void 0 : logging.error; | ||
| instance.interceptors.response.use( | ||
| (response) => response, | ||
| async (error) => (0, import_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 }; | ||
| } | ||
| // Annotate the CommonJS export names for ESM import in node: | ||
| 0 && (module.exports = { | ||
| SellingPartnerApiError, | ||
| createAxiosInstance, | ||
| sellingPartnerRegions | ||
| }); | ||
| //# sourceMappingURL=index.cjs.map |
| {"version":3,"sources":["../src/index.ts","../src/regions.ts","../src/axios.ts","../src/errors.ts","../src/utils/package.ts"],"sourcesContent":["export * from './regions.js'\nexport * from './axios.js'\nexport * from './errors.js'\n","/** Selling Partner API region identifier. */\nexport type SellingPartnerRegion = 'na' | 'eu' | 'fe'\n\ninterface RegionConfiguration {\n awsRegion: string\n endpoints: {\n production: string\n sandbox: string\n }\n}\n\n/** AWS region and endpoint mapping for each Selling Partner API region. */\nexport const sellingPartnerRegions: Record<SellingPartnerRegion, RegionConfiguration> = {\n na: {\n awsRegion: 'us-east-1',\n endpoints: {\n production: 'https://sellingpartnerapi-na.amazon.com',\n sandbox: 'https://sandbox.sellingpartnerapi-na.amazon.com',\n },\n },\n eu: {\n awsRegion: 'eu-west-1',\n endpoints: {\n production: 'https://sellingpartnerapi-eu.amazon.com',\n sandbox: 'https://sandbox.sellingpartnerapi-eu.amazon.com',\n },\n },\n fe: {\n awsRegion: 'us-west-2',\n endpoints: {\n production: 'https://sellingpartnerapi-fe.amazon.com',\n sandbox: 'https://sandbox.sellingpartnerapi-fe.amazon.com',\n },\n },\n}\n","import axios, {type AxiosError, isAxiosError, type Method} from 'axios'\nimport {errorLogger, requestLogger, responseLogger} from 'axios-logger'\nimport axiosRetry from 'axios-retry'\n\nimport {type SellingPartnerApiAuth, SellingPartnerApiAuthError} from '@sp-api-sdk/auth'\n\nimport {SellingPartnerApiError} from './errors.js'\nimport {type SellingPartnerRegion, sellingPartnerRegions} from './regions.js'\nimport {packageJson} from './utils/package.js'\n\ntype RequestLogConfig = Exclude<Parameters<typeof requestLogger>[1], undefined>\ntype ResponseLogConfig = Exclude<Parameters<typeof responseLogger>[1], undefined>\ntype ErrorLogConfig = Exclude<Parameters<typeof errorLogger>[1], undefined>\n\n/** Per-endpoint rate limit definition used for retry delay calculation. */\nexport interface RateLimit {\n /** Regular expression matched against the request URL pathname. */\n urlRegex: RegExp\n /** Sustained request rate in requests per second. */\n rate: number\n /** Maximum burst size (number of requests allowed before throttling). */\n burst: number\n /** HTTP method this rate limit applies to. */\n method: Method\n}\n\n/** Parameters passed to the {@link ClientConfiguration.rateLimiting} `onRetry` callback. */\nexport interface OnRetryParameters {\n /** Delay in milliseconds before the next retry attempt. */\n delay: number\n /** Rate limit (requests per second) used to calculate the delay, if available. */\n rateLimit?: number\n /** Number of retry attempts so far. */\n retryCount: number\n /** The Axios error that triggered the retry. */\n error: AxiosError\n}\n\n/** Configuration options for creating a Selling Partner API Axios instance. */\nexport interface ClientConfiguration {\n /** Authentication handler that provides LWA access tokens. */\n auth: SellingPartnerApiAuth\n /** Restricted Data Token to use instead of the standard access token. */\n restrictedDataToken?: string\n /** Selling Partner API region to send requests to. */\n region: SellingPartnerRegion\n /** Custom `User-Agent` header value. */\n userAgent?: string\n /** When `true`, requests are sent to the sandbox endpoint. Defaults to `false`. */\n sandbox?: boolean\n /** Rate-limiting and retry configuration for 429 responses. */\n rateLimiting?: {\n /** When `true`, automatically retries throttled (HTTP 429) requests. */\n retry: boolean\n /** Optional callback invoked before each retry attempt. */\n onRetry?: (retryInfo: OnRetryParameters) => void\n }\n /** Axios request/response/error logging configuration. Pass `true` to use defaults. */\n logging?: {\n /** Log outgoing requests. */\n request?: RequestLogConfig | true\n /** Log incoming responses. */\n response?: ResponseLogConfig | true\n /** Log request errors. */\n error?: ErrorLogConfig | true\n }\n}\n\n/**\n * Creates a pre-configured Axios instance for a Selling Partner API client.\n *\n * The instance handles authentication, rate-limit retries, error wrapping,\n * and optional request/response logging.\n *\n * @param configuration - Client configuration options.\n * @param rateLimits - Per-endpoint rate limits used for retry delay calculation.\n * @returns An object containing the configured Axios instance and the resolved API endpoint.\n */\nexport function createAxiosInstance(\n {\n auth,\n restrictedDataToken,\n region,\n userAgent = `${packageJson.name}/${packageJson.version}`,\n sandbox = false,\n rateLimiting,\n logging,\n }: ClientConfiguration,\n rateLimits: RateLimit[],\n) {\n const regionConfiguration = sellingPartnerRegions[region]\n if (!regionConfiguration) {\n throw new TypeError(`Unknown or unsupported region: ${region}`)\n }\n\n const instance = axios.create({\n headers: {\n 'user-agent': userAgent,\n },\n })\n\n const endpoint = regionConfiguration.endpoints[sandbox ? 'sandbox' : 'production']\n\n if (rateLimiting?.retry) {\n axiosRetry(instance, {\n retryCondition: (error) => error.response?.status === 429,\n retryDelay(retryCount, error) {\n const url = new URL(error.config!.url!)\n const method = error.config!.method?.toLowerCase()\n const amznRateLimit = Number.parseFloat(\n error.response?.headers['x-amzn-ratelimit-limit'] ?? '',\n )\n\n const rateLimit = Number.isNaN(amznRateLimit)\n ? rateLimits.find(\n (rateLimit) =>\n rateLimit.method.toLowerCase() === method && rateLimit.urlRegex.exec(url.pathname),\n )?.rate\n : amznRateLimit\n\n const delay = rateLimit ? (1 / rateLimit) * 1000 + 1500 : 60 * 1000\n\n if (rateLimiting.onRetry) {\n rateLimiting.onRetry({delay, rateLimit, retryCount, error})\n }\n\n return delay\n },\n })\n }\n\n // Set x-amz-access-token to each request\n instance.interceptors.request.use(async (config) => {\n config.headers['x-amz-access-token'] = restrictedDataToken ?? (await auth.getAccessToken())\n\n return config\n })\n\n instance.interceptors.response.use(\n async (response) => response,\n async (error: unknown) => {\n if (isAxiosError(error) && !(error instanceof SellingPartnerApiAuthError)) {\n throw new SellingPartnerApiError(error)\n }\n\n throw error\n },\n )\n\n if (logging?.request) {\n const requestLoggerOptions = logging.request === true ? undefined : logging.request\n\n if (requestLoggerOptions?.headers) {\n console.warn(\n 'WARNING: You have enabled logging of request headers, this can leak authentication information, you should disable in production.',\n )\n }\n\n instance.interceptors.request.use((config) => {\n const logger = requestLogger(config, {\n prefixText: `sp-api-sdk/${region}`,\n dateFormat: 'isoDateTime',\n method: true,\n url: true,\n params: false,\n data: true,\n headers: false,\n logger: console.info,\n ...requestLoggerOptions,\n })\n\n return {\n ...logger,\n headers: config.headers,\n }\n })\n }\n\n if (logging?.response) {\n const responseLoggerOptions = logging.response === true ? undefined : logging.response\n\n instance.interceptors.response.use((response) =>\n responseLogger(response, {\n prefixText: `sp-api-sdk/${region}`,\n dateFormat: 'isoDateTime',\n status: true,\n statusText: false,\n params: false,\n data: false,\n headers: true,\n logger: console.info,\n ...responseLoggerOptions,\n }),\n )\n }\n\n if (logging?.error) {\n const errorLoggerOptions = logging.error === true ? undefined : logging.error\n\n instance.interceptors.response.use(\n (response) => response,\n async (error) =>\n errorLogger(error, {\n prefixText: `sp-api-sdk/${region}`,\n dateFormat: 'isoDateTime',\n status: true,\n statusText: false,\n params: false,\n data: false,\n headers: true,\n logger: console.error,\n ...errorLoggerOptions,\n }),\n )\n }\n\n return {axios: instance, endpoint}\n}\n","import {URL} from 'node:url'\n\nimport {AxiosError} from 'axios'\n\n/**\n * Error thrown when a Selling Partner API request fails.\n *\n * Wraps the underlying Axios error with a message that includes the API name,\n * version, and HTTP status code (or \"No response\" for network errors).\n */\nexport class SellingPartnerApiError<T = unknown, D = any> extends AxiosError<T, D> {\n /** The original error message from the failed HTTP request. */\n public readonly innerMessage: string\n /** The API name extracted from the request URL path (e.g. `\"orders\"`). */\n public readonly apiName?: string\n /** The API version extracted from the request URL path (e.g. `\"v0\"`). */\n public readonly apiVersion?: string\n\n constructor(error: AxiosError<T, D>) {\n super('Unknown error', error.code, error.config, error.request, error.response)\n\n this.innerMessage = error.message\n\n if (error.config!.url) {\n const [apiName, apiVersion] = new URL(error.config!.url).pathname.split('/').slice(1)\n const apiPrefix = `${apiName} (${apiVersion})`\n\n this.apiName = apiName\n this.apiVersion = apiVersion\n this.message = error.response\n ? `${apiPrefix} error: Response code ${error.response.status}`\n : `${apiPrefix} error: No response`\n }\n\n this.name = this.constructor.name\n }\n}\n","import {type NormalizedPackageJson, sync as readPackageJson} from 'read-pkg-up'\n\nconst result = readPackageJson()\n\nexport const packageJson: NormalizedPackageJson = result?.packageJson ?? {\n _id: '',\n readme: '',\n name: '@sp-api-sdk/common',\n version: 'unknown',\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYO,IAAM,wBAA2E;AAAA,EACtF,IAAI;AAAA,IACF,WAAW;AAAA,IACX,WAAW;AAAA,MACT,YAAY;AAAA,MACZ,SAAS;AAAA,IACX;AAAA,EACF;AAAA,EACA,IAAI;AAAA,I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AA,MACL,CAAC;AAAA,IACL;AAAA,EACF;AAEA,SAAO,EAAC,OAAO,UAAU,SAAQ;AACnC;","names":["import_axios","readPackageJson","axios","axiosRetry","rateLimit"]} |
+103
| import * as axios from 'axios'; | ||
| import { AxiosError, Method } from 'axios'; | ||
| import { requestLogger, responseLogger, errorLogger } from 'axios-logger'; | ||
| import { SellingPartnerApiAuth } from '@sp-api-sdk/auth'; | ||
| /** Selling Partner API region identifier. */ | ||
| type SellingPartnerRegion = 'na' | 'eu' | 'fe'; | ||
| interface RegionConfiguration { | ||
| awsRegion: string; | ||
| endpoints: { | ||
| production: string; | ||
| sandbox: string; | ||
| }; | ||
| } | ||
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| declare const sellingPartnerRegions: Record<SellingPartnerRegion, RegionConfiguration>; | ||
| type RequestLogConfig = Exclude<Parameters<typeof requestLogger>[1], undefined>; | ||
| type ResponseLogConfig = Exclude<Parameters<typeof responseLogger>[1], undefined>; | ||
| type ErrorLogConfig = Exclude<Parameters<typeof errorLogger>[1], undefined>; | ||
| /** Per-endpoint rate limit definition used for retry delay calculation. */ | ||
| interface RateLimit { | ||
| /** Regular expression matched against the request URL pathname. */ | ||
| urlRegex: RegExp; | ||
| /** Sustained request rate in requests per second. */ | ||
| rate: number; | ||
| /** Maximum burst size (number of requests allowed before throttling). */ | ||
| burst: number; | ||
| /** HTTP method this rate limit applies to. */ | ||
| method: Method; | ||
| } | ||
| /** Parameters passed to the {@link ClientConfiguration.rateLimiting} `onRetry` callback. */ | ||
| interface OnRetryParameters { | ||
| /** Delay in milliseconds before the next retry attempt. */ | ||
| delay: number; | ||
| /** Rate limit (requests per second) used to calculate the delay, if available. */ | ||
| rateLimit?: number; | ||
| /** Number of retry attempts so far. */ | ||
| retryCount: number; | ||
| /** The Axios error that triggered the retry. */ | ||
| error: AxiosError; | ||
| } | ||
| /** Configuration options for creating a Selling Partner API Axios instance. */ | ||
| interface ClientConfiguration { | ||
| /** Authentication handler that provides LWA access tokens. */ | ||
| auth: SellingPartnerApiAuth; | ||
| /** Restricted Data Token to use instead of the standard access token. */ | ||
| restrictedDataToken?: string; | ||
| /** Selling Partner API region to send requests to. */ | ||
| region: SellingPartnerRegion; | ||
| /** Custom `User-Agent` header value. */ | ||
| userAgent?: string; | ||
| /** When `true`, requests are sent to the sandbox endpoint. Defaults to `false`. */ | ||
| sandbox?: boolean; | ||
| /** Rate-limiting and retry configuration for 429 responses. */ | ||
| rateLimiting?: { | ||
| /** When `true`, automatically retries throttled (HTTP 429) requests. */ | ||
| retry: boolean; | ||
| /** Optional callback invoked before each retry attempt. */ | ||
| onRetry?: (retryInfo: OnRetryParameters) => void; | ||
| }; | ||
| /** Axios request/response/error logging configuration. Pass `true` to use defaults. */ | ||
| logging?: { | ||
| /** Log outgoing requests. */ | ||
| request?: RequestLogConfig | true; | ||
| /** Log incoming responses. */ | ||
| response?: ResponseLogConfig | true; | ||
| /** Log request errors. */ | ||
| error?: ErrorLogConfig | true; | ||
| }; | ||
| } | ||
| /** | ||
| * 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. | ||
| */ | ||
| declare function createAxiosInstance({ auth, restrictedDataToken, region, userAgent, sandbox, rateLimiting, logging, }: ClientConfiguration, rateLimits: RateLimit[]): { | ||
| axios: axios.AxiosInstance; | ||
| endpoint: string; | ||
| }; | ||
| /** | ||
| * 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). | ||
| */ | ||
| declare class SellingPartnerApiError<T = unknown, D = any> extends AxiosError<T, D> { | ||
| /** The original error message from the failed HTTP request. */ | ||
| readonly innerMessage: string; | ||
| /** The API name extracted from the request URL path (e.g. `"orders"`). */ | ||
| readonly apiName?: string; | ||
| /** The API version extracted from the request URL path (e.g. `"v0"`). */ | ||
| readonly apiVersion?: string; | ||
| constructor(error: AxiosError<T, D>); | ||
| } | ||
| export { type ClientConfiguration, type OnRetryParameters, type RateLimit, SellingPartnerApiError, type SellingPartnerRegion, createAxiosInstance, sellingPartnerRegions }; |
+103
| import * as axios from 'axios'; | ||
| import { AxiosError, Method } from 'axios'; | ||
| import { requestLogger, responseLogger, errorLogger } from 'axios-logger'; | ||
| import { SellingPartnerApiAuth } from '@sp-api-sdk/auth'; | ||
| /** Selling Partner API region identifier. */ | ||
| type SellingPartnerRegion = 'na' | 'eu' | 'fe'; | ||
| interface RegionConfiguration { | ||
| awsRegion: string; | ||
| endpoints: { | ||
| production: string; | ||
| sandbox: string; | ||
| }; | ||
| } | ||
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| declare const sellingPartnerRegions: Record<SellingPartnerRegion, RegionConfiguration>; | ||
| type RequestLogConfig = Exclude<Parameters<typeof requestLogger>[1], undefined>; | ||
| type ResponseLogConfig = Exclude<Parameters<typeof responseLogger>[1], undefined>; | ||
| type ErrorLogConfig = Exclude<Parameters<typeof errorLogger>[1], undefined>; | ||
| /** Per-endpoint rate limit definition used for retry delay calculation. */ | ||
| interface RateLimit { | ||
| /** Regular expression matched against the request URL pathname. */ | ||
| urlRegex: RegExp; | ||
| /** Sustained request rate in requests per second. */ | ||
| rate: number; | ||
| /** Maximum burst size (number of requests allowed before throttling). */ | ||
| burst: number; | ||
| /** HTTP method this rate limit applies to. */ | ||
| method: Method; | ||
| } | ||
| /** Parameters passed to the {@link ClientConfiguration.rateLimiting} `onRetry` callback. */ | ||
| interface OnRetryParameters { | ||
| /** Delay in milliseconds before the next retry attempt. */ | ||
| delay: number; | ||
| /** Rate limit (requests per second) used to calculate the delay, if available. */ | ||
| rateLimit?: number; | ||
| /** Number of retry attempts so far. */ | ||
| retryCount: number; | ||
| /** The Axios error that triggered the retry. */ | ||
| error: AxiosError; | ||
| } | ||
| /** Configuration options for creating a Selling Partner API Axios instance. */ | ||
| interface ClientConfiguration { | ||
| /** Authentication handler that provides LWA access tokens. */ | ||
| auth: SellingPartnerApiAuth; | ||
| /** Restricted Data Token to use instead of the standard access token. */ | ||
| restrictedDataToken?: string; | ||
| /** Selling Partner API region to send requests to. */ | ||
| region: SellingPartnerRegion; | ||
| /** Custom `User-Agent` header value. */ | ||
| userAgent?: string; | ||
| /** When `true`, requests are sent to the sandbox endpoint. Defaults to `false`. */ | ||
| sandbox?: boolean; | ||
| /** Rate-limiting and retry configuration for 429 responses. */ | ||
| rateLimiting?: { | ||
| /** When `true`, automatically retries throttled (HTTP 429) requests. */ | ||
| retry: boolean; | ||
| /** Optional callback invoked before each retry attempt. */ | ||
| onRetry?: (retryInfo: OnRetryParameters) => void; | ||
| }; | ||
| /** Axios request/response/error logging configuration. Pass `true` to use defaults. */ | ||
| logging?: { | ||
| /** Log outgoing requests. */ | ||
| request?: RequestLogConfig | true; | ||
| /** Log incoming responses. */ | ||
| response?: ResponseLogConfig | true; | ||
| /** Log request errors. */ | ||
| error?: ErrorLogConfig | true; | ||
| }; | ||
| } | ||
| /** | ||
| * 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. | ||
| */ | ||
| declare function createAxiosInstance({ auth, restrictedDataToken, region, userAgent, sandbox, rateLimiting, logging, }: ClientConfiguration, rateLimits: RateLimit[]): { | ||
| axios: axios.AxiosInstance; | ||
| endpoint: string; | ||
| }; | ||
| /** | ||
| * 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). | ||
| */ | ||
| declare class SellingPartnerApiError<T = unknown, D = any> extends AxiosError<T, D> { | ||
| /** The original error message from the failed HTTP request. */ | ||
| readonly innerMessage: string; | ||
| /** The API name extracted from the request URL path (e.g. `"orders"`). */ | ||
| readonly apiName?: string; | ||
| /** The API version extracted from the request URL path (e.g. `"v0"`). */ | ||
| readonly apiVersion?: string; | ||
| constructor(error: AxiosError<T, D>); | ||
| } | ||
| export { type ClientConfiguration, type OnRetryParameters, type RateLimit, SellingPartnerApiError, type SellingPartnerRegion, createAxiosInstance, sellingPartnerRegions }; |
+184
| // src/regions.ts | ||
| var sellingPartnerRegions = { | ||
| na: { | ||
| awsRegion: "us-east-1", | ||
| endpoints: { | ||
| production: "https://sellingpartnerapi-na.amazon.com", | ||
| sandbox: "https://sandbox.sellingpartnerapi-na.amazon.com" | ||
| } | ||
| }, | ||
| eu: { | ||
| awsRegion: "eu-west-1", | ||
| endpoints: { | ||
| production: "https://sellingpartnerapi-eu.amazon.com", | ||
| sandbox: "https://sandbox.sellingpartnerapi-eu.amazon.com" | ||
| } | ||
| }, | ||
| fe: { | ||
| awsRegion: "us-west-2", | ||
| endpoints: { | ||
| production: "https://sellingpartnerapi-fe.amazon.com", | ||
| sandbox: "https://sandbox.sellingpartnerapi-fe.amazon.com" | ||
| } | ||
| } | ||
| }; | ||
| // src/axios.ts | ||
| import axios, { isAxiosError } from "axios"; | ||
| import { errorLogger, requestLogger, responseLogger } from "axios-logger"; | ||
| import axiosRetry from "axios-retry"; | ||
| import { SellingPartnerApiAuthError } from "@sp-api-sdk/auth"; | ||
| // src/errors.ts | ||
| import { URL as URL2 } from "url"; | ||
| import { AxiosError } from "axios"; | ||
| var SellingPartnerApiError = class extends 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 URL2(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; | ||
| } | ||
| }; | ||
| // src/utils/package.ts | ||
| import { sync as readPackageJson } from "read-pkg-up"; | ||
| var result = readPackageJson(); | ||
| var packageJson = result?.packageJson ?? { | ||
| _id: "", | ||
| readme: "", | ||
| name: "@sp-api-sdk/common", | ||
| version: "unknown" | ||
| }; | ||
| // src/axios.ts | ||
| function createAxiosInstance({ | ||
| auth, | ||
| restrictedDataToken, | ||
| region, | ||
| userAgent = `${packageJson.name}/${packageJson.version}`, | ||
| sandbox = false, | ||
| rateLimiting, | ||
| logging | ||
| }, rateLimits) { | ||
| const regionConfiguration = sellingPartnerRegions[region]; | ||
| if (!regionConfiguration) { | ||
| throw new TypeError(`Unknown or unsupported region: ${region}`); | ||
| } | ||
| const instance = axios.create({ | ||
| headers: { | ||
| "user-agent": userAgent | ||
| } | ||
| }); | ||
| const endpoint = regionConfiguration.endpoints[sandbox ? "sandbox" : "production"]; | ||
| if (rateLimiting?.retry) { | ||
| axiosRetry(instance, { | ||
| retryCondition: (error) => error.response?.status === 429, | ||
| retryDelay(retryCount, error) { | ||
| const url = new URL(error.config.url); | ||
| const method = error.config.method?.toLowerCase(); | ||
| const amznRateLimit = Number.parseFloat( | ||
| error.response?.headers["x-amzn-ratelimit-limit"] ?? "" | ||
| ); | ||
| const rateLimit = Number.isNaN(amznRateLimit) ? rateLimits.find( | ||
| (rateLimit2) => rateLimit2.method.toLowerCase() === method && rateLimit2.urlRegex.exec(url.pathname) | ||
| )?.rate : amznRateLimit; | ||
| const delay = rateLimit ? 1 / rateLimit * 1e3 + 1500 : 60 * 1e3; | ||
| 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 (isAxiosError(error) && !(error instanceof SellingPartnerApiAuthError)) { | ||
| throw new SellingPartnerApiError(error); | ||
| } | ||
| throw error; | ||
| } | ||
| ); | ||
| if (logging?.request) { | ||
| 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) => { | ||
| const logger = requestLogger(config, { | ||
| prefixText: `sp-api-sdk/${region}`, | ||
| dateFormat: "isoDateTime", | ||
| method: true, | ||
| url: true, | ||
| params: false, | ||
| data: true, | ||
| headers: false, | ||
| logger: console.info, | ||
| ...requestLoggerOptions | ||
| }); | ||
| return { | ||
| ...logger, | ||
| headers: config.headers | ||
| }; | ||
| }); | ||
| } | ||
| if (logging?.response) { | ||
| const responseLoggerOptions = logging.response === true ? void 0 : logging.response; | ||
| instance.interceptors.response.use( | ||
| (response) => 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) { | ||
| const errorLoggerOptions = logging.error === true ? void 0 : logging.error; | ||
| instance.interceptors.response.use( | ||
| (response) => response, | ||
| async (error) => 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 }; | ||
| } | ||
| export { | ||
| SellingPartnerApiError, | ||
| createAxiosInstance, | ||
| sellingPartnerRegions | ||
| }; | ||
| //# sourceMappingURL=index.js.map |
| {"version":3,"sources":["../src/regions.ts","../src/axios.ts","../src/errors.ts","../src/utils/package.ts"],"sourcesContent":["/** Selling Partner API region identifier. */\nexport type SellingPartnerRegion = 'na' | 'eu' | 'fe'\n\ninterface RegionConfiguration {\n awsRegion: string\n endpoints: {\n production: string\n sandbox: string\n }\n}\n\n/** AWS region and endpoint mapping for each Selling Partner API region. */\nexport const sellingPartnerRegions: Record<SellingPartnerRegion, RegionConfiguration> = {\n na: {\n awsRegion: 'us-east-1',\n endpoints: {\n production: 'https://sellingpartnerapi-na.amazon.com',\n sandbox: 'https://sandbox.sellingpartnerapi-na.amazon.com',\n },\n },\n eu: {\n awsRegion: 'eu-west-1',\n endpoints: {\n production: 'https://sellingpartnerapi-eu.amazon.com',\n sandbox: 'https://sandbox.sellingpartnerapi-eu.amazon.com',\n },\n },\n fe: {\n awsRegion: 'us-west-2',\n endpoints: {\n production: 'https://sellingpartnerapi-fe.amazon.com',\n sandbox: 'https://sandbox.sellingpartnerapi-fe.amazon.com',\n },\n },\n}\n","import axios, {type AxiosError, isAxiosError, type Method} from 'axios'\nimport {errorLogger, requestLogger, responseLogger} from 'axios-logger'\nimport axiosRetry from 'axios-retry'\n\nimport {type SellingPartnerApiAuth, SellingPartnerApiAuthError} from '@sp-api-sdk/auth'\n\nimport {SellingPartnerApiError} from './errors.js'\nimport {type SellingPartnerRegion, sellingPartnerRegions} from './regions.js'\nimport {packageJson} from './utils/package.js'\n\ntype RequestLogConfig = Exclude<Parameters<typeof requestLogger>[1], undefined>\ntype ResponseLogConfig = Exclude<Parameters<typeof responseLogger>[1], undefined>\ntype ErrorLogConfig = Exclude<Parameters<typeof errorLogger>[1], undefined>\n\n/** Per-endpoint rate limit definition used for retry delay calculation. */\nexport interface RateLimit {\n /** Regular expression matched against the request URL pathname. */\n urlRegex: RegExp\n /** Sustained request rate in requests per second. */\n rate: number\n /** Maximum burst size (number of requests allowed before throttling). */\n burst: number\n /** HTTP method this rate limit applies to. */\n method: Method\n}\n\n/** Parameters passed to the {@link ClientConfiguration.rateLimiting} `onRetry` callback. */\nexport interface OnRetryParameters {\n /** Delay in milliseconds before the next retry attempt. */\n delay: number\n /** Rate limit (requests per second) used to calculate the delay, if available. */\n rateLimit?: number\n /** Number of retry attempts so far. */\n retryCount: number\n /** The Axios error that triggered the retry. */\n error: AxiosError\n}\n\n/** Configuration options for creating a Selling Partner API Axios instance. */\nexport interface ClientConfiguration {\n /** Authentication handler that provides LWA access tokens. */\n auth: SellingPartnerApiAuth\n /** Restricted Data Token to use instead of the standard access token. */\n restrictedDataToken?: string\n /** Selling Partner API region to send requests to. */\n region: SellingPartnerRegion\n /** Custom `User-Agent` header value. */\n userAgent?: string\n /** When `true`, requests are sent to the sandbox endpoint. Defaults to `false`. */\n sandbox?: boolean\n /** Rate-limiting and retry configuration for 429 responses. */\n rateLimiting?: {\n /** When `true`, automatically retries throttled (HTTP 429) requests. */\n retry: boolean\n /** Optional callback invoked before each retry attempt. */\n onRetry?: (retryInfo: OnRetryParameters) => void\n }\n /** Axios request/response/error logging configuration. Pass `true` to use defaults. */\n logging?: {\n /** Log outgoing requests. */\n request?: RequestLogConfig | true\n /** Log incoming responses. */\n response?: ResponseLogConfig | true\n /** Log request errors. */\n error?: ErrorLogConfig | true\n }\n}\n\n/**\n * Creates a pre-configured Axios instance for a Selling Partner API client.\n *\n * The instance handles authentication, rate-limit retries, error wrapping,\n * and optional request/response logging.\n *\n * @param configuration - Client configuration options.\n * @param rateLimits - Per-endpoint rate limits used for retry delay calculation.\n * @returns An object containing the configured Axios instance and the resolved API endpoint.\n */\nexport function createAxiosInstance(\n {\n auth,\n restrictedDataToken,\n region,\n userAgent = `${packageJson.name}/${packageJson.version}`,\n sandbox = false,\n rateLimiting,\n logging,\n }: ClientConfiguration,\n rateLimits: RateLimit[],\n) {\n const regionConfiguration = sellingPartnerRegions[region]\n if (!regionConfiguration) {\n throw new TypeError(`Unknown or unsupported region: ${region}`)\n }\n\n const instance = axios.create({\n headers: {\n 'user-agent': userAgent,\n },\n })\n\n const endpoint = regionConfiguration.endpoints[sandbox ? 'sandbox' : 'production']\n\n if (rateLimiting?.retry) {\n axiosRetry(instance, {\n retryCondition: (error) => error.response?.status === 429,\n retryDelay(retryCount, error) {\n const url = new URL(error.config!.url!)\n const method = error.config!.method?.toLowerCase()\n const amznRateLimit = Number.parseFloat(\n error.response?.headers['x-amzn-ratelimit-limit'] ?? '',\n )\n\n const rateLimit = Number.isNaN(amznRateLimit)\n ? rateLimits.find(\n (rateLimit) =>\n rateLimit.method.toLowerCase() === method && rateLimit.urlRegex.exec(url.pathname),\n )?.rate\n : amznRateLimit\n\n const delay = rateLimit ? (1 / rateLimit) * 1000 + 1500 : 60 * 1000\n\n if (rateLimiting.onRetry) {\n rateLimiting.onRetry({delay, rateLimit, retryCount, error})\n }\n\n return delay\n },\n })\n }\n\n // Set x-amz-access-token to each request\n instance.interceptors.request.use(async (config) => {\n config.headers['x-amz-access-token'] = restrictedDataToken ?? (await auth.getAccessToken())\n\n return config\n })\n\n instance.interceptors.response.use(\n async (response) => response,\n async (error: unknown) => {\n if (isAxiosError(error) && !(error instanceof SellingPartnerApiAuthError)) {\n throw new SellingPartnerApiError(error)\n }\n\n throw error\n },\n )\n\n if (logging?.request) {\n const requestLoggerOptions = logging.request === true ? undefined : logging.request\n\n if (requestLoggerOptions?.headers) {\n console.warn(\n 'WARNING: You have enabled logging of request headers, this can leak authentication information, you should disable in production.',\n )\n }\n\n instance.interceptors.request.use((config) => {\n const logger = requestLogger(config, {\n prefixText: `sp-api-sdk/${region}`,\n dateFormat: 'isoDateTime',\n method: true,\n url: true,\n params: false,\n data: true,\n headers: false,\n logger: console.info,\n ...requestLoggerOptions,\n })\n\n return {\n ...logger,\n headers: config.headers,\n }\n })\n }\n\n if (logging?.response) {\n const responseLoggerOptions = logging.response === true ? undefined : logging.response\n\n instance.interceptors.response.use((response) =>\n responseLogger(response, {\n prefixText: `sp-api-sdk/${region}`,\n dateFormat: 'isoDateTime',\n status: true,\n statusText: false,\n params: false,\n data: false,\n headers: true,\n logger: console.info,\n ...responseLoggerOptions,\n }),\n )\n }\n\n if (logging?.error) {\n const errorLoggerOptions = logging.error === true ? undefined : logging.error\n\n instance.interceptors.response.use(\n (response) => response,\n async (error) =>\n errorLogger(error, {\n prefixText: `sp-api-sdk/${region}`,\n dateFormat: 'isoDateTime',\n status: true,\n statusText: false,\n params: false,\n data: false,\n headers: true,\n logger: console.error,\n ...errorLoggerOptions,\n }),\n )\n }\n\n return {axios: instance, endpoint}\n}\n","import {URL} from 'node:url'\n\nimport {AxiosError} from 'axios'\n\n/**\n * Error thrown when a Selling Partner API request fails.\n *\n * Wraps the underlying Axios error with a message that includes the API name,\n * version, and HTTP status code (or \"No response\" for network errors).\n */\nexport class SellingPartnerApiError<T = unknown, D = any> extends AxiosError<T, D> {\n /** The original error message from the failed HTTP request. */\n public readonly innerMessage: string\n /** The API name extracted from the request URL path (e.g. `\"orders\"`). */\n public readonly apiName?: string\n /** The API version extracted from the request URL path (e.g. `\"v0\"`). */\n public readonly apiVersion?: string\n\n constructor(error: AxiosError<T, D>) {\n super('Unknown error', error.code, error.config, error.request, error.response)\n\n this.innerMessage = error.message\n\n if (error.config!.url) {\n const [apiName, apiVersion] = new URL(error.config!.url).pathname.split('/').slice(1)\n const apiPrefix = `${apiName} (${apiVersion})`\n\n this.apiName = apiName\n this.apiVersion = apiVersion\n this.message = error.response\n ? `${apiPrefix} error: Response code ${error.response.status}`\n : `${apiPrefix} error: No response`\n }\n\n this.name = this.constructor.name\n }\n}\n","import {type NormalizedPackageJson, sync as readPackageJson} from 'read-pkg-up'\n\nconst result = readPackageJson()\n\nexport const packageJson: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,OAAO,SAAY,QAAQ;AAExE,aAAS,aAAa,SAAS;AAAA,MAC7B,CAAC,aAAa;AAAA,MACd,OAAO,UACL,YAAY,OAAO;AAAA,QACjB,YAAY,cAAc,MAAM;AAAA,QAChC,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,YAAY;AAAA,QACZ,QAAQ;AAAA,QACR,MAAM;AAAA,QACN,SAAS;AAAA,QACT,QAAQ,QAAQ;AAAA,QAChB,GAAG;AAAA,MACL,CAAC;AAAA,IACL;AAAA,EACF;AAEA,SAAO,EAAC,OAAO,UAAU,SAAQ;AACnC;","names":["URL","rateLimit"]} |
+23
-13
@@ -5,21 +5,31 @@ { | ||
| "description": "Selling Parner API common library", | ||
| "version": "2.1.31", | ||
| "main": "dist/cjs/index.js", | ||
| "module": "dist/es/index.js", | ||
| "types": "dist/types/index.d.ts", | ||
| "version": "3.0.0", | ||
| "license": "MIT", | ||
| "type": "module", | ||
| "sideEffects": false, | ||
| "source": "./src/index.ts", | ||
| "main": "./dist/index.cjs", | ||
| "module": "./dist/index.js", | ||
| "types": "./dist/index.d.ts", | ||
| "exports": { | ||
| ".": { | ||
| "import": { | ||
| "types": "./dist/index.d.ts", | ||
| "default": "./dist/index.js" | ||
| }, | ||
| "require": { | ||
| "types": "./dist/index.d.cts", | ||
| "default": "./dist/index.cjs" | ||
| } | ||
| } | ||
| }, | ||
| "publishConfig": { | ||
| "access": "public" | ||
| }, | ||
| "directories": { | ||
| "lib": "dist", | ||
| "test": "__tests__" | ||
| }, | ||
| "files": [ | ||
| "dist/**/*.js", | ||
| "dist/**/*.d.ts" | ||
| "dist" | ||
| ], | ||
| "dependencies": { | ||
| "@sp-api-sdk/auth": "2.2.25", | ||
| "axios": "^1.15.2", | ||
| "@sp-api-sdk/auth": "3.0.0", | ||
| "axios": "^1.16.1", | ||
| "axios-logger": "^2.8.1", | ||
@@ -47,3 +57,3 @@ "axios-retry": "^4.5.0", | ||
| ], | ||
| "gitHead": "cc3ed7e58346bf7a4110ed8f1353aae840f294e2" | ||
| "gitHead": "40177b741b5e9299d449d10c8e41a9a798aec593" | ||
| } |
+3
-3
@@ -101,8 +101,8 @@ # `@sp-api-sdk/common` | ||
| try { | ||
| await client.getOrders({ marketplaceIds: ["A1PA6795UKMFR9"] }); | ||
| await client.searchOrders({ marketplaceIds: ["A1PA6795UKMFR9"] }); | ||
| } catch (error) { | ||
| if (error instanceof SellingPartnerApiError) { | ||
| console.error(error.message); // e.g. "orders (v0) error: Response code 403" | ||
| console.error(error.message); // e.g. "orders (2026-01-01) error: Response code 403" | ||
| console.error(error.apiName); // e.g. "orders" | ||
| console.error(error.apiVersion); // e.g. "v0" | ||
| console.error(error.apiVersion); // e.g. "2026-01-01" | ||
| console.error(error.innerMessage); // Original axios error message | ||
@@ -109,0 +109,0 @@ } |
| "use strict"; | ||
| var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| var desc = Object.getOwnPropertyDescriptor(m, k); | ||
| if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
| desc = { enumerable: true, get: function() { return m[k]; } }; | ||
| } | ||
| Object.defineProperty(o, k2, desc); | ||
| }) : (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| o[k2] = m[k]; | ||
| })); | ||
| var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { | ||
| Object.defineProperty(o, "default", { enumerable: true, value: v }); | ||
| }) : function(o, v) { | ||
| o["default"] = v; | ||
| }); | ||
| var __importStar = (this && this.__importStar) || (function () { | ||
| var ownKeys = function(o) { | ||
| ownKeys = Object.getOwnPropertyNames || function (o) { | ||
| var ar = []; | ||
| for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; | ||
| return ar; | ||
| }; | ||
| return ownKeys(o); | ||
| }; | ||
| return function (mod) { | ||
| if (mod && mod.__esModule) return mod; | ||
| var result = {}; | ||
| if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); | ||
| __setModuleDefault(result, mod); | ||
| return result; | ||
| }; | ||
| })(); | ||
| var __importDefault = (this && this.__importDefault) || function (mod) { | ||
| return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.createAxiosInstance = createAxiosInstance; | ||
| const axios_1 = __importStar(require("axios")); | ||
| const axios_logger_1 = require("axios-logger"); | ||
| const axios_retry_1 = __importDefault(require("axios-retry")); | ||
| const auth_1 = require("@sp-api-sdk/auth"); | ||
| const errors_1 = require("./errors"); | ||
| const regions_1 = require("./regions"); | ||
| const package_1 = require("./utils/package"); | ||
| /** | ||
| * 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 = `${package_1.packageJson.name}/${package_1.packageJson.version}`, sandbox = false, rateLimiting, logging, }, rateLimits) { | ||
| const regionConfiguration = regions_1.sellingPartnerRegions[region]; | ||
| if (!regionConfiguration) { | ||
| throw new TypeError(`Unknown or unsupported region: ${region}`); | ||
| } | ||
| const instance = axios_1.default.create({ | ||
| headers: { | ||
| 'user-agent': userAgent, | ||
| }, | ||
| }); | ||
| const endpoint = regionConfiguration.endpoints[sandbox ? 'sandbox' : 'production']; | ||
| if (rateLimiting?.retry) { | ||
| (0, axios_retry_1.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 amznRateLimit = Number.parseFloat(error.response?.headers['x-amzn-ratelimit-limit'] ?? ''); | ||
| const rateLimit = Number.isNaN(amznRateLimit) | ||
| ? rateLimits.find((rateLimit) => rateLimit.method.toLowerCase() === method && rateLimit.urlRegex.exec(url.pathname))?.rate | ||
| : amznRateLimit; | ||
| const delay = rateLimit ? (1 / rateLimit) * 1000 + 1500 : 60 * 1000; | ||
| if (rateLimiting.onRetry) { | ||
| rateLimiting.onRetry({ delay, rateLimit, retryCount, error }); | ||
| } | ||
| return delay; | ||
| }, | ||
| }); | ||
| } | ||
| // Set x-amz-access-token to each request | ||
| 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_1.isAxiosError)(error) && !(error instanceof auth_1.SellingPartnerApiAuthError)) { | ||
| throw new errors_1.SellingPartnerApiError(error); | ||
| } | ||
| throw error; | ||
| }); | ||
| if (logging?.request) { | ||
| const requestLoggerOptions = logging.request === true ? undefined : 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) => { | ||
| const logger = (0, axios_logger_1.requestLogger)(config, { | ||
| prefixText: `sp-api-sdk/${region}`, | ||
| dateFormat: 'isoDateTime', | ||
| method: true, | ||
| url: true, | ||
| params: false, | ||
| data: true, | ||
| headers: false, | ||
| logger: console.info, | ||
| ...requestLoggerOptions, | ||
| }); | ||
| return { | ||
| ...logger, | ||
| headers: config.headers, | ||
| }; | ||
| }); | ||
| } | ||
| if (logging?.response) { | ||
| const responseLoggerOptions = logging.response === true ? undefined : logging.response; | ||
| instance.interceptors.response.use((response) => (0, axios_logger_1.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) { | ||
| const errorLoggerOptions = logging.error === true ? undefined : logging.error; | ||
| instance.interceptors.response.use((response) => response, async (error) => (0, axios_logger_1.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 }; | ||
| } |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.SellingPartnerApiError = void 0; | ||
| const node_url_1 = require("node:url"); | ||
| const axios_1 = require("axios"); | ||
| /** | ||
| * 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). | ||
| */ | ||
| class SellingPartnerApiError extends axios_1.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_1.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; | ||
| } | ||
| } | ||
| exports.SellingPartnerApiError = SellingPartnerApiError; |
| "use strict"; | ||
| var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| var desc = Object.getOwnPropertyDescriptor(m, k); | ||
| if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { | ||
| desc = { enumerable: true, get: function() { return m[k]; } }; | ||
| } | ||
| Object.defineProperty(o, k2, desc); | ||
| }) : (function(o, m, k, k2) { | ||
| if (k2 === undefined) k2 = k; | ||
| o[k2] = m[k]; | ||
| })); | ||
| var __exportStar = (this && this.__exportStar) || function(m, exports) { | ||
| for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); | ||
| }; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| __exportStar(require("./regions"), exports); | ||
| __exportStar(require("./axios"), exports); | ||
| __exportStar(require("./errors"), exports); |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.sellingPartnerRegions = void 0; | ||
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| exports.sellingPartnerRegions = { | ||
| na: { | ||
| awsRegion: 'us-east-1', | ||
| endpoints: { | ||
| production: 'https://sellingpartnerapi-na.amazon.com', | ||
| sandbox: 'https://sandbox.sellingpartnerapi-na.amazon.com', | ||
| }, | ||
| }, | ||
| eu: { | ||
| awsRegion: 'eu-west-1', | ||
| endpoints: { | ||
| production: 'https://sellingpartnerapi-eu.amazon.com', | ||
| sandbox: 'https://sandbox.sellingpartnerapi-eu.amazon.com', | ||
| }, | ||
| }, | ||
| fe: { | ||
| awsRegion: 'us-west-2', | ||
| endpoints: { | ||
| production: 'https://sellingpartnerapi-fe.amazon.com', | ||
| sandbox: 'https://sandbox.sellingpartnerapi-fe.amazon.com', | ||
| }, | ||
| }, | ||
| }; |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.packageJson = void 0; | ||
| const read_pkg_up_1 = require("read-pkg-up"); | ||
| const result = (0, read_pkg_up_1.sync)(); | ||
| exports.packageJson = result?.packageJson ?? { | ||
| _id: '', | ||
| readme: '', | ||
| name: '@sp-api-sdk/common', | ||
| version: 'unknown', | ||
| }; |
-110
| import axios, { isAxiosError } from 'axios'; | ||
| import { errorLogger, requestLogger, responseLogger } from 'axios-logger'; | ||
| import axiosRetry from 'axios-retry'; | ||
| import { SellingPartnerApiAuthError } from '@sp-api-sdk/auth'; | ||
| import { SellingPartnerApiError } from './errors'; | ||
| import { sellingPartnerRegions } from './regions'; | ||
| import { packageJson } from './utils/package'; | ||
| /** | ||
| * 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. | ||
| */ | ||
| export function createAxiosInstance({ auth, restrictedDataToken, region, userAgent = `${packageJson.name}/${packageJson.version}`, sandbox = false, rateLimiting, logging, }, rateLimits) { | ||
| const regionConfiguration = sellingPartnerRegions[region]; | ||
| if (!regionConfiguration) { | ||
| throw new TypeError(`Unknown or unsupported region: ${region}`); | ||
| } | ||
| const instance = axios.create({ | ||
| headers: { | ||
| 'user-agent': userAgent, | ||
| }, | ||
| }); | ||
| const endpoint = regionConfiguration.endpoints[sandbox ? 'sandbox' : 'production']; | ||
| if (rateLimiting?.retry) { | ||
| axiosRetry(instance, { | ||
| retryCondition: (error) => error.response?.status === 429, | ||
| retryDelay(retryCount, error) { | ||
| const url = new URL(error.config.url); | ||
| const method = error.config.method?.toLowerCase(); | ||
| const amznRateLimit = Number.parseFloat(error.response?.headers['x-amzn-ratelimit-limit'] ?? ''); | ||
| const rateLimit = Number.isNaN(amznRateLimit) | ||
| ? rateLimits.find((rateLimit) => rateLimit.method.toLowerCase() === method && rateLimit.urlRegex.exec(url.pathname))?.rate | ||
| : amznRateLimit; | ||
| const delay = rateLimit ? (1 / rateLimit) * 1000 + 1500 : 60 * 1000; | ||
| if (rateLimiting.onRetry) { | ||
| rateLimiting.onRetry({ delay, rateLimit, retryCount, error }); | ||
| } | ||
| return delay; | ||
| }, | ||
| }); | ||
| } | ||
| // Set x-amz-access-token to each request | ||
| 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 (isAxiosError(error) && !(error instanceof SellingPartnerApiAuthError)) { | ||
| throw new SellingPartnerApiError(error); | ||
| } | ||
| throw error; | ||
| }); | ||
| if (logging?.request) { | ||
| const requestLoggerOptions = logging.request === true ? undefined : 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) => { | ||
| const logger = requestLogger(config, { | ||
| prefixText: `sp-api-sdk/${region}`, | ||
| dateFormat: 'isoDateTime', | ||
| method: true, | ||
| url: true, | ||
| params: false, | ||
| data: true, | ||
| headers: false, | ||
| logger: console.info, | ||
| ...requestLoggerOptions, | ||
| }); | ||
| return { | ||
| ...logger, | ||
| headers: config.headers, | ||
| }; | ||
| }); | ||
| } | ||
| if (logging?.response) { | ||
| const responseLoggerOptions = logging.response === true ? undefined : logging.response; | ||
| instance.interceptors.response.use((response) => 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) { | ||
| const errorLoggerOptions = logging.error === true ? undefined : logging.error; | ||
| instance.interceptors.response.use((response) => response, async (error) => 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 }; | ||
| } |
| import { URL } from 'node:url'; | ||
| import { AxiosError } from 'axios'; | ||
| /** | ||
| * 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). | ||
| */ | ||
| export class SellingPartnerApiError extends 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 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; | ||
| } | ||
| } |
| export * from './regions'; | ||
| export * from './axios'; | ||
| export * from './errors'; |
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| export const sellingPartnerRegions = { | ||
| na: { | ||
| awsRegion: 'us-east-1', | ||
| endpoints: { | ||
| production: 'https://sellingpartnerapi-na.amazon.com', | ||
| sandbox: 'https://sandbox.sellingpartnerapi-na.amazon.com', | ||
| }, | ||
| }, | ||
| eu: { | ||
| awsRegion: 'eu-west-1', | ||
| endpoints: { | ||
| production: 'https://sellingpartnerapi-eu.amazon.com', | ||
| sandbox: 'https://sandbox.sellingpartnerapi-eu.amazon.com', | ||
| }, | ||
| }, | ||
| fe: { | ||
| awsRegion: 'us-west-2', | ||
| endpoints: { | ||
| production: 'https://sellingpartnerapi-fe.amazon.com', | ||
| sandbox: 'https://sandbox.sellingpartnerapi-fe.amazon.com', | ||
| }, | ||
| }, | ||
| }; |
| import { sync as readPackageJson } from 'read-pkg-up'; | ||
| const result = readPackageJson(); | ||
| export const packageJson = result?.packageJson ?? { | ||
| _id: '', | ||
| readme: '', | ||
| name: '@sp-api-sdk/common', | ||
| version: 'unknown', | ||
| }; |
| import axios, { type AxiosError, type Method } from 'axios'; | ||
| import { errorLogger, requestLogger, responseLogger } from 'axios-logger'; | ||
| import { type SellingPartnerApiAuth } from '@sp-api-sdk/auth'; | ||
| import { type SellingPartnerRegion } from './regions'; | ||
| type RequestLogConfig = Exclude<Parameters<typeof requestLogger>[1], undefined>; | ||
| type ResponseLogConfig = Exclude<Parameters<typeof responseLogger>[1], undefined>; | ||
| type ErrorLogConfig = Exclude<Parameters<typeof errorLogger>[1], undefined>; | ||
| /** Per-endpoint rate limit definition used for retry delay calculation. */ | ||
| export interface RateLimit { | ||
| /** Regular expression matched against the request URL pathname. */ | ||
| urlRegex: RegExp; | ||
| /** Sustained request rate in requests per second. */ | ||
| rate: number; | ||
| /** Maximum burst size (number of requests allowed before throttling). */ | ||
| burst: number; | ||
| /** HTTP method this rate limit applies to. */ | ||
| method: Method; | ||
| } | ||
| /** Parameters passed to the {@link ClientConfiguration.rateLimiting} `onRetry` callback. */ | ||
| export interface OnRetryParameters { | ||
| /** Delay in milliseconds before the next retry attempt. */ | ||
| delay: number; | ||
| /** Rate limit (requests per second) used to calculate the delay, if available. */ | ||
| rateLimit?: number; | ||
| /** Number of retry attempts so far. */ | ||
| retryCount: number; | ||
| /** The Axios error that triggered the retry. */ | ||
| error: AxiosError; | ||
| } | ||
| /** Configuration options for creating a Selling Partner API Axios instance. */ | ||
| export interface ClientConfiguration { | ||
| /** Authentication handler that provides LWA access tokens. */ | ||
| auth: SellingPartnerApiAuth; | ||
| /** Restricted Data Token to use instead of the standard access token. */ | ||
| restrictedDataToken?: string; | ||
| /** Selling Partner API region to send requests to. */ | ||
| region: SellingPartnerRegion; | ||
| /** Custom `User-Agent` header value. */ | ||
| userAgent?: string; | ||
| /** When `true`, requests are sent to the sandbox endpoint. Defaults to `false`. */ | ||
| sandbox?: boolean; | ||
| /** Rate-limiting and retry configuration for 429 responses. */ | ||
| rateLimiting?: { | ||
| /** When `true`, automatically retries throttled (HTTP 429) requests. */ | ||
| retry: boolean; | ||
| /** Optional callback invoked before each retry attempt. */ | ||
| onRetry?: (retryInfo: OnRetryParameters) => void; | ||
| }; | ||
| /** Axios request/response/error logging configuration. Pass `true` to use defaults. */ | ||
| logging?: { | ||
| /** Log outgoing requests. */ | ||
| request?: RequestLogConfig | true; | ||
| /** Log incoming responses. */ | ||
| response?: ResponseLogConfig | true; | ||
| /** Log request errors. */ | ||
| error?: ErrorLogConfig | true; | ||
| }; | ||
| } | ||
| /** | ||
| * 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. | ||
| */ | ||
| export declare function createAxiosInstance({ auth, restrictedDataToken, region, userAgent, sandbox, rateLimiting, logging, }: ClientConfiguration, rateLimits: RateLimit[]): { | ||
| axios: axios.AxiosInstance; | ||
| endpoint: string; | ||
| }; | ||
| export {}; |
| import { AxiosError } from 'axios'; | ||
| /** | ||
| * 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). | ||
| */ | ||
| export declare class SellingPartnerApiError<T = unknown, D = any> extends AxiosError<T, D> { | ||
| /** The original error message from the failed HTTP request. */ | ||
| readonly innerMessage: string; | ||
| /** The API name extracted from the request URL path (e.g. `"orders"`). */ | ||
| readonly apiName?: string; | ||
| /** The API version extracted from the request URL path (e.g. `"v0"`). */ | ||
| readonly apiVersion?: string; | ||
| constructor(error: AxiosError<T, D>); | ||
| } |
| export * from './regions'; | ||
| export * from './axios'; | ||
| export * from './errors'; |
| /** Selling Partner API region identifier. */ | ||
| export type SellingPartnerRegion = 'na' | 'eu' | 'fe'; | ||
| interface RegionConfiguration { | ||
| awsRegion: string; | ||
| endpoints: { | ||
| production: string; | ||
| sandbox: string; | ||
| }; | ||
| } | ||
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| export declare const sellingPartnerRegions: Record<SellingPartnerRegion, RegionConfiguration>; | ||
| export {}; |
| import { type NormalizedPackageJson } from 'read-pkg-up'; | ||
| export declare const packageJson: NormalizedPackageJson; |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
57242
95.15%Yes
NaN9
-50%494
-5.18%1
Infinity%+ Added
- Removed
Updated
Updated