"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SalesforceConnector = void 0;

var _commercecloudOcapiClient = _interopRequireDefault(require("commercecloud-ocapi-client"));

var _btoa = _interopRequireDefault(require("btoa"));

var errors = _interopRequireWildcard(require("../errors"));

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj["default"] = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

var clean = function clean(obj) {
  Object.keys(obj).forEach(function (key) {
    return (obj[key] === null || obj[key] === undefined) && delete obj[key];
  });
  return obj;
};

var filterAttributeDictionary = {
  categoryId: 'cgid'
  /**
   * This function will take product search request as we use them in the commerce-integrations
   * and output them into a format usable by the specific connector (ocapi).
   *
   * @private
   */

};

var transformProductSearchRequest = function transformProductSearchRequest(_ref) {
  var query = _ref.query,
      count = _ref.count,
      start = _ref.start,
      sort = _ref.sort,
      _ref$filters = _ref.filters,
      filters = _ref$filters === void 0 ? {} : _ref$filters;
  return {
    count: count,
    q: query,
    sort: sort,
    start: start,
    refine: Object.keys(filters).map(function (key) {
      return "".concat(filterAttributeDictionary[key] || key, "=").concat(filters[key]);
    })
  };
};
/**
 * Format a message with the the information from a given Fault object.
 *
 * @param {String} message - the message to be displayed
 * @param {Object} fault a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Fault.html|Fault} fault or {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} error
 *
 * @return {String} Formatted fault message message.
 * @private
 */


var formatFault = function formatFault() {
  var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  var fault = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var seperator = '. ';
  return [message, fault.type, fault.message].filter(function (s) {
    return !!s;
  }).join(seperator);
};
/**
 * Takes a OCAPI Image object and parses it into a commerce-integrations
 * Image type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Image.html|Image} document
 *
 * @return {module:@mobify/commerce-integrations/dist/types.Image}
 */

/* eslint-disable camelcase */


