@medusajs/medusa-js
Version:
Client for Medusa Commerce Rest API
1 lines • 548 kB
Source Map (JSON)
{"version":3,"sources":["../src/error.ts","../src/key-manager.ts","../src/request.ts","../src/jwt-token-manager.ts","../src/resources/base.ts","../src/resources/addresses.ts","../src/resources/auth.ts","../src/resources/line-items.ts","../src/resources/carts.ts","../src/resources/collections.ts","../src/resources/customers.ts","../src/resources/payment-methods.ts","../src/resources/gift-cards.ts","../src/resources/order-edits.ts","../src/resources/orders.ts","../src/resources/payment-collections.ts","../src/resources/product-categories.ts","../src/resources/product-tags.ts","../src/resources/product-types.ts","../src/resources/product-variants.ts","../src/resources/products.ts","../src/resources/regions.ts","../src/resources/return-reasons.ts","../src/resources/returns.ts","../src/resources/shipping-options.ts","../src/resources/swaps.ts","../src/resources/admin/auth.ts","../src/resources/admin/batch-jobs.ts","../src/utils.ts","../src/resources/admin/collections.ts","../src/resources/admin/currencies.ts","../src/resources/admin/custom.ts","../src/resources/admin/customer-groups.ts","../src/resources/admin/customers.ts","../src/resources/admin/discounts.ts","../src/resources/admin/draft-orders.ts","../src/resources/admin/gift-cards.ts","../src/resources/admin/inventory-item.ts","../src/resources/admin/invites.ts","../src/resources/admin/notes.ts","../src/resources/admin/notifications.ts","../src/resources/admin/order-edits.ts","../src/resources/admin/orders.ts","../src/resources/admin/payment-collections.ts","../src/resources/admin/payments.ts","../src/resources/admin/price-lists.ts","../src/resources/admin/product-categories.ts","../src/resources/admin/product-tags.ts","../src/resources/admin/product-types.ts","../src/resources/admin/products.ts","../src/resources/admin/publishable-api-keys.ts","../src/resources/admin/regions.ts","../src/resources/admin/reservations.ts","../src/resources/admin/return-reasons.ts","../src/resources/admin/returns.ts","../src/resources/admin/sales-channels.ts","../src/resources/admin/shipping-options.ts","../src/resources/admin/shipping-profiles.ts","../src/resources/admin/stock-locations.ts","../src/resources/admin/store.ts","../src/resources/admin/swaps.ts","../src/resources/admin/tax-rates.ts","../src/resources/admin/uploads.ts","../src/resources/admin/users.ts","../src/resources/admin/variants.ts","../src/resources/admin/index.ts","../src/index.ts"],"sourcesContent":["\"use strict\"\n/**\n * MedusaError is the base error for every other MedusaError\n */\nexport default class MedusaError extends Error {\n constructor() {\n super()\n }\n\n public static factory(type: ErrorType): MedusaError {\n switch (type) {\n case ErrorType.INVALID_REQUEST:\n return new MedusaInvalidRequestError()\n case ErrorType.AUTHENTICATION:\n return new MedusaAuthenticationError()\n case ErrorType.API:\n return new MedusaAPIError()\n case ErrorType.PERMISSION:\n return new MedusaPermissionError()\n case ErrorType.CONNECTION:\n return new MedusaConnectionError()\n }\n }\n}\n\nenum ErrorType {\n \"INVALID_REQUEST\",\n \"API\",\n \"AUTHENTICATION\",\n \"PERMISSION\",\n \"CONNECTION\",\n}\n\n/**\n * MedusaInvalidRequestError is raised when a request as invalid parameters.\n */\nexport class MedusaInvalidRequestError extends MedusaError {}\n\n/**\n * MedusaAPIError is raised in case no other type cover the problem\n */\nexport class MedusaAPIError extends MedusaError {}\n\n/**\n * MedusaAuthenticationError is raised when invalid credentials is used to connect to Medusa\n */\nexport class MedusaAuthenticationError extends MedusaError {}\n\n/**\n * MedusaPermissionError is raised when attempting to access a resource without permissions\n */\nexport class MedusaPermissionError extends MedusaError {}\n\n/**\n * MedusaConnectionError is raised when the Medusa servers can't be reached.\n */\nexport class MedusaConnectionError extends MedusaError {}\n","/**\n * `KeyManager` holds API keys in state.\n */\nclass KeyManager {\n private publishableApiKey: string | null = null\n\n /**\n * Set a publishable api key to be sent with each request.\n */\n public registerPublishableApiKey(key: string) {\n this.publishableApiKey = key\n }\n\n /**\n * Retrieve the publishable api key.\n */\n public getPublishableApiKey() {\n return this.publishableApiKey\n }\n}\n\n/**\n * Export singleton instance.\n */\nexport default new KeyManager()\n","import axios, { AxiosError, AxiosInstance, AxiosRequestHeaders } from \"axios\"\nimport * as rax from \"retry-axios\"\nimport { v4 as uuidv4 } from \"uuid\"\n\nimport KeyManager from \"./key-manager\"\nimport JwtTokenManager from \"./jwt-token-manager\"\n\nconst unAuthenticatedAdminEndpoints = {\n \"/admin/auth\": \"POST\",\n \"/admin/users/password-token\": \"POST\",\n \"/admin/users/reset-password\": \"POST\",\n \"/admin/invites/accept\": \"POST\",\n}\n\nexport interface Config {\n baseUrl: string\n maxRetries: number\n apiKey?: string\n publishableApiKey?: string\n customHeaders?: Record<string, any>\n}\n\n/**\n * @interface\n * \n * Options to pass to requests sent to custom API Routes\n * \n * @prop timeout - The number of milliseconds before the request times out.\n * @prop numberOfRetries - The number of times to retry a request before failing.\n */\nexport interface RequestOptions {\n timeout?: number\n numberOfRetries?: number\n}\n\nexport type RequestMethod = \"DELETE\" | \"POST\" | \"GET\"\n\nconst defaultConfig = {\n maxRetries: 0,\n baseUrl: \"http://localhost:9000\",\n}\n\nclass Client {\n private axiosClient: AxiosInstance\n private config: Config\n\n constructor(config: Config) {\n /** @private @constant {AxiosInstance} */\n this.axiosClient = this.createClient({ ...defaultConfig, ...config })\n\n /** @private @constant {Config} */\n this.config = { ...defaultConfig, ...config }\n }\n\n shouldRetryCondition(\n err: AxiosError,\n numRetries: number,\n maxRetries: number\n ): boolean {\n // Obviously, if we have reached max. retries we stop\n if (numRetries >= maxRetries) {\n return false\n }\n\n // If no response, we assume a connection error and retry\n if (!err.response) {\n return true\n }\n\n // Retry on conflicts\n if (err.response.status === 409) {\n return true\n }\n\n // All 5xx errors are retried\n // OBS: We are currently not retrying 500 requests, since our core needs proper error handling.\n // At the moment, 500 will be returned on all errors, that are not of type MedusaError.\n if (err.response.status > 500 && err.response.status <= 599) {\n return true\n }\n\n return false\n }\n\n // Stolen from https://github.com/stripe/stripe-node/blob/fd0a597064289b8c82f374f4747d634050739043/lib/utils.js#L282\n normalizeHeaders(obj: object): Record<string, any> {\n if (!(obj && typeof obj === \"object\")) {\n return obj\n }\n\n return Object.keys(obj).reduce((result, header) => {\n result[this.normalizeHeader(header)] = obj[header]\n return result\n }, {})\n }\n\n // Stolen from https://github.com/marten-de-vries/header-case-normalizer/blob/master/index.js#L36-L41\n normalizeHeader(header: string): string {\n return header\n .split(\"-\")\n .map(\n (text) => text.charAt(0).toUpperCase() + text.substr(1).toLowerCase()\n )\n .join(\"-\")\n }\n\n requiresAuthentication(path, method): boolean {\n return (\n path.startsWith(\"/admin\") &&\n unAuthenticatedAdminEndpoints[path] !== method\n )\n }\n\n /**\n * Creates all the initial headers.\n * We add the idempotency key, if the request is configured to retry.\n * @param {object} userHeaders user supplied headers\n * @param {Types.RequestMethod} method request method\n * @param {string} path request path\n * @param {object} customHeaders user supplied headers\n * @return {object}\n */\n setHeaders(\n userHeaders: RequestOptions,\n method: RequestMethod,\n path: string,\n customHeaders: Record<string, any> = {}\n ): AxiosRequestHeaders {\n let defaultHeaders: Record<string, any> = {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n }\n\n if (this.config.apiKey && this.requiresAuthentication(path, method)) {\n defaultHeaders = {\n ...defaultHeaders,\n \"x-medusa-access-token\": this.config.apiKey,\n }\n }\n\n const domain: \"admin\" | \"store\" = path.includes(\"admin\") ? \"admin\" : \"store\"\n\n if (JwtTokenManager.getJwt(domain)) {\n defaultHeaders = {\n ...defaultHeaders,\n Authorization: `Bearer ${JwtTokenManager.getJwt(domain)}`,\n }\n }\n\n const publishableApiKey =\n this.config.publishableApiKey || KeyManager.getPublishableApiKey()\n\n if (publishableApiKey) {\n defaultHeaders[\"x-publishable-api-key\"] = publishableApiKey\n }\n\n // only add idempotency key, if we want to retry\n if (this.config.maxRetries > 0 && method === \"POST\") {\n defaultHeaders[\"Idempotency-Key\"] = uuidv4()\n }\n\n return Object.assign(\n {},\n defaultHeaders,\n this.normalizeHeaders(userHeaders),\n customHeaders\n )\n }\n\n /**\n * Creates the axios client used for requests\n * As part of the creation, we configure the retry conditions\n * and the exponential backoff approach.\n * @param {Config} config user supplied configurations\n * @return {AxiosInstance}\n */\n createClient(config: Config): AxiosInstance {\n const client = axios.create({\n baseURL: config.baseUrl,\n })\n\n rax.attach(client)\n\n client.defaults.raxConfig = {\n instance: client,\n retry: config.maxRetries,\n backoffType: \"exponential\",\n shouldRetry: (err: AxiosError): boolean => {\n const cfg = rax.getConfig(err)\n if (cfg) {\n return this.shouldRetryCondition(\n err,\n cfg.currentRetryAttempt ?? 1,\n cfg.retry ?? 3\n )\n } else {\n return false\n }\n },\n }\n\n return client\n }\n\n /**\n * Axios request\n * @param method request method\n * @param path request path\n * @param payload request payload\n * @param options axios configuration\n * @param customHeaders custom request headers\n * @return\n */\n async request(\n method: RequestMethod,\n path: string,\n payload: Record<string, any> = {},\n options: RequestOptions = {},\n customHeaders: Record<string, any> = {}\n ): Promise<any> {\n \n customHeaders = { ...this.config.customHeaders, ...customHeaders }\n\n const reqOpts = {\n method,\n withCredentials: true,\n url: path,\n json: true,\n headers: this.setHeaders(options, method, path, customHeaders),\n }\n\n if ([\"POST\", \"DELETE\"].includes(method)) {\n reqOpts[\"data\"] = payload\n }\n\n // e.g. data = { cart: { ... } }, response = { status, headers, ... }\n const { data, ...response } = await this.axiosClient(reqOpts)\n\n // e.g. would return an object like of this shape { cart, response }\n return { ...data, response }\n }\n}\n\nexport default Client\n","/**\n * `JwtTokenManager` holds JWT tokens in state.\n */\nclass JwtTokenManager {\n private adminJwt: string | null = null;\n private storeJwt: string | null = null;\n\n /**\n * Set a store or admin jwt token to be sent with each request.\n */\n public registerJwt(token: string, domain: \"admin\" | \"store\") {\n if (domain === \"admin\") {\n this.adminJwt = token;\n } else if (domain === \"store\") {\n this.storeJwt = token;\n } else {\n throw new Error(`'domain' must be wither 'admin' or 'store' received ${domain}`)\n }\n }\n\n /**\n * Retrieve the store or admin jwt token\n */\n public getJwt(domain: \"admin\" | \"store\") {\n if (domain === \"admin\") {\n return this.adminJwt;\n } else if (domain === \"store\") {\n return this.storeJwt;\n } else {\n throw new Error(`'domain' must be wither 'admin' or 'store' received ${domain}`)\n }\n }\n}\n\n/**\n * Export singleton instance.\n */\nexport default new JwtTokenManager()\n","import Client from \"../request\"\n\nexport default class BaseResource {\n public client: Client\n\n constructor(client: Client) {\n this.client = client\n }\n}\n","import {\n StoreCustomersRes,\n StorePostCustomersCustomerAddressesAddressReq,\n StorePostCustomersCustomerAddressesReq,\n} from \"@medusajs/medusa\"\nimport { ResponsePromise } from \"../typings\"\nimport BaseResource from \"./base\"\n\n/**\n * This class is used to send requests to Address API Routes part of the [Store Customer API Routes](https://docs.medusajs.com/api/store#customers_postcustomers). All its method\n * are available in the JS Client under the `medusa.customers.addresses` property.\n * \n * All methods in this class require {@link AuthResource.authenticate | customer authentication}.\n */\nclass AddressesResource extends BaseResource {\n /**\n * Add an address to the logged-in customer's saved addresses.\n * @param {StorePostCustomersCustomerAddressesReq} payload - The address to add.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCustomersRes>} Resolves to the customer's details, including the customer's addresses in the `shipping_addresses` attribute.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * // must be previously logged\n * medusa.customers.addresses.addAddress({\n * address: {\n * first_name: \"Celia\",\n * last_name: \"Schumm\",\n * address_1: \"225 Bednar Curve\",\n * city: \"Danielville\",\n * country_code: \"US\",\n * postal_code: \"85137\",\n * phone: \"981-596-6748 x90188\",\n * company: \"Wyman LLC\",\n * province: \"Georgia\",\n * }\n * })\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n addAddress(\n payload: StorePostCustomersCustomerAddressesReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCustomersRes> {\n const path = `/store/customers/me/addresses`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Delete an address of the logged-in customer.\n * @param {string} address_id - The ID of the address to delete.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCustomersRes>} Resolves to the customer's details, including the customer's addresses in the `shipping_addresses` attribute.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * // must be previously logged\n * medusa.customers.addresses.deleteAddress(addressId)\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n deleteAddress(\n address_id: string,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCustomersRes> {\n const path = `/store/customers/me/addresses/${address_id}`\n return this.client.request(\"DELETE\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Update an address of the logged-in customer.\n * @param {string} address_id - The address's ID.\n * @param {StorePostCustomersCustomerAddressesAddressReq} payload - The attributes to update in the address.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCustomersRes>} Resolves to the customer's details, including the customer's addresses in the `shipping_addresses` attribute.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * // must be previously logged\n * medusa.customers.addresses.updateAddress(addressId, {\n * first_name: \"Gina\"\n * })\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n updateAddress(\n address_id: string,\n payload: StorePostCustomersCustomerAddressesAddressReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCustomersRes> {\n const path = `/store/customers/me/addresses/${address_id}`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n}\n\nexport default AddressesResource\n","import {\n StoreGetAuthEmailRes,\n StorePostAuthReq,\n StoreAuthRes,\n StoreBearerAuthRes,\n} from \"@medusajs/medusa\"\nimport { ResponsePromise } from \"../typings\"\nimport JwtTokenManager from \"../jwt-token-manager\"\nimport BaseResource from \"./base\"\n\n/**\n * This class is used to send requests to [Store Auth API Routes](https://docs.medusajs.com/api/store#auth). All its method\n * are available in the JS Client under the `medusa.auth` property.\n * \n * The methods in this class allows you to manage a customer's session, such as login or log out.\n * You can send authenticated requests for a customer either using the Cookie header or using the JWT Token.\n * When you log the customer in using the {@link authenticate} method, the JS client will automatically attach the\n * cookie header in all subsequent requests.\n * \n * Related Guide: [How to implement customer profiles in your storefront](https://docs.medusajs.com/modules/customers/storefront/implement-customer-profiles).\n */\nclass AuthResource extends BaseResource {\n /**\n * Authenticate a customer using their email and password. If the customer is authenticated successfully, the cookie is automatically attached to subsequent requests sent with the JS Client.\n * @param {StorePostAuthReq} payload - The credentials of the customer to authenticate.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreAuthRes>} Resolves to the customer's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.auth.authenticate({\n * email: \"user@example.com\",\n * password: \"user@example.com\"\n * })\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n authenticate(payload: StorePostAuthReq, customHeaders: Record<string, any> = {}): ResponsePromise<StoreAuthRes> {\n const path = `/store/auth`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Log out the customer and remove their authentication session. This method requires {@link AuthResource.authenticate | customer authentication}.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<void>} Resolves when customer is logged out successfully.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.auth.deleteSession()\n * .then(() => {\n * // customer logged out successfully\n * })\n */\n deleteSession(customHeaders: Record<string, any> = {}): ResponsePromise<void> {\n const path = `/store/auth`\n return this.client.request(\"DELETE\", path, {}, {}, customHeaders)\n }\n\n /**\n * Retrieve the details of the logged-in customer. Can also be used to check if there is an authenticated customer.\n * This method requires {@link AuthResource.authenticate | customer authentication}.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreAuthRes>} Resolves to the customer's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * // must be previously logged\n * medusa.auth.getSession()\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n getSession(customHeaders: Record<string, any> = {}): ResponsePromise<StoreAuthRes> {\n const path = `/store/auth`\n return this.client.request(\"GET\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Check if the email is already used by another registered customer. Can be used to validate a new customer's email.\n * @param {string} email - The email to check.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreGetAuthEmailRes>} Resolves to the result of the check.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.auth.exists(\"user@example.com\")\n */\n exists(email: string, customHeaders: Record<string, any> = {}): ResponsePromise<StoreGetAuthEmailRes> {\n const path = `/store/auth/${email}`\n return this.client.request(\"GET\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Authenticate the customer and retrieve a JWT token to use for subsequent authenticated requests.\n * @param {AdminPostAuthReq} payload - The credentials of the customer to authenticate.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreBearerAuthRes>} Resolves to the access token of the customer, if they're authenticated successfully.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.auth.getToken({\n * email: 'user@example.com',\n * password: 'supersecret'\n * })\n * .then(({ access_token }) => {\n * console.log(access_token);\n * })\n */\n getToken(\n payload: StorePostAuthReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreBearerAuthRes> {\n const path = `/store/auth/token`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n .then((res) => {\n JwtTokenManager.registerJwt(res.access_token, \"store\");\n \n return res\n });\n }\n}\n\nexport default AuthResource\n","import {\n StoreCartsRes,\n StorePostCartsCartLineItemsItemReq,\n StorePostCartsCartLineItemsReq,\n} from \"@medusajs/medusa\"\nimport { ResponsePromise } from \"../typings\"\nimport BaseResource from \"./base\"\n\n/**\n * This class is used to send requests to Line Item API Routes part of the [Store Cart API Routes](https://docs.medusajs.com/api/store#carts). All its method\n * are available in the JS Client under the `medusa.carts.lineItems` property.\n */\nclass LineItemsResource extends BaseResource {\n /**\n * Generates a Line Item with a given Product Variant and adds it to the Cart\n * @param {string} cart_id - The cart's ID.\n * @param {StorePostCartsCartLineItemsReq} payload - The line item to be created.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the associated cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.lineItems.create(cart_id, {\n * variant_id,\n * quantity: 1\n * })\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n create(\n cart_id: string,\n payload: StorePostCartsCartLineItemsReq,\n customHeaders: Record<string, any> = {}): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/line-items`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Update a line item's data.\n * @param {string} cart_id - The ID of the line item's cart.\n * @param {string} line_id - The ID of the line item to update.\n * @param {StorePostCartsCartLineItemsItemReq} payload - The data to update in the line item.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the associated cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.lineItems.update(cartId, lineId, {\n * quantity: 1\n * })\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n update(\n cart_id: string,\n line_id: string,\n payload: StorePostCartsCartLineItemsItemReq,\n customHeaders: Record<string, any> = {}): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/line-items/${line_id}`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Delete a line item from a cart. The payment sessions will be updated and the totals will be recalculated.\n * @param {string} cart_id - The ID of the line item's cart.\n * @param {string} line_id - The ID of the line item to delete.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the associated cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.lineItems.delete(cartId, lineId)\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n delete(cart_id: string, line_id: string, customHeaders: Record<string, any> = {}): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/line-items/${line_id}`\n return this.client.request(\"DELETE\", path, undefined, {}, customHeaders)\n }\n}\n\nexport default LineItemsResource\n","import {\n StoreCartsRes,\n StoreCompleteCartRes,\n StorePostCartReq,\n StorePostCartsCartPaymentSessionReq,\n StorePostCartsCartPaymentSessionUpdateReq,\n StorePostCartsCartReq,\n StorePostCartsCartShippingMethodReq,\n} from \"@medusajs/medusa\"\nimport { ResponsePromise } from \"../typings\"\nimport BaseResource from \"./base\"\nimport LineItemsResource from \"./line-items\"\n\n/**\n * This class is used to send requests to [Store Cart API Routes](https://docs.medusajs.com/api/store#carts). All its method\n * are available in the JS Client under the `medusa.carts` property.\n * \n * A cart is a virtual shopping bag that customers can use to add items they want to purchase.\n * A cart is then used to checkout and place an order.\n * \n * Related Guide: [How to implement cart functionality in your storefront](https://docs.medusajs.com/modules/carts-and-checkout/storefront/implement-cart).\n */\nclass CartsResource extends BaseResource {\n /**\n * An instance of {@link LineItemsResource} used to send requests to line-item-related routes part of the [Store Cart API Routes](https://docs.medusajs.com/api/store#carts).\n */\n public lineItems = new LineItemsResource(this.client)\n\n /**\n * Add a shipping method to the cart. The validation of the `data` field is handled by the fulfillment provider of the chosen shipping option.\n * @param {string} cart_id - The ID of the cart to add the shipping method to.\n * @param {StorePostCartsCartShippingMethodReq} payload - The shipping method to add.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.addShippingMethod(cartId, {\n * option_id\n * })\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n addShippingMethod(\n cart_id: string,\n payload: StorePostCartsCartShippingMethodReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/shipping-methods`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Complete a cart and place an order or create a swap, based on the cart's type. This includes attempting to authorize the cart's payment.\n * If authorizing the payment requires more action, the cart will not be completed and the order will not be placed or the swap will not be created.\n * An idempotency key will be generated if none is provided in the header `Idempotency-Key` and added to\n * the response. If an error occurs during cart completion or the request is interrupted for any reason, the cart completion can be retried by passing the idempotency\n * key in the `Idempotency-Key` header.\n * @param {string} cart_id - The ID of the cart to complete.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCompleteCartRes>} Resolves to the completion details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.complete(cartId)\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n complete(\n cart_id: string,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCompleteCartRes> {\n const path = `/store/carts/${cart_id}/complete`\n return this.client.request(\"POST\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Create a Cart. Although optional, specifying the cart's region and sales channel can affect the cart's pricing and\n * the products that can be added to the cart respectively. So, make sure to set those early on and change them if necessary, such as when the customer changes their region.\n * If a customer is logged in, make sure to pass its ID or email within the cart's details so that the cart is attached to the customer.\n * @param {StorePostCartReq} payload - The cart to create.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the created cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.create()\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n create(\n payload?: StorePostCartReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Create Payment Sessions for each of the available Payment Providers in the Cart's Region. If there's only one payment session created,\n * it will be selected by default. The creation of the payment session uses the payment provider and may require sending requests to third-party services.\n * @param {string} cart_id - The ID of the cart to create the payment sessions for.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.createPaymentSessions(cartId)\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n createPaymentSessions(\n cart_id: string,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/payment-sessions`\n return this.client.request(\"POST\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Remove a Discount from a Cart. This only removes the application of the discount, and not completely deletes it. The totals will be re-calculated and the payment sessions\n * will be refreshed after the removal.\n * @param {string} cart_id - the ID of the cart to remove the discount from.\n * @param {string} code - The code of the discount to remove from the cart.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.deleteDiscount(cartId, code)\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n deleteDiscount(\n cart_id: string,\n code: string,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/discounts/${code}`\n return this.client.request(\"DELETE\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Delete a Payment Session in a Cart. May be useful if a payment has failed. The totals will be recalculated.\n * @param {string} cart_id - The ID of the cart to delete the payment session from.\n * @param {string} provider_id - The ID of the payment provider that the session is associated with.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.deletePaymentSession(cartId, \"manual\")\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n deletePaymentSession(\n cart_id: string,\n provider_id: string,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/payment-sessions/${provider_id}`\n return this.client.request(\"DELETE\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Refresh a Payment Session to ensure that it is in sync with the Cart. This is usually not necessary, but is provided for edge cases.\n * @param {string} cart_id - The ID of the cart to refresh its payment session.\n * @param {string} provider_id - The ID of the payment provider that's associated with the payment session.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.refreshPaymentSession(cartId, \"manual\")\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n refreshPaymentSession(\n cart_id: string,\n provider_id: string,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/payment-sessions/${provider_id}/refresh`\n return this.client.request(\"POST\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Retrieve a Cart's details. This includes recalculating its totals.\n * @param {string} cart_id - The cart's ID.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.retrieve(cartId)\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n retrieve(\n cart_id: string,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}`\n return this.client.request(\"GET\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Select the Payment Session that will be used to complete the cart. This is typically used when the customer chooses their preferred payment method during checkout.\n * The totals of the cart will be recalculated.\n * @param {string} cart_id - The cart's ID.\n * @param {StorePostCartsCartPaymentSessionReq} payload - The associated payment provider.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.setPaymentSession(cartId, {\n * provider_id: \"manual\"\n * })\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n setPaymentSession(\n cart_id: string,\n payload: StorePostCartsCartPaymentSessionReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/payment-session`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Update a Cart's details. If the cart has payment sessions and the region was not changed, the payment sessions are updated. The cart's totals are also recalculated.\n * @param {string} cart_id - The cart's ID.\n * @param {StorePostCartsCartReq} payload - The attributes to update in the cart.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.update(cartId, {\n * email: \"user@example.com\"\n * })\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n update(\n cart_id: string,\n payload: StorePostCartsCartReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Update a Payment Session with additional data. This can be useful depending on the payment provider used.\n * All payment sessions are updated and cart totals are recalculated afterwards.\n * @param {string} cart_id - The cart's ID.\n * @param {string} provider_id - The ID of the payment provider that the payment session is associated with.\n * @param {StorePostCartsCartPaymentSessionUpdateReq} payload - The attributes to update in the payment session.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCartsRes>} Resolves to the cart's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.carts.updatePaymentSession(cartId, \"manual\", {\n * data: {\n * \n * }\n * })\n * .then(({ cart }) => {\n * console.log(cart.id);\n * })\n */\n updatePaymentSession(\n cart_id: string,\n provider_id: string,\n payload: StorePostCartsCartPaymentSessionUpdateReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCartsRes> {\n const path = `/store/carts/${cart_id}/payment-sessions/${provider_id}`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n}\n\nexport default CartsResource\n","import {\n StoreCollectionsRes,\n StoreCollectionsListRes,\n StoreGetCollectionsParams,\n} from \"@medusajs/medusa\"\nimport qs from \"qs\"\nimport { ResponsePromise } from \"../typings\"\nimport BaseResource from \"./base\"\n\n/**\n * This class is used to send requests to [Store Product Collection API Routes](https://docs.medusajs.com/api/store#product-collections). All its method\n * are available in the JS Client under the `medusa.collections` property.\n * \n * A product collection is used to organize products for different purposes such as marketing or discount purposes. For example, you can create a Summer Collection.\n * Using the methods in this class, you can list or retrieve a collection's details and products.\n */\nclass CollectionsResource extends BaseResource {\n /**\n * Retrieve a product collection's details.\n * @param {string} id - The ID of the product collection.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCollectionsRes>} Resolves to the collection's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.collections.retrieve(collectionId)\n * .then(({ collection }) => {\n * console.log(collection.id);\n * })\n */\n retrieve(id: string, customHeaders: Record<string, any> = {}): ResponsePromise<StoreCollectionsRes> {\n const path = `/store/collections/${id}`\n return this.client.request(\"GET\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Retrieve a list of product collections. The product collections can be filtered by fields such as `handle` or `created_at` passed in the `query` parameter. \n * The product collections can also be paginated.\n * @param {StoreGetCollectionsParams} query - Filters and pagination configurations to apply on the retrieved product collections.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCollectionsListRes>} Resolves to the list of product collections with pagination fields.\n * \n * @example\n * To list product collections:\n * \n * ```ts\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.collections.list()\n * .then(({ collections, limit, offset, count }) => {\n * console.log(collections.length);\n * })\n * ```\n * \n * By default, only the first `10` records are retrieved. You can control pagination by specifying the `limit` and `offset` properties:\n * \n * ```ts\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.collections.list({\n * limit,\n * offset\n * })\n * .then(({ collections, limit, offset, count }) => {\n * console.log(collections.length);\n * })\n * ```\n */\n list(\n query?: StoreGetCollectionsParams,\n customHeaders: Record<string, any> = {}): ResponsePromise<StoreCollectionsListRes> {\n let path = `/store/collections`\n\n if (query) {\n const queryString = qs.stringify(query)\n path = `/store/collections?${queryString}`\n }\n\n return this.client.request(\"GET\", path, undefined, {}, customHeaders)\n }\n}\n\nexport default CollectionsResource\n","import {\n StoreCustomersListOrdersRes,\n StoreCustomersRes,\n StoreGetCustomersCustomerOrdersParams,\n StorePostCustomersCustomerPasswordTokenReq,\n StorePostCustomersCustomerReq,\n StorePostCustomersReq,\n StorePostCustomersResetPasswordReq,\n} from \"@medusajs/medusa\"\nimport qs from \"qs\"\nimport { ResponsePromise } from \"../typings\"\nimport AddressesResource from \"./addresses\"\nimport BaseResource from \"./base\"\nimport PaymentMethodsResource from \"./payment-methods\"\n\n/**\n * This class is used to send requests to [Store Customer API Routes](https://docs.medusajs.com/api/store#customers_postcustomers). All its method\n * are available in the JS Client under the `medusa.customers` property.\n * \n * A customer can register and manage their information such as addresses, orders, payment methods, and more.\n * \n * Related Guide: [How to implement customer profiles in your storefront](https://docs.medusajs.com/modules/customers/storefront/implement-customer-profiles).\n */\nclass CustomerResource extends BaseResource {\n /**\n * An instance of {@link PaymentMethodsResource} used to send requests to payment-related routes part of the [Store Customer API Routes](https://docs.medusajs.com/api/store#customers_postcustomers).\n */\n public paymentMethods = new PaymentMethodsResource(this.client)\n /**\n * An instance of {@link AddressesResource} used to send requests to address-related routes part of the [Store Customer API Routes](https://docs.medusajs.com/api/store#customers_postcustomers).\n */\n public addresses = new AddressesResource(this.client)\n\n /**\n * Register a new customer. This will also automatically authenticate the customer and set their login session in the response Cookie header.\n * Subsequent requests sent with the JS client are sent with the Cookie session automatically.\n * @param {StorePostCustomersReq} payload - The details of the customer to be created.\n * @param {string} query - Filters and pagination configurations to apply on the retrieved product collections.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns { ResponsePromise<StoreCustomersRes>} Resolves to the created customer's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * medusa.customers.create({\n * first_name: \"Alec\",\n * last_name: \"Reynolds\",\n * email: \"user@example.com\",\n * password: \"supersecret\"\n * })\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n create(\n payload: StorePostCustomersReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCustomersRes> {\n const path = `/store/customers`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Retrieve the logged-in customer's details. This method requires {@link AuthResource.authenticate | customer authentication}.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCustomersRes>} Resolves to the logged-in customer's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * // must be previously logged\n * medusa.customers.retrieve()\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n retrieve(\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCustomersRes> {\n const path = `/store/customers/me`\n return this.client.request(\"GET\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Update the logged-in customer's details. This method requires {@link AuthResource.authenticate | customer authentication}.\n * @param {StorePostCustomersCustomerReq} payload - The attributes to update in the logged-in customer.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCustomersRes>} Resolves to the logged-in customer's details.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * // must be previously logged\n * medusa.customers.update({\n * first_name: \"Laury\"\n * })\n * .then(({ customer }) => {\n * console.log(customer.id);\n * })\n */\n update(\n payload: StorePostCustomersCustomerReq,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCustomersRes> {\n const path = `/store/customers/me`\n return this.client.request(\"POST\", path, payload, {}, customHeaders)\n }\n\n /**\n * Retrieve a list of the logged-in customer's orders. The orders can be filtered by fields such as `status` or `fulfillment_status`. The orders can also be paginated.\n * This method requires {@link AuthResource.authenticate | customer authentication}.\n * @param {StoreGetCustomersCustomerOrdersParams} params - Filters and pagination configurations to apply on the retrieved orders.\n * @param {Record<string, any>} customHeaders - Custom headers to attach to the request.\n * @returns {ResponsePromise<StoreCustomersListOrdersRes>} Resolves to the list of orders with pagination fields.\n * \n * @example\n * import Medusa from \"@medusajs/medusa-js\"\n * const medusa = new Medusa({ baseUrl: MEDUSA_BACKEND_URL, maxRetries: 3 })\n * // must be previously logged\n * medusa.customers.listOrders()\n * .then(({ orders, limit, offset, count }) => {\n * console.log(orders);\n * })\n */\n listOrders(\n params?: StoreGetCustomersCustomerOrdersParams,\n customHeaders: Record<string, any> = {}\n ): ResponsePromise<StoreCustomersListOrdersRes> {\n let path = `/store/customers/me/orders`\n if (params) {\n const query = qs.stringify(params)\n if (query) {\n path += `?${query}`\n }\n }\n return this.client.request(\"GET\", path, undefined, {}, customHeaders)\n }\n\n /**\n * Reset a customer's password using a password token created by a previous request using the {@link generatePasswordToken} method. If the password token expired,\n * you must create a new one.\n * @param {StorePostCustomersResetPasswordReq} payload - The necessary details to reset the password.\n * @param {Record<string, any>} customHeaders - Custom headers t