var parseImage = function parseImage(_ref2) {
  var alt = _ref2.alt,
      dis_base_link = _ref2.dis_base_link,
      link = _ref2.link,
      title = _ref2.title;
  return {
    alt: alt,
    description: alt,
    src: dis_base_link || link,
    title: title
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI VariationAttributeValue object and parses it into a commerce-integrations
 * ProductSearchResult type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/VariationAttributeValue.html|VariationAttributeValue} document
 * @return {module:@mobify/commerce-integrations/dist/types.VariationPropertyValue}
 * @private
 */

/* eslint-disable camelcase */


var parseVariationPropertyValue = function parseVariationPropertyValue(_ref3) {
  var image = _ref3.image,
      image_swatch = _ref3.image_swatch,
      name = _ref3.name,
      value = _ref3.value;
  return {
    name: name,
    value: value,
    mainImage: image ? parseImage(image) : undefined,
    swatchImage: image_swatch ? parseImage(image_swatch) : undefined
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI VariationAttribute object and parses it into a commerce-integrations
 * VariationProperty type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/VariationAttribute.html|VariationAttribute} document
 * @return {module:@mobify/commerce-integrations/dist/types.VariationProperty}
 * @private
 */


var parseVariationProperty = function parseVariationProperty(_ref4) {
  var id = _ref4.id,
      name = _ref4.name,
      _ref4$values = _ref4.values,
      values = _ref4$values === void 0 ? [] : _ref4$values;
  return {
    id: id,
    label: name,
    values: values.map(parseVariationPropertyValue)
  };
};
/**
 * Takes a OCAPI ProductSearchHit object and parses it into a commerce-integrations
 * ProductSearchResult type.
 *
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchHit.html|ProductSearchHit} document
 *
 * @returns {module:@mobify/commerce-integrations/dist/types.ProductSearchResult}
 */

/* eslint-disable camelcase */


var parseProductSearchResult = function parseProductSearchResult(_ref5) {
  var product_id = _ref5.product_id,
      product_name = _ref5.product_name,
      image = _ref5.image,
      orderable = _ref5.orderable,
      price = _ref5.price,
      variation_attributes = _ref5.variation_attributes;
  return {
    available: orderable,
    productId: product_id,
    productName: product_name,
    price: price,
    defaultImage: image ? parseImage(image) : undefined,
    variationProperties: variation_attributes ? variation_attributes.map(parseVariationProperty) : []
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI ProductSearchRefinementValue object and parses it into a commerce-integrations
 * FilterValue type.
 *
 * @param {Object} data a OCAPI
 * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchRefinementValue.html|ProductSearchRefinementValue} document
 *
 * @returns {module:@mobify/commerce-integrations/dist/types.FilterValue}
 */

/* eslint-disable camelcase */


var parseFilterValue = function parseFilterValue(_ref6) {
  var hit_count = _ref6.hit_count,
      label = _ref6.label,
      value = _ref6.value;
  return {
    count: hit_count,
    label: label,
    value: value
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI ProductSearchRefinement object and parses it into a commerce-integrations
 * Filter type.
 *
 * @param {Object} data a OCAPI
 * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchRefinement.html|ProductSearchRefinement} document // eslint-disable-line
 *
 * @returns {module:@mobify/commerce-integrations/dist/types.Filter}
 */

/* eslint-disable camelcase */


var parseFilters = function parseFilters(_ref7) {
  var label = _ref7.label,
      attribute_id = _ref7.attribute_id,
      values = _ref7.values;
  return {
    propertyId: attribute_id,
    label: label,
    values: values ? values.map(function (value) {
      return parseFilterValue(value);
    }) : undefined
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI ProductSearchResult object and parses it into a commerce-integrations
 * ProductSearch type.
 *
 * @param {Object} data a OCAPI
 * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchResult.html?cp=0_12_5_96|ProductSearchResult} document // eslint-disable-line
 *
 * @returns {module:@mobify/commerce-integrations/dist/types.ProductSearch}
 */

/* eslint-disable camelcase */


var parseProductSearch = function parseProductSearch(_ref8) {
  var count = _ref8.count,
      _ref8$hits = _ref8.hits,
      hits = _ref8$hits === void 0 ? [] : _ref8$hits,
      query = _ref8.query,
      _ref8$refinements = _ref8.refinements,
      refinements = _ref8$refinements === void 0 ? [] : _ref8$refinements,
      selected_sorting_option = _ref8.selected_sorting_option,
      selected_refinements = _ref8.selected_refinements,
      sorting_options = _ref8.sorting_options,
      start = _ref8.start,
      total = _ref8.total;
  return {
    count: count,
    filters: refinements.map(function (refinement) {
      return parseFilters(refinement);
    }),
    query: query,
    results: hits.map(function (hit) {
      return parseProductSearchResult(hit);
    }),
    selectedFilters: selected_refinements,
    selectedSortingOption: selected_sorting_option,
    sortingOptions: sorting_options,
    start: start,
    total: total
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI Variant object and parses it into a commerce-integrations Variation type.
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Variant.html|Variant} document
 *
 * @returns {Promise<module:@mobify/commerce-integrations/dist/types.Variation>}
 */

/* eslint-disable camelcase */


var parseVariation = function parseVariation(_ref9) {
  var product_id = _ref9.product_id,
      price = _ref9.price,
      orderable = _ref9.orderable,
      variation_values = _ref9.variation_values;
  return {
    id: product_id,
    price: price,
    orderable: orderable,
    values: variation_values
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI ImageGroup object and parses it into a commerce-integrations ImageSet type.
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ImageGroup.html|ImageGroup} document
 *
 * @returns {Promise<module:@mobify/commerce-integrations/dist/types.ImageSet>}
 */

/* eslint-disable camelcase */


var parseImageSet = function parseImageSet(_ref10) {
  var images = _ref10.images,
      view_type = _ref10.view_type,
      variation_attributes = _ref10.variation_attributes;
  return {
    images: images.map(parseImage),
    variationProperties: variation_attributes && variation_attributes.map(parseVariationProperty),
    sizeType: view_type
  };
};
/* eslint-enable camelcase */

/**
 * Takes a OCAPI Product object and parses it into a commerce-integrations Product type.
 * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Product.html|Product} document
 *
 * @returns {Promise<module:@mobify/commerce-integrations/dist/types.Product>}
 */

/* eslint-disable camelcase */


var _parseProduct = function parseProduct(_ref11) {
  var id = _ref11.id,
      _ref11$image_groups = _ref11.image_groups,
      image_groups = _ref11$image_groups === void 0 ? [] : _ref11$image_groups,
      name = _ref11.name,
      long_description = _ref11.long_description,
      primary_category_id = _ref11.primary_category_id,
      brand = _ref11.brand,
      min_order_quantity = _ref11.min_order_quantity,
      step_quantity = _ref11.step_quantity,
      upc = _ref11.upc,
      unit = _ref11.unit,
      price = _ref11.price,
      prices = _ref11.prices,
      _ref11$variants = _ref11.variants,
      variants = _ref11$variants === void 0 ? [] : _ref11$variants,
      _ref11$variation_attr = _ref11.variation_attributes,
      variation_attributes = _ref11$variation_attr === void 0 ? [] : _ref11$variation_attr,
      _ref11$variation_valu = _ref11.variation_values,
      variation_values = _ref11$variation_valu === void 0 ? {} : _ref11$variation_valu;
  return {
    id: id,
    name: name,
    imageSets: image_groups.map(parseImageSet),
    description: long_description,
    categoryId: primary_category_id,
    brand: brand,
    minimumOrderQuantity: min_order_quantity,
    stepQuantity: step_quantity,
    upc: upc,
    unit: unit,
    price: price,
    prices: prices,
    variations: variants.map(parseVariation),
    variationProperties: variation_attributes.map(parseVariationProperty),
    variationValues: variation_values
  };
};
/* eslint-enable camelcase */

/* eslint-disable camelcase */


var _parseCustomer = function parseCustomer(_ref12) {
  var customer_id = _ref12.customer_id,
      first_name = _ref12.first_name,
      last_name = _ref12.last_name,
      email = _ref12.email;
  return {
    id: customer_id,
    firstName: first_name,
    lastName: last_name,
    email: email
  };
};
/* eslint-enable camelcase */


var transformOrderAddress = function transformOrderAddress(shippingAddress) {
  return {
    first_name: shippingAddress.firstName,
    last_name: shippingAddress.lastName,
    phone: shippingAddress.phone,
    address1: shippingAddress.addressLine1,
    address2: shippingAddress.addressLine2,
    country_code: shippingAddress.countryCode,
    state_code: shippingAddress.stateCode,
    city: shippingAddress.city,
    postal_code: shippingAddress.postalCode
  };
};

var transformPayment = function transformPayment(payment) {
  return {
    amount: payment.amount,
    payment_card: {
      issue_number: payment.details.number,
      security_code: payment.details.ccv,
      holder: payment.details.holderName,
      card_type: payment.details.type,
      expiration_month: payment.details.expiryMonth,
      expiration_year: payment.details.expiryYear
    },
    payment_method_id: payment.methodId
  };
};

var transformShippingMethod = function transformShippingMethod(shippingMethod) {
  return {
    id: shippingMethod.id
  };
};

var transformCustomerInformation = function transformCustomerInformation(customerInfo) {
  return {
    customer_id: customerInfo.id,
    email: customerInfo.email
  };
};

var transformCartItem = function transformCartItem(cartItem) {
  return {
    product_id: cartItem.productId,
    quantity: cartItem.quantity
  };
};

var transformCart = function transformCart(cart) {
  var transformedCart = {};
  var billingAddress = cart.billingAddress,
      customerInfo = cart.customerInfo,
      items = cart.items,
      payments = cart.payments,
      shippingAddress = cart.shippingAddress; // Transform our mobify api schema to salesforce ocapi schema

  if (billingAddress) {
    transformedCart.billing_address = transformOrderAddress(billingAddress);
  }

  if (customerInfo) {
    transformedCart.customer_info = transformCustomerInformation(customerInfo);
  }

  if (items) {
    transformedCart.product_items = items.map(transformCartItem);
  }

  if (payments) {
    transformedCart.payment_instruments = payments.map(transformPayment);
  }

  if (shippingAddress) {
    transformedCart.shipments = [{
      shipment_id: 'me',
      shipping_address: transformOrderAddress(shippingAddress)
    }];
  }

  return transformedCart;
};
/**
 * A Commerce Integrations connector for Salesforce B2C Commerce backends.
 *
 * @implements {module:@mobify/commerce-integrations/dist/connectors/interfaces.CommerceConnector}
 * @implements {module:@mobify/commerce-integrations/dist/connectors/interfaces.ParserHooks}
 */


var SalesforceConnector =
/*#__PURE__*/
function () {
  /**
   * @param client {ShopApi.ApiClient}
   */
  function SalesforceConnector(client) {
    _classCallCheck(this, SalesforceConnector);

    this.client = client;
  }
  /**
   * Given a configuration in the form of a plain object, this method returns
   * a new SalesforceConnector instance.
   *
   * @param {Object} config {@link https://github.com/mobify/commercecloud-ocapi-client/blob/develop/src/ApiClient.js#L44}
   * @returns {module:@mobify/commerce-integrations/dist/connectors/sfcc.SalesforceConnector} The new SalesforceConnector instance.
   */


  _createClass(SalesforceConnector, [{
    key: "createCart",

    /**
     * @inheritDoc
     */
    value: function createCart(oldCart) {
      var _this = this;

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      var options = {}; // Append the cart to the body.

      if (oldCart) {
        options.body = transformCart(oldCart);
      }

      return api.postBaskets(options).then(function (data) {
        return _this.parseCart(data);
      })["catch"](function () {
        throw new errors.ServerError('Could Not Create Cart');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getCart",
    value: function getCart(cartId) {
      var _this2 = this;

      if (!cartId) {
        throw new errors.InvalidArgumentError("Parameter 'cartId' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      return api.getBasketsByID(cartId).then(function (data) {
        return _this2.parseCart(data);
      })["catch"](function () {
        throw new errors.NotFoundError('Cart Not Found');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "deleteCart",
    value: function deleteCart(cartId) {
      if (!cartId) {
        throw new errors.InvalidArgumentError("Parameter 'cartId' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      return api.deleteBasketsByID(cartId)["catch"](function () {
        throw new errors.ServerError('Could Not Delete Cart');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "addCartItem",
    value: function addCartItem(cart, cartItem) {
      var _this3 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!cartItem) {
        throw new errors.InvalidArgumentError("Parameter 'cartItem' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client); // eslint-disable-next-line no-undef

      cartItem = transformCartItem(cartItem);
      return api.postBasketsByIDItems(cart.id, [cartItem]).then(function (data) {
        return _this3.parseCart(data);
      })["catch"](function () {
        throw new errors.ServerError('Could Not Add Cart Item');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "removeCartItem",
    value: function removeCartItem(cart, cartItemId) {
      var _this4 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!cartItemId) {
        throw new errors.InvalidArgumentError("Parameter 'cartItemId' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      return api.deleteBasketsByIDItemsByID(cart.id, cartItemId).then(function (data) {
        return _this4.parseCart(data);
      })["catch"](function () {
        throw new errors.ServerError('Could Not Remove Cart');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "updateCartItem",
    value: function updateCartItem(cart, cartItem) {
      var _this5 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!cartItem) {
        throw new errors.InvalidArgumentError("Parameter 'cartItem' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      var cartItemId = cartItem.id; // eslint-disable-next-line no-undef

      cartItem = transformCartItem(cartItem);
      return api.patchBasketsByIDItemsByID(cart.id, cartItemId, cartItem).then(function (data) {
        return _this5.parseCart(data);
      })["catch"](function () {
        throw new errors.ServerError('Could Not Update Cart');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "setShippingAddress",
    value: function setShippingAddress(cart, shippingAddress) {
      var _this6 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!shippingAddress) {
        throw new errors.InvalidArgumentError("Parameter 'shippingAddress' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client); // Transform Mobify schema into OCAPI schema
      // eslint-disable-next-line no-undef

      shippingAddress = transformOrderAddress(shippingAddress);
      return api.putBasketsByIDShipmentsByIDShippingAddress(cart.id, 'me', shippingAddress).then(function (data) {
        return _this6.parseCart(data);
      })["catch"](function () {
        throw new errors.ServerError('Could Not Set Shipping Address');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "setBillingAddress",
    value: function setBillingAddress(cart, billingAddress) {
      var _this7 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!billingAddress) {
        throw new errors.InvalidArgumentError("Parameter 'billingAddress' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client); // Transform Mobify schema into OCAPI schema
      // eslint-disable-next-line no-undef

      billingAddress = transformOrderAddress(billingAddress);
      return api.putBasketsByIDBillingAddress(cart.id, {
        body: billingAddress
      }).then(function (data) {
        return _this7.parseCart(data);
      })["catch"](function () {
        throw new errors.ServerError('Could Not Set Billing Address');
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "setPayment",
    value: function setPayment(cart, payment) {
      var _this8 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!payment) {
        throw new errors.InvalidArgumentError("Parameter 'payment' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client); // Only allow one payment of a given type. If there is already a type in the cart,
      // then get it's id so we can `patch` it.

      var _cart$payments = cart.payments,
          payments = _cart$payments === void 0 ? [] : _cart$payments;
      var oldPayment = payments.find(function (_ref13) {
        var methodId = _ref13.methodId;
        return methodId === payment.methodId;
      }); // Transform Mobify schema into OCAPI schema
      // eslint-disable-next-line no-undef

      payment = transformPayment(payment);
      var request = !oldPayment ? api.postBasketsByIDPaymentInstruments(cart.id, payment) : api.patchBasketsByIDPaymentInstrumentsByID(cart.id, oldPayment.id, payment);
      return request.then(function (data) {
        return _this8.parseCart(data);
      })["catch"](function () {
        throw new errors.ServerError('Could Not Add Payment');
      });
    }
    /**
     * Register a new customer account and login.
     *
     * @param {module:@mobify/commerce-integrations/dist/types.CustomerRegistration} data
     * @return {Promise<module:@mobify/commerce-integrations/dist/types.Customer>}
     */

  }, {
    key: "registerCustomer",
    value: function registerCustomer(data) {
      var _this9 = this;

      var body = {
        password: data.password,
        customer: {
          first_name: data.firstName,
          last_name: data.lastName,
          login: data.email,
          email: data.email
        }
      };
      var api = new _commercecloudOcapiClient["default"].CustomersApi(this.client);
      return api.postCustomers(body).then(function () {
        return _this9.login(data.email, data.password);
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "login",
    value: function login(username, password) {
      var _this10 = this;

      var type = username && password ? 'credentials' : 'guest';
      var api = new _commercecloudOcapiClient["default"].CustomersApi(this.client);
      var authParam = type === 'credentials' ? {
        authorization: "Basic ".concat((0, _btoa["default"])("".concat(username, ":").concat(password)))
      } : undefined; // Clear authorization from previous login

      delete api.apiClient.defaultHeaders.authorization;
      return api.postCustomersAuth({
        type: type
      }, authParam).then(function (data) {
        return _this10.parseCustomer(data);
      })["catch"](function (fault) {
        throw new errors.ForbiddenError(formatFault('Login error', fault));
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "logout",
    value: function logout() {
      var api = new _commercecloudOcapiClient["default"].CustomersApi(this.client);
      return api.deleteCustomersAuth().then(function () {
        // Clear authorization from current login
        delete api.apiClient.defaultHeaders.authorization;
        return undefined;
      })["catch"](function (fault) {
        throw new errors.ServerError(formatFault('Logout error', fault));
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getShippingMethods",
    value: function getShippingMethods(cart) {
      var _this11 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      return api.getBasketsByIDShipmentsByIDShippingMethods(cart.id, 'me') // eslint-disable-next-line camelcase
      .then(function (_ref14) {
        var _ref14$applicable_shi = _ref14.applicable_shipping_methods,
            applicable_shipping_methods = _ref14$applicable_shi === void 0 ? [] : _ref14$applicable_shi;
        return applicable_shipping_methods.map(_this11.parseShippingMethod);
      })["catch"](function (fault) {
        throw new errors.ServerError(formatFault('Could Not Get Shipping Methods', fault));
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "refreshSession",
    value: function refreshSession() {
      var _this12 = this;

      var api = new _commercecloudOcapiClient["default"].CustomersApi(this.client);
      return api.postCustomersAuth({
        type: 'refresh'
      }).then(function (data) {
        return _this12.parseCustomer(data);
      })["catch"](function (fault) {
        throw new errors.ForbiddenError(formatFault('Unable to refresh session', fault));
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getPaymentMethods",
    value: function getPaymentMethods(cart) {
      var _this13 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      return api.getBasketsByIDPaymentMethods(cart.id, 'me') // eslint-disable-next-line camelcase
      .then(function (_ref15) {
        var _ref15$applicable_pay = _ref15.applicable_payment_methods,
            applicable_payment_methods = _ref15$applicable_pay === void 0 ? [] : _ref15$applicable_pay;
        return applicable_payment_methods.map(_this13.parsePaymentMethod);
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "setShippingMethod",
    value: function setShippingMethod(cart, shippingMethod) {
      var _this14 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!shippingMethod) {
        throw new errors.InvalidArgumentError("Parameter 'shippingMethod' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client); // Transform Mobify schema into OCAPI schema
      // eslint-disable-next-line no-undef

      shippingMethod = transformShippingMethod(shippingMethod);
      return api.putBasketsByIDShipmentsByIDShippingMethod(cart.id, 'me', shippingMethod).then(function (data) {
        return _this14.parseCart(data);
      })["catch"](function (fault) {
        throw new errors.ServerError(formatFault('Could Not Set Shipping Method', fault));
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "setCustomerInformation",
    value: function setCustomerInformation(cart, customerInformation) {
      var _this15 = this;

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!customerInformation) {
        throw new errors.InvalidArgumentError("Parameter 'customerInformation' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client); // Transform Mobify schema into OCAPI schema
      // eslint-disable-next-line no-undef

      customerInformation = transformCustomerInformation(customerInformation);
      return api.putBasketsByIDCustomer(cart.id, customerInformation).then(function (data) {
        return _this15.parseCart(data);
      });
    }
    /**
     * Parse a cart item
     */

  }, {
    key: "parseCartItem",
    value: function parseCartItem(data) {
      return {
        id: data.item_id,
        baseItemPrice: data.base_price,
        baseLinePrice: data.base_price * data.quantity,
        productId: data.product_id,
        productName: data.product_name,
        quantity: data.quantity,
        itemPrice: data.price_after_order_discount / data.quantity,
        linePrice: data.price_after_order_discount
      };
    }
    /**
     * Parse a coupon item
     */

  }, {
    key: "parseCouponEntry",
    value: function parseCouponEntry(data) {
      return {
        id: data.coupon_item_id,
        code: data.code
      };
    }
    /**
     * Parse an order address
     */

  }, {
    key: "parseOrderAddress",
    value: function parseOrderAddress(data) {
      return {
        firstName: data.first_name,
        lastName: data.last_name,
        phone: data.phone,
        addressLine1: data.address1,
        addressLine2: data.address2,
        city: data.city,
        countryCode: data.country_code,
        stateCode: data.state_code,
        postalCode: data.postal_code
      };
    }
    /**
     * Parse customer information
     */

  }, {
    key: "parseCustomerInformation",
    value: function parseCustomerInformation(data) {
      return {
        id: data.customer_id,
        email: data.email || undefined
      };
    }
    /**
     * Parse a shipping method
     */

  }, {
    key: "parseShippingMethod",
    value: function parseShippingMethod(data) {
      return {
        id: data.id,
        cost: data.price,
        label: "".concat(data.name, " - ").concat(data.description)
      };
    }
    /**
     * Parse a payment method
     */

  }, {
    key: "parsePaymentMethod",
    value: function parsePaymentMethod(data) {
      var cards = data.cards;
      var method = {
        id: data.id,
        name: data.name
      };

      if (cards) {
        method.types = cards.map(function (card) {
          return {
            id: card.card_type,
            name: card.name
          };
        });
      }

      return method;
    }
    /**
     * Parse a payment.
     */

  }, {
    key: "parsePayment",
    value: function parsePayment(data) {
      return {
        id: data.payment_instrument_id,
        amount: data.amount,
        methodId: data.payment_method_id,
        details: {
          type: data.payment_card.card_type,
          expiryMonth: data.payment_card.expiration_month,
          expiryYear: data.payment_card.expiration_year,
          holderName: data.payment_card.holder,
          number: data.payment_card.issue_number,
          maskedNumber: data.payment_card.masked_number
        }
      };
    }
    /**
     * Parse a cart
     */

  }, {
    key: "parseCart",
    value: function parseCart(data) {
      /* eslint-disable camelcase */
      var billing_address = data.billing_address,
          _data$shipments = data.shipments,
          shipments = _data$shipments === void 0 ? [] : _data$shipments,
          _data$coupon_items = data.coupon_items,
          coupon_items = _data$coupon_items === void 0 ? [] : _data$coupon_items,
          _data$payment_instrum = data.payment_instruments,
          payment_instruments = _data$payment_instrum === void 0 ? [] : _data$payment_instrum,
          _data$product_items = data.product_items,
          product_items = _data$product_items === void 0 ? [] : _data$product_items,
          customer_info = data.customer_info;
      var shippingAddress;
      var selectedShippingMethodId;
      var shipment = shipments.length ? shipments[0] : undefined;

      if (shipment) {
        shippingAddress = shipment.shipping_address ? this.parseOrderAddress(shipment.shipping_address) : undefined;
        selectedShippingMethodId = shipment.shipping_method ? shipment.shipping_method.id : undefined;
      }

      var billingAddress = billing_address ? this.parseOrderAddress(billing_address) : undefined;
      var payments = payment_instruments.map(this.parsePayment);
      var items = product_items.map(this.parseCartItem);
      var couponEntries = coupon_items.map(this.parseCouponEntry);

      var parseNumberValue = function parseNumberValue(value) {
        return value !== null ? value : undefined;
      };

      var id = data.basket_id;
      var customerInfo = customer_info ? this.parseCustomerInformation(customer_info) : undefined;
      var subtotal = parseNumberValue(data.product_sub_total);
      var discounts = (data.order_price_adjustments || []).reduce(function (acc, curr) {
        return acc + curr.price;
      }, 0);
      var shipping = parseNumberValue(data.shipping_total);
      var tax = parseNumberValue(data.tax_total || data.merchandize_total_tax);
      var total = parseNumberValue(data.order_total || data.product_total);
      return {
        id: id,
        discounts: discounts,
        billingAddress: billingAddress,
        couponEntries: couponEntries,
        customerInfo: customerInfo,
        items: items,
        payments: payments,
        shippingAddress: shippingAddress,
        selectedShippingMethodId: selectedShippingMethodId,
        shipping: shipping,
        subtotal: subtotal,
        tax: tax,
        total: total
        /* eslint-enable camelcase */

      };
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getDefaultHeaders",
    value: function getDefaultHeaders() {
      return Object.assign({}, this.client.defaultHeaders);
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "setDefaultHeaders",
    value: function setDefaultHeaders(headers) {
      this.client.defaultHeaders = Object.assign({}, headers);
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getCustomer",
    value: function getCustomer(id, opts) {
      var _this16 = this;

      var api = new _commercecloudOcapiClient["default"].CustomersApi(this.client);
      var defaultOptions = {
        expand: ['addresses', 'paymentinstruments'],
        allImages: true
      };

      var options = _objectSpread({}, defaultOptions, {}, opts);

      return api.getCustomersByID(id, options).then(function (data) {
        return _this16.parseCustomer(data);
      });
    }
    /**
     * Takes a OCAPI Customer object and parses it into a commerce-integrations Customer type.
     * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Customer.html|Customer} document
     *
     * @returns {Promise<module:@mobify/commerce-integrations/dist/types.Customer>}
     */

  }, {
    key: "parseCustomer",
    value: function parseCustomer(data) {
      return _parseCustomer(data);
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getProduct",
    value: function getProduct(id) {
      var _this17 = this;

      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var api = new _commercecloudOcapiClient["default"].ProductsApi(this.client);
      var defaultOptions = {
        expand: ['availability', 'prices', 'variations', 'images'],
        allImages: true
      };

      var options = _objectSpread({}, defaultOptions, {}, opts);

      return api.getProductsByID(id, options).then(function (data) {
        return _this17.parseProduct(data);
      })["catch"](function (fault) {
        throw new errors.NotFoundError(formatFault('Product Not Found', fault));
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getProducts",
    value: function getProducts(ids) {
      var _this18 = this;

      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (!ids || ids.length <= 0) {
        throw new Error('Please specify list of product ids to get.');
      }

      var api = new _commercecloudOcapiClient["default"].ProductsApi(this.client);
      var defaultOptions = {
        expand: ['availability', 'prices', 'variations', 'images'],
        allImages: true
      };

      var options = _objectSpread({}, defaultOptions, {}, opts);

      return api.getProductsByIDs(ids, options).then(function (_ref16) {
        var count = _ref16.count,
            _ref16$data = _ref16.data,
            data = _ref16$data === void 0 ? [] : _ref16$data,
            total = _ref16.total;
        return {
          count: count,
          data: data.map(_this18.parseProduct),
          total: total
        };
      });
    }
    /**
     * Takes a OCAPI Product object and parses it into a commerce-integrations Product type.
     * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Product.html|Product} document
     *
     * @returns {Promise<module:@mobify/commerce-integrations/dist/types.Product>}
     */

  }, {
    key: "parseProduct",
    value: function parseProduct(data) {
      return _parseProduct(data);
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "searchProducts",
    value: function searchProducts(productSearchRequest) {
      var _this19 = this;

      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var searchRequest = transformProductSearchRequest(productSearchRequest);
      var api = new _commercecloudOcapiClient["default"].ProductSearchApi(this.client);
      var defaultOptions = {
        expand: ['availability', 'prices', 'variations', 'images'] // Assign options to new object. This allows the user to override
        // and defaults we set.

      };
      searchRequest = _objectSpread({}, searchRequest, {}, defaultOptions, {}, opts);
      return api.getProductSearch(searchRequest).then(function (data) {
        return _this19.parseSearchProducts(data, searchRequest);
      });
    }
    /**
     * Takes a OCAPI ProductSearchResult object and parses it into a commerce-integrations
     * ProductSearch type.
     *
     * @param {Object} data a OCAPI
     * {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/ProductSearchResult.html?cp=0_12_5_96|ProductSearchResult} document
     *
     * @returns {Promise<module:@mobify/commerce-integrations/dist/types.ProductSearch>}
     */

  }, {
    key: "parseSearchProducts",
    value: function parseSearchProducts(data, searchParams) {
      return parseProductSearch(data, searchParams);
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getStore",
    value: function getStore(id) {
      var _this20 = this;

      var api = new _commercecloudOcapiClient["default"].StoresApi(this.client);
      return api.getStoresByID(id).then(function (data) {
        return _this20.parseGetStore(data);
      });
    }
    /**
     * Takes a OCAPI Store object and parses it into a commerce-integrations Store type.
     * @param {Object} data a OCAPI {@link https://documentation.demandware.com/DOC1/topic/com.demandware.dochelp/OCAPI/18.3/shop/Documents/Store.html|Store} document
     *
     * @returns {Promise<module:@mobify/commerce-integrations/dist/types.Store>}
     */

  }, {
    key: "parseGetStore",
    value: function parseGetStore(data) {
      var d = data;
      return {
        addressLine1: d.address1,
        addressLine2: d.address2,
        city: d.city,
        country: d.country_code,
        email: d.email,
        id: d.id,
        name: d.name,
        phone: d.phone ? d.phone.replace(new RegExp('[(]|[)]|[.]|[ ]|[-]|[#]|[x]', 'g'), '') : undefined,
        postalCode: d.postal_code,
        hours: d.store_hours,
        images: d.image ? {
          src: d.image,
          alt: d.name
        } : undefined
      };
    }
    /**
     * This function will take product search request as we use them in the commerce-integrations
     * and output them into a format usable by the specific connector (ocapi).
     */

  }, {
    key: "transformSearchStoreParams",
    value: function transformSearchStoreParams(searchParams) {
      var sp = searchParams;
      return {
        count: sp.count > 0 ? sp.count : 20,
        start: sp.start > 0 ? sp.start : 0,
        distanceUnit: 'km',
        // only 'mi' and 'km' supported
        latitude: sp.latlon.latitude,
        longitude: sp.latlon.longitude
      };
    }
    /**
     * @inheritDoc
     */
    // eslint-disable-next-line no-unused-vars

  }, {
    key: "searchStores",
    value: function searchStores(storeSearchRequest) {
      var _this21 = this;

      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (isNaN(storeSearchRequest.latlon.latitude) || isNaN(storeSearchRequest.latlon.longitude)) {
        throw new Error('Provide Latitude and Longitude coordinates');
      }

      var api = new _commercecloudOcapiClient["default"].StoresApi(this.client);
      var searchRequest = this.transformSearchStoreParams(storeSearchRequest);
      return api.getStores(searchRequest).then(function (data) {
        return _this21.parseSearchStores(data);
      });
    }
  }, {
    key: "parseSearchStores",
    value: function parseSearchStores(data) {
      var _this22 = this;

      var d = data;
      return {
        count: d.count,
        start: d.start,
        total: d.total,
        stores: d.data ? d.data.map(function (store) {
          return _this22.parseGetStore(store);
        }) : undefined
      };
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getCategory",
    value: function getCategory(id) {
      var _this23 = this;

      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var api = new _commercecloudOcapiClient["default"].CategoriesApi(this.client);
      return api.getCategoriesByID(id, options).then(function (data) {
        return _this23.parseCategory(data);
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "getCategories",
    value: function getCategories(ids) {
      var _this24 = this;

      var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var api = new _commercecloudOcapiClient["default"].CategoriesApi(this.client);
      return api.getCategoriesByIDs(ids, options).then(function (_ref17) {
        var data = _ref17.data,
            count = _ref17.count,
            total = _ref17.total;
        return {
          data: _this24.parseCategories(data),
          count: count,
          total: total
        };
      });
    }
    /**
     * Takes an array of OCAPI Category objects and parses it into an
     * commerce-integrations Category type.
     * @param {Object[]} categories an array of OCAPI {@link https://mobify.github.io/commercecloud-ocapi-client/module-models_Category.html|Category} document
     *
     * @returns {Array<module:@mobify/commerce-integrations/dist/types.Category>}
     */

  }, {
    key: "parseCategories",
    value: function parseCategories(categories) {
      var _this25 = this;

      return categories.map(function (c) {
        return _this25.parseCategory(c);
      });
    }
    /**
     * Takes a OCAPI Category objects and parses it into an
     * commerce-integrations Category type.
     * @param {Object[]} categories an OCAPI {@link https://mobify.github.io/commercecloud-ocapi-client/module-models_Category.html|Category} document
     *
     * @returns {module:@mobify/commerce-integrations/dist/types.Category}
     */

    /* eslint-disable camelcase */

  }, {
    key: "parseCategory",
    value: function parseCategory(_ref18) {
      var id = _ref18.id,
          name = _ref18.name,
          page_description = _ref18.page_description,
          subCategories = _ref18.categories,
          backgroundImage = _ref18.image,
          thumbnailImage = _ref18.thumbnail;
      var imageAttributes = {
        alt: name,
        description: page_description,
        title: name
      };
      var category = {
        id: id,
        name: name,
        description: page_description,
        thumbnailImage: thumbnailImage && this.parseImage(thumbnailImage, imageAttributes),
        backgroundImage: backgroundImage && this.parseImage(backgroundImage, imageAttributes)
      };

      if (subCategories) {
        category.categories = this.parseCategories(subCategories);
      }

      return clean(category);
    }
    /* eslint-enable camelcase */

    /**
     * Takes an image url and its attributes and return an
     * commerce-integrations Image type.
     * @param {string} imageUrl
     * @param {Object} attributes additional attributes of an image
     *
     * @returns {Promise<module:@mobify/commerce-integrations/dist/types.Image>}
     */

  }, {
    key: "parseImage",
    value: function parseImage(imageUrl, attributes) {
      return _objectSpread({}, attributes, {
        src: imageUrl
      });
    }
    /**
     * @inheritDoc
     */

  }, {
    key: "parseOrder",
    value: function parseOrder(data) {
      var order = this.parseCart(data);
      return _objectSpread({}, order, {
        creationDate: new Date(data.creation_date),
        id: data.order_no,
        status: data.shipping_status
      });
    }
    /**
     * Create a new order using a given cart. This command will trigger the appropriate
     * OCAPI order authorization hooks. If orders placed through this command aren't progressing
     * from the `created` status, it's possible that your API hooks haven't been set up. Please
     * consult your Saleforce professional.
     * @param {module:@mobify/commerce-integrations/dist/types.Cart} cart The customer's cart.
     * @param {Object} opts
     * @return {Promise<module:@mobify/commerce-integrations/dist/types.Order>}
     */
    // eslint-disable-next-line no-unused-vars

  }, {
    key: "createOrder",
    value: function createOrder(cart) {
      var _this26 = this;

      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      var api = new _commercecloudOcapiClient["default"].OrdersApi(this.client); // OCAPI only requires that you pass in the id of the basket, so we don't need
      // a complex transformation here.

      return api.postOrders({
        basket_id: cart.id
      }).then(function (data) {
        // The OCAPI backend doesn't like having this value defined, so let's remove it.
        delete data.payment_instruments[0].payment_card.credit_card_expired; // To ensure that the OCAPI backend triggers the payment authorization hook, we have
        // to either update the order payment intruments or add one. He you can see we are just
        // re-submitting the payments after it's creation.

        return api.patchOrdersByIDPaymentInstrumentsByID(data.order_no, data.payment_instruments[0].payment_instrument_id, {
          amount: data.payment_instruments[0].amount,
          payment_card: data.payment_instruments[0].payment_card,
          payment_method_id: data.payment_instruments[0].payment_method_id
        });
      }).then(function (data) {
        return _this26.parseOrder(data);
      });
    }
    /**
     * @inheritDoc
     */
    // eslint-disable-next-line no-unused-vars

  }, {
    key: "getOrder",
    value: function getOrder(id) {
      var _this27 = this;

      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (!id) {
        throw new errors.InvalidArgumentError("Parameter 'id' is required");
      }

      var api = new _commercecloudOcapiClient["default"].OrdersApi(this.client); // OCAPI only requires that you pass in the id of the basket, so we don't need
      // a complex transformation here.

      return api.getOrdersByID(id).then(function (data) {
        return _this27.parseOrder(data);
      })["catch"](function (fault) {
        throw new errors.NotFoundError(formatFault('Order Not Found', fault));
      });
    }
    /**
     * @inheritDoc
     */
    // eslint-disable-next-line no-unused-vars

  }, {
    key: "getOrders",
    value: function getOrders(ids) {
      var _this28 = this;

      var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

      if (!ids || ids.length <= 0) {
        throw new errors.InvalidArgumentError("Parameter 'ids' is required");
      }

      var getOrderPromises = ids.map(function (id) {
        return _this28.getOrder(id, opts)["catch"](function () {
          return null;
        });
      });
      return Promise.all(getOrderPromises).then(function (orders) {
        var validOrders = orders.filter(function (order) {
          return !!order;
        });
        return {
          count: validOrders.length,
          data: validOrders,
          total: validOrders.length
        };
      });
    }
    /**
     * @inheritDoc
     */
    // eslint-disable-next-line no-unused-vars

  }, {
    key: "addCouponEntry",
    value: function addCouponEntry(cart, couponCode) {
      var _this29 = this;

      var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!couponCode) {
        throw new errors.InvalidArgumentError("Parameter 'couponCode' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      return api.postBasketsByIDCoupons(cart.id, {
        code: couponCode
      }).then(function (data) {
        return _this29.parseCart(data);
      })["catch"](function (fault) {
        throw new errors.ServerError(formatFault('Could Not Add Coupon', fault));
      });
    }
    /**
     * @inheritDoc
     */
    // eslint-disable-next-line no-unused-vars

  }, {
    key: "removeCouponEntry",
    value: function removeCouponEntry(cart, couponEntryId) {
      var _this30 = this;

      var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      if (!cart) {
        throw new errors.InvalidArgumentError("Parameter 'cart' is required");
      }

      if (!couponEntryId) {
        throw new errors.InvalidArgumentError("Parameter 'couponEntryId' is required");
      }

      var api = new _commercecloudOcapiClient["default"].BasketsApi(this.client);
      return api.deleteBasketsByIDCouponsByID(cart.id, couponEntryId).then(function (data) {
        return _this30.parseCart(data);
      })["catch"](function (fault) {
        throw new errors.ServerError(formatFault('Could Not Remove Coupon', fault));
      });
    }
  }], [{
    key: "fromConfig",
    value: function fromConfig(config) {
      return new this.prototype.constructor(new _commercecloudOcapiClient["default"].ApiClient(config));
    }
  }]);

  return SalesforceConnector;
}();

exports.SalesforceConnector = SalesforceConnector